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

Fra*_*lla 9 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")
Run Code Online (Sandbox Code Playgroud)

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

这是保存的图像(只是空白): 在此输入图像描述

Omi*_*aha 9

它与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.
    """
Run Code Online (Sandbox Code Playgroud)

当您调用plt.show()脚本时,似乎文件对象仍然打开,并且plt.savefig写入方法无法完全从该流中读取.但有一个block选项plt.show可以改变这种行为,所以你可以使用它:

plt.show(block=False)
plt.savefig("Graph.png", format="PNG")
Run Code Online (Sandbox Code Playgroud)

或者只是评论它:

# plt.show()
plt.savefig("Graph.png", format="PNG")
Run Code Online (Sandbox Code Playgroud)

或者只是保存以表明它:

plt.savefig("Graph.png", format="PNG")
plt.show()
Run Code Online (Sandbox Code Playgroud)

演示: 在这里