Capture pygraphviz image rendering without saving to a file?
An answer to this question on Stack Overflow.
Question
Does pygraphviz allow for you to render an image to a variable? I would like to serve up dynamic images via a webpage without having to render the graphs to disk.
Answer
I couldn't find a way to do this without a file being involved, so I created this handy function:
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import networkx as nx
import pygraphviz
def plot_network(G: nx.DiGraph):
ag = nx.nx_agraph.to_agraph(G)
ag.layout(prog="dot")
temp = tempfile.NamedTemporaryFile(delete=False)
tempname = temp.name + ".png"
ag.draw(tempname)
img = mpimg.imread(tempname)
plt.imshow(img)
plt.show()
os.remove(tempname)