I want to create a graph and draw it, so far so good, but the problem is that i want to draw more information on each node. I saw i can save attributes to nodes\edges, but how do i draw the attributes? i'm using PyGraphviz witch uses Graphviz.
3 に答える
An example would be
import pygraphviz as pgv
from pygraphviz import *
G=pgv.AGraph()
ndlist = [1,2,3]
for node in ndlist:
label = "Label #" + str(node)
G.add_node(node, label=label)
G.layout()
G.draw('example.png', format='png')
but make sure you explicitly add the attribute label
for extra information to show as Martin mentioned https://stackoverflow.com/a/15456323/1601580.
You can only add supported attributes to nodes and edges. These attributes have specific meaning to GrpahViz.
To show extra information on edges or nodes, use the label
attribute.
If you already have a graph with some attribute you want to label you can use this:
def draw_nx_with_pygraphviz_attribtes_as_labels(g, attribute_name, path2file=None):
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
# https://stackoverflow.com/questions/15345192/draw-more-information-on-graph-nodes-using-pygraphviz
if path2file is None:
path2file = './example.png'
path2file = Path(path2file).expanduser()
g = nx.nx_agraph.to_agraph(g)
# to label in pygrapviz make sure to have the AGraph obj have the label attribute set on the nodes
g = str(g)
g = g.replace(attribute_name, 'label') # it only
print(g)
g = pgv.AGraph(g)
g.layout()
g.draw(path2file)
# https://stackoverflow.com/questions/20597088/display-a-png-image-from-python-on-mint-15-linux
img = mpimg.imread(path2file)
plt.imshow(img)
plt.show()
# remove file https://stackoverflow.com/questions/6996603/how-to-delete-a-file-or-folder
path2file.unlink()
# -- tests
def test_draw():
# import pylab
import networkx as nx
g = nx.Graph()
g.add_node('Golf', size='small')
g.add_node('Hummer', size='huge')
g.add_node('Soccer', size='huge')
g.add_edge('Golf', 'Hummer')
draw_nx_with_pygraphviz_attribtes_as_labels(g, attribute_name='size')
if __name__ == '__main__':
test_draw()
result:
in particular note that the two huge's did not become a self loop and they are TWO different nodes (e.g. two sports can be huge but they are not the same sport/entity).
related but plotting with nx: Plotting networkx graph with node labels defaulting to node name