在NetworkX中无法将图形保存为jpg或png文件

时间:2014-03-25 13:04:34

标签: python image matplotlib save networkx

我在NetworkX中有一个包含一些信息的图表。显示图表后,我想将其另存为jpgpng文件。我使用了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")

为什么保存图像时没有任何内容(只是白色)?

这是保存的图像(只是空白): enter image description here

2 个答案:

答案 0 :(得分:5)

它与plt.show方法有关。

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写入方法无法完全从该流中读取。但block有一个plt.show选项可以更改此行为,因此您可以使用它:

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

演示: Here

答案 1 :(得分:1)

我也遇到同样的问题。查看其他评论,并在此链接https://problemsolvingwithpython.com/06-Plotting-with-Matplotlib/06.04-Saving-Plots/的帮助下,它对我有用!我必须在简单程序中更改的两件事是添加: 导入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'是可选的 保存后#use plt.show()。希望这会有所帮助。