print graph attribuites networkx in python

You can use the graph_attr parameter in the to_agraph() function from the PyGraphviz library to get a list of attributes for a graph in NetworkX:

main.py
import networkx as nx
import matplotlib.pyplot as plt
from networkx.drawing.nx_agraph import to_agraph

# create a graph
G = nx.Graph()
G.add_edges_from([(1,2), (2,3), (3,1), (3,4)])

# set some graph attributes
G.graph['name'] = 'My Graph'
G.graph['rankdir'] = 'LR'

# convert graph to PyGraphviz AGraph
A = to_agraph(G)

# print graph attributes
print('Graph attributes:', A.graph_attr.items())

# plot the graph
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels=True)
plt.show()
486 chars
23 lines

This will print a list of attribute-value pairs for the graph, such as:

main.py
Graph attributes: [('name', 'My Graph'), ('rankdir', 'LR')]
60 chars
2 lines

And the last three lines will display the graph visualization.

related categories

gistlibby LogSnag