捕获pygraphviz图像渲染而不保存到文件?

时间:2013-09-04 07:54:23

标签: python graphviz pygraphviz

pygraphviz是否允许您将图像渲染到变量?我想通过网页提供动态图像,而不必将图形渲染到磁盘。

2 个答案:

答案 0 :(得分:1)

根据to the sources,如果在draw参数被省略(或设置为path)时调用AGraph对象的None方法,则它将返回数据而不是保存到文件。不要忘记指定format参数。

答案 1 :(得分:-1)

我认为这就是你想要的:

# https://stackoverflow.com/questions/28533111/plotting-networkx-graph-with-node-labels-defaulting-to-node-name

import dgl
import numpy as np
import torch

import networkx as nx

import matplotlib.pyplot as plt
import matplotlib.image as mpimg

from pathlib import Path

g = dgl.graph(([0, 0, 0, 0, 0], [1, 2, 3, 4, 5]), num_nodes=6)
print(f'{g=}')
print(f'{g.edges()=}')

# Since the actual graph is undirected, we convert it for visualization purpose.
g = g.to_networkx().to_undirected()
print(f'{g=}')

# relabel
int2label = {0: "app", 1: "cons", 2: "with", 3: "app3", 4: "app4", 5: "app5"}
g = nx.relabel_nodes(g, int2label)

# https://networkx.org/documentation/stable/reference/drawing.html#module-networkx.drawing.layout
g = nx.nx_agraph.to_agraph(g)
print(f'{g=}')
print(f'{g.string()=}')

# draw
g.layout()
g.draw("file.png")

# https://stackoverflow.com/questions/20597088/display-a-png-image-from-python-on-mint-15-linux
img = mpimg.imread('file.png')
plt.imshow(img)
plt.show()

# remove file https://stackoverflow.com/questions/6996603/how-to-delete-a-file-or-folder
Path('./file.png').expanduser().unlink()
# import os
# os.remove('./file.png')

您基本上需要从文件中显式渲染图形对象,然后将其删除(不幸的是,idk 有更好的答案)。有关更多详细信息,请查看我关于为什么我认为 pygraphviz 是可视化的最佳方式(而不是 networkx)的长篇讨论:https://stackoverflow.com/a/67439711/1601580