本文介绍了保存无边距的matplotlib/networkx数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我使用matplotlib
绘制图形时,如何保存它而没有多余的边距?通常当我另存为
When I draw a figure using matplotlib
how do I save it without extra margins?Usually when I save it as
plt.savefig("figure.png") # or .pdf
我得到了一些保证金:
示例:
import matplotlib.pyplot as plt
import networkx as nx
G=nx.Graph()
G.add_edge('a','b',weight=1)
G.add_edge('a','c',weight=1)
G.add_edge('a','d',weight=1)
G.add_edge('a','e',weight=1)
G.add_edge('a','f',weight=1)
G.add_edge('a','g',weight=1)
pos=nx.spring_layout(G)
nx.draw_networkx_nodes(G,pos,node_size=1200,node_shape='o',node_color='0.75')
nx.draw_networkx_edges(G,pos,
width=2,edge_color='b')
plt.axis('off')
plt.savefig("degree.png", bbox_inches="tight")
plt.show()
更新2:
在轴内部设置了空格.如果删除plt.axis('off')
,则可以清楚地看到.因此,我认为Networkx软件包可以使用一些技巧.
The spaces are set inside the axes.. This is clear if I remove plt.axis('off')
So I think there is some trick to use with the package Networkx.
推荐答案
在保存之前添加以下代码以控制绘图限制.
add the codes below to control plot limits before saving.
尝试使用不同的cut
值(例如1.05至1.50),直到您认为合适为止.
try different values of cut
, like from 1.05 to 1.50, until you see fit.
# adjust the plot limits
cut = 1.05
xmax= cut*max(xx for xx,yy in pos.values())
ymax= cut*max(yy for xx,yy in pos.values())
plt.xlim(0,xmax)
plt.ylim(0,ymax)
这篇关于保存无边距的matplotlib/networkx数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!