【问题标题】:Capture pygraphviz image rendering without saving to a file?在不保存到文件的情况下捕获 pygraphviz 图像渲染?
【发布时间】:2013-09-07 15:13:39
【问题描述】:

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

【问题讨论】:

  • 如果您有有效的代码,您介意与我们分享吗?如果您的代码运行良好,请向我们展示您的伟大! ;)

标签: python graphviz pygraphviz


【解决方案1】:

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

【讨论】:

  • 你有我们可以复制粘贴的代码示例(并看到它工作)吗?
【解决方案2】:

我认为是你想要的:

# 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')

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-15
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    相关资源
    最近更新 更多