I need to process a graphml (XML) file created by a yEd graph in order to get the node and edges attributes of that graph. I need to do that using the networkX library. I'm new at Python and I have never used the networkX library so any help would be appreciated.
This should get you started...
In yEd create the graph and File > Save As... using the GraphML format. Say, you save it to file 'test.graphml'.
Navigate to that directory and run Python:
>>> import networkx as nx
>>> import matplotlib.pyplot as plt
>>> G = nx.read_graphml('test.graphml')
>>> nx.draw(G)
>>> plt.show()
>>>
Furthermore, if you want to read and process the attributes of the nodes, you can iterate through them, extracting the data from them like this:
for node in G.nodes(data=True):
print node
This will result in something like this (I created a random graph in yEd to test this):
('n8', {'y': '178.1328125', 'x': '268.0', 'label': '8'})
('n9', {'y': '158.1328125', 'x': '0.0', 'label': '9'})
('n0', {'y': '243.1328125', 'x': '160.0', 'label': '0'})
('n1', {'y': '303.1328125', 'x': '78.0', 'label': '1'})
('n2', {'y': '82.1328125', 'x': '221.0', 'label': '2'})
('n3', {'y': '18.1328125', 'x': '114.0', 'label': '3'})
('n4', {'y': '151.1328125', 'x': '170.0', 'label': '4'})
('n5', {'y': '122.1328125', 'x': '85.0', 'label': '5'})
('n6', {'y': '344.1328125', 'x': '231.0', 'label': '6'})
('n7', {'y': '55.1328125', 'x': '290.0', 'label': '7'})
As a final example, if one wants to access the x coordinate of node n5
, then:
>>> print G['n5']['x']
will give you 85.0
.
I read this question and thought: The doc for that package is REALLY good, even by Python standards. You should really check it out.
IF you have a graph XML file, it looks like it's as easy as:
>>> mygraph=nx.read_gml("path.to.file")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With