如何在循环的每次迭代中将新图形保存为 png [英] How do I save a new graph as png with every iteration of a loop

查看:45
本文介绍了如何在循环的每次迭代中将新图形保存为 png的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何使用NetworkX为循环的每次迭代保存新的图png.我已从以下问题中借用了代码:在NetworkX中,无法将图形另存为jpg或png文件并对其进行了一些操作.下面是代码:

I don't know how to save a new graph png for each iteration of a loop using NetworkX. I've borrowed the code from this question: in NetworkX cannot save a graph as jpg or png file and manipulated it a bit. Below is the code:

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)
n = 0
colorses = ['yellow', 'red', 'blue', 'green']
while n < len(colorses):
    nx.draw(G, pos, node_size=1500, node_color=colorses[n], font_size=8, font_weight='bold')
    plt.tight_layout()
    # plt.show()
    plt.savefig("Graph.png", format="PNG")
    n += 1

理想情况下,我希望有四个图像,每个图像具有不同的颜色节点.让我知道您是否需要更多信息.谢谢!

Ideally I would like to have four images each one with different color nodes. Let me know if you need any more information. Thanks!

推荐答案

只需更改输出文件的名称

Just change the name of the output file

while n < len(colorses):
    nx.draw(G, pos, node_size=1500, node_color=colorses[n], font_size=8, font_weight='bold')
    plt.tight_layout()
    # plt.show()
    plt.savefig("Graph" + str(n) +".png", format="PNG")
    n += 1

不过,您应该使用更具描述性的名称.也许可以用n代替n

You should use more descriptive names though. Maybe instead of n, you could refer to a time

    plt.savefig("Graph" + str(datetime.datetime.now()) +".png", format="PNG")

这不太好,因为字符串会有空格,但您可以事先调整它

That isn't great, since the string will have whitespace, but you can tweak it beforehand

这篇关于如何在循环的每次迭代中将新图形保存为 png的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆