'When exporting a networkx graph to GML, how can I explicitly set the labels?
When exporting a networkx graph to GML, how can I explicitly set the labels? Given this script:
import networkx as nx
G2 = nx.DiGraph()
G2.add_node( "id:UserA", label="Cat" )
G2.add_node( "id:Userb", label="Dog" )
nx.write_gml(G2, 'tt.gml')
I get
graph [
directed 1
node [
id 0
label "id:UserA"
]
node [
id 1
label "id:Userb"
]
]
where I want
graph [
directed 1
node [
id 0
label "Cat"
]
node [
id 1
label "Dog"
]
]
I can explicitly color nodes by adding graphics={'fill': '#FF0000'}
but adding label
this way does not seem to work.
Solution 1:[1]
You can use the LabelGraphics
attribute. This works with yEd editor at least.
import networkx as nx
G2 = nx.DiGraph()
G2.add_node( "id:UserA", LabelGraphics={"text" : "Cat"} )
G2.add_node( "id:Userb", LabelGraphics={"text" : "Dog"} )
nx.write_gml(G2, 'tt.gml')
Solution 2:[2]
The reason is that as mentioned in the docs:
Graph attributes named 'directed', 'multigraph', 'node' or 'edge',node attributes named 'id' or 'label', edge attributes named 'source' or 'target' (or 'key' if G is a multigraph) are ignored because these attribute names are used to encode the graph structure.
i.e if you set the attribute name to label
it will be ignored since it is a name which is always used to define the graph structure, that is why the label
that you see does not show as the value you've set it to. So what you can do is to simply set these attributes with another name, such as:
G2 = nx.DiGraph()
G2.add_node( "id:UserA", tag="Cat" )
G2.add_node( "id:Userb", tag="Dog" )
nx.write_gml(G2, 'tt.gml')
In this case you'd get:
graph [
directed 1
node [
id 0
label "id:UserA"
tag "Cat"
]
node [
id 1
label "id:Userb"
tag "Dog"
]
]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Santiago Dandois |
Solution 2 | yatu |