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

21 投票
2 回答
41353 浏览
提问于 2025-04-17 23:49

我在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 个回答

2

我也遇到过同样的问题。看了其他人的评论,还有这个链接的帮助 https://problemsolvingwithpython.com/06-Plotting-with-Matplotlib/06.04-Saving-Plots/,我终于解决了!我在我的简单程序中需要改动的两件事是:在导入matplotlib之后加上 %matplotlib inline,并且在 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()。希望这对你有帮助。

31

这和 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 方法在写入时就无法完全读取这个流。不过,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()

示例: 在这里

撰写回答