Export a graph to a graph with node positions using NetworkX

I am using NetworkX 1.9.1.

I have a chart that I need to organize using positions, and then export it to a chart format.

I tried the code in this question . This does not work, here is my example

import networkx as nx import matplotlib.pyplot as plt G = nx.read_graphml("colored.graphml") pos=nx.spring_layout(G) # an example of quick positioning nx.set_node_attributes(G, 'pos', pos) nx.write_graphml(G, "g.graphml") nx.draw_networkx(G, pos) plt.savefig("g.pdf") 

Here are the errors I get, the problem is how the positions are saved (graphml does not accept arrays).

 C:\Anaconda\python.exe C:/Users/sturaroa/Documents/PycharmProjects/node_labeling_test.py Traceback (most recent call last): File "C:/Users/sturaroa/Documents/PycharmProjects/node_labeling_test.py", line 11, in <module> nx.write_graphml(G, "g.graphml") File "<string>", line 2, in write_graphml File "C:\Anaconda\lib\site-packages\networkx\utils\decorators.py", line 220, in _open_file result = func(*new_args, **kwargs) File "C:\Anaconda\lib\site-packages\networkx\readwrite\graphml.py", line 82, in write_graphml writer.add_graph_element(G) File "C:\Anaconda\lib\site-packages\networkx\readwrite\graphml.py", line 350, in add_graph_element self.add_nodes(G,graph_element) File "C:\Anaconda\lib\site-packages\networkx\readwrite\graphml.py", line 307, in add_nodes self.add_attributes("node", node_element, data, default) File "C:\Anaconda\lib\site-packages\networkx\readwrite\graphml.py", line 300, in add_attributes scope=scope, default=default_value) File "C:\Anaconda\lib\site-packages\networkx\readwrite\graphml.py", line 288, in add_data '%s as data values.'%element_type) networkx.exception.NetworkXError: GraphML writer does not support <type 'numpy.ndarray'> as data values. 

I got the impression that I would be better off defining the positions as two separate node, x and y attributes and storing them separately, defining a key for each of them in a graph format like this .

However, I am not so familiar with Python and would like your opinion before I made a mess repeating back and forth.

Thanks.

0
source share
1 answer

You're right, GraphML wants simpler attributes (no numpy arrays or lists).

You can set the x and y positions of nodes as attributes like this

 G = nx.path_graph(4) pos = nx.spring_layout(G) for node,(x,y) in pos.items(): G.node[node]['x'] = float(x) G.node[node]['y'] = float(y) nx.write_graphml(G, "g.graphml") 
+4
source

All Articles