将networkx图形另存为pdf时不同的边宽

时间:2020-07-28 19:18:43

标签: python matplotlib networkx

问题::我想以矢量化格式(例如,以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图像?

0 个答案:

没有答案