首页 > 解决方案 > 将networkx图保存为pdf时的不同边宽

问题描述

问题:我想以矢量化格式(例如 pdf)保存 networkx 图,但这不能保留预期的边缘宽度。

示例:考虑以下代码段:

import networkx
import matplotlib.pyplot as plt
import numpy as np

# Define graph
G = nx.Graph()
for i in range(10):
    for j in range(10):
        weight = 1
        if i != j:
            if np.random.rand() < 0.7:
                weight = 0.01
            else:
                weight = 0.5*np.random.rand()
        G.add_edge('A{}'.format(i), 'B{}'.format(j), weight=weight)

# Plot graph
plt.figure(figsize=(7, 7))
left_nodes, right_nodes = nx.bipartite.sets(G)
pos = dict()
pos.update((n, (1, i)) for i, n in enumerate(left_nodes))
pos.update((n, (2, i)) for i, n in enumerate(right_nodes))
weights = [G[u][v]['weight'] for u, v in G.edges()]
color_map = ['lightblue' if n.startswith('A') else 'orange' for n in G]
nx.draw(G, 
        pos=pos,
        width=weights,
        node_color=color_map,
        node_size=1000,
        with_labels = True)
plt.savefig('test.png', bbox_inches='tight');

这会将以下图像保存为test.png

相反,当我使用可缩放矢量格式(例如,将图像另存为test.pdf)时,输出为:

这不会保留预期的边缘宽度。如何以矢量格式保存绘图,使其看起来像 .png 图像?

标签: pythonmatplotlibnetworkx

解决方案


推荐阅读