in NetworkX cannot save a graph as jpg or png file

匿名 (未验证) 提交于 2019-12-03 03:10:03

问题:

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):

回答1:

It's related to plt.show method.

Help of show method:

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.     """ 

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") 

Or just comment it:

# plt.show() plt.savefig("Graph.png", format="PNG") 

Or just save befor show it:

plt.savefig("Graph.png", format="PNG") plt.show() 

Demo: Here



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!