使用pydot显示图形而不保存
我正在尝试使用pydot显示一个简单的图表。
我想问的是,有没有办法可以直接在屏幕上显示这个图,而不需要先把它写入文件?因为目前我使用的是写入功能,先画出图,然后还得用Image模块来显示文件。
有没有什么方法可以让图直接在屏幕上显示,而不需要保存成文件呢?
另外,我想补充一下,我注意到当我使用Image模块的显示命令时,图像保存得很快,但显示出来却需要花费明显的时间……有时候我还会遇到错误,提示图像无法打开,因为它被删除了或者保存在一个不可用的位置。但其实我是在桌面上保存的……有没有人知道这是怎么回事?有没有更快的方法来加载这个图像呢?
非常感谢……
7 个回答
30
你可以通过调用 GraphViz
的 dot
来直接显示 pydot
的图像,而不需要把任何文件写入硬盘。然后只需将其绘制出来。具体可以这样做:
import io
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import networkx as nx
# create a `networkx` graph
g = nx.MultiDiGraph()
g.add_nodes_from([1,2])
g.add_edge(1, 2)
# convert from `networkx` to a `pydot` graph
pydot_graph = nx.drawing.nx_pydot.to_pydot(g)
# render the `pydot` by calling `dot`, no file saved to disk
png_str = pydot_graph.create_png(prog='dot')
# treat the DOT output as an image file
sio = io.BytesIO()
sio.write(png_str)
sio.seek(0)
img = mpimg.imread(sio)
# plot the image
imgplot = plt.imshow(img, aspect='equal')
plt.show()
这对于有向图特别有用。
另外,看看这个 拉取请求,它将这样的功能直接引入到 networkx
中。
34
这里有一个简单的解决方案,使用的是IPython:
from IPython.display import Image, display
def view_pydot(pdot):
plt = Image(pdot.create_png())
display(plt)
使用示例:
import networkx as nx
to_pdot = nx.drawing.nx_pydot.to_pydot
pdot = to_pdot(nx.complete_graph(5))
view_pydot(pdot)
0
我担心 pydot
是用 graphviz
来绘制图形的。也就是说,它会运行一个程序,然后加载生成的图像。
简单来说——不,你无法避免创建这个文件。