Skip to main content
 首页 » 编程设计

python之Networkx 图在不同平台上的大小不同

2025年01月19日11bonelee

我有一个绘制图表的简短代码:

plt.figure(figsize=(15,15),dpi=300) 
ax = plt.subplot(111) 
nd = nx.draw_networkx_nodes(G, pos, node_color=node_cols, linewidths=1, node_size=node_sizes) 
nd.set_edgecolor('w') #<- set the edgecolor to red on the node markers 
nx.draw_networkx_edges(G, pos, edge_color=edge_cols,width=edge_sizes) 
nx.draw_networkx_labels(G, pos, labels, font_size=fs, font_weight='bold') 
plt.tick_params( 
    axis='both',          # changes apply to both axes 
    which='both',      # both major and minor ticks are affected 
    bottom='off',      # ticks along the bottom edge are off 
    top='off',         # ticks along the top edge are off 
    labelbottom='off', # labels along the bottom edge are off 
    left='off', 
    labelleft='off') 
#plt.show() 
plt.savefig('foo.pdf') 

在我的 Mac 上的 iPython notebook 上运行时和在 Windows 上从 pycharm 运行时大小不同。有办法解决吗?我如何有意识地指定 edge_sizes 和 node_sizes? 谢谢!

请您参考如下方法:

jupyter notebook 中 matplotlib 图形的默认图形大小和 dpi 与通常的脚本不同。

你可以通过

import matplotlib.pyplot as plt 
print(plt.rcParams["figure.figsize"]) 
print(plt.rcParams["figure.dpi"]) 

对于 jupyter notebook 应该打印 [6.0, 4.0] 72.0,对于脚本应该打印 [6.4, 4.8] 100.0。

为了设置这些参数,要么使用

plt.rcParams["figure.figsize"] = 6,4 
plt.rcParams["figure.dpi"] = 100 

为所有输出设置它们, 或

plt.figure(figsize=(6,4), dpi=100)  

为单图。通过这种方式,您可以确保脚本和笔记本的输出相同。