问题描述
我在NetworkX中有一个包含一些信息的图表。显示图表后,我想将其保存为 jpg
或 png
文件。我使用了 matplotlib
函数 savefig
,但是保存图像后,它不包含任何内容。这只是一张白色图片。
I have a graph in NetworkX containing some info. After the graph is shown, I want to save it as jpg
or png
file. I used the matplotlib
function savefig
but when the image is saved, it does not contain anything. It is just a white image.
以下是我写的示例代码:
Here is a sample code I wrote:
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")
为什么保存图像时没有任何内容(只是白色)?
Why is the image saved without anything inside (just white) ?
这是保存的图像(只是空白):
This is the image saved (just blank):
推荐答案
它与 plt.show $ c相关$ c>方法。
的帮助显示
方法:
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
的块
选项可以改变此行为,因此您可以使用它:
When you call plt.show()
in your script, it seems something like file object is still open, and plt.savefig
method for writing can not read from that stream completely. but there is a block
option for plt.show
that can change this behavior, so you can use it:
plt.show(block=False)
plt.savefig("Graph.png", format="PNG")
或者只是评论:
# plt.show()
plt.savefig("Graph.png", format="PNG")
或者只需保存即可显示:
Or just save befor show it:
plt.savefig("Graph.png", format="PNG")
plt.show()
演示:
这篇关于在NetworkX中无法将图形保存为jpg或png文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!