Python 在NetworkX中,无法将图形另存为jpg或png文件
我在NetworkX中有一个包含一些信息的图表。显示图形后,我想将其保存为Python 在NetworkX中,无法将图形另存为jpg或png文件,python,image,matplotlib,save,networkx,Python,Image,Matplotlib,Save,Networkx,我在NetworkX中有一个包含一些信息的图表。显示图形后,我想将其保存为jpg或png文件。我使用了matplotlib函数savefig,但在保存图像时,它不包含任何内容。它只是一个白色的图像 以下是我编写的示例代码: import networkx as nx import matplotlib.pyplot as plt fig = plt.figure(figsize=(12,12)) ax = plt.subplot(111) ax.set_title('Graph - Shape
jpg
或png
文件。我使用了matplotlib
函数savefig
,但在保存图像时,它不包含任何内容。它只是一个白色的图像
以下是我编写的示例代码:
import networkx as nx
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(12,12))
ax = plt.subplot(111)
ax.set_title('Graph - Shapes', fontsize=10)
G = nx.DiGraph()
G.add_node('shape1', level=1)
G.add_node('shape2', level=2)
G.add_node('shape3', level=2)
G.add_node('shape4', level=3)
G.add_edge('shape1', 'shape2')
G.add_edge('shape1', 'shape3')
G.add_edge('shape3', 'shape4')
pos = nx.spring_layout(G)
nx.draw(G, pos, node_size=1500, node_color='yellow', font_size=8, font_weight='bold')
plt.tight_layout()
plt.show()
plt.savefig("Graph.png", format="PNG")
为什么图像保存时内部没有任何内容(仅为白色)
这是已保存的图像(仅为空白):
它与
plt.show
方法有关
显示
方法的帮助:
def show(*args, **kw):
"""
Display a figure.
When running in ipython with its pylab mode, display all
figures and return to the ipython prompt.
In non-interactive mode, display all figures and block until
the figures have been closed; in interactive mode it has no
effect unless figures were created prior to a change from
non-interactive to interactive mode (not recommended). In
that case it displays the figures but does not block.
A single experimental keyword argument, *block*, may be
set to True or False to override the blocking behavior
described above.
"""
当您在脚本中调用plt.show()
时,似乎文件对象仍然处于打开状态,plt.savefig
写入方法无法从该流中完全读取。但是plt.show
有一个block
选项可以更改此行为,因此您可以使用它:
plt.show(block=False)
plt.savefig("Graph.png", format="PNG")
或者只是评论一下:
# plt.show()
plt.savefig("Graph.png", format="PNG")
或者在显示之前先保存:
plt.savefig("Graph.png", format="PNG")
plt.show()
演示:
我也遇到了同样的问题。看看其他评论,在这个链接的帮助下,它为我工作了!在我的简单程序中,我必须改变的两件事是添加: %导入matplotlib后,matplotlib内联并将图形保存在plt.show()之前。请参见我的基本示例:
#importing the package
import networkx as nx
import matplotlib.pyplot as plt
%matplotlib inline
#initializing an empty graph
G = nx.Graph()
#adding one node
G.add_node(1)
#adding a second node
G.add_node(2)
#adding an edge between the two nodes (undirected)
G.add_edge(1,2)
nx.draw(G, with_labels=True)
plt.savefig('plotgraph.png', dpi=300, bbox_inches='tight')
plt.show()
#dpi=指定保存的图像中每英寸有多少个点(图像分辨率),#bbox_inches='tight'是可选的
#保存后使用plt.show()。希望这有帮助