Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Color Attribute to Nodes on NetworkX to export to Gephi

I am making a graph using NetworkX to export to visualize with Gephi. I've been adding various attributes to the nodes in my graph, without issue, until I tried adding colors. Does anyone know how to export a graph with "colored" nodes using networkx? (I've been writing into a gexf file, but don't care if it is another format as long as it is compatible with Gephi.)

Here is the code in which I make the graph:

def construct_weighted_graph(nodes, distance_dict, weighting_function, color = True):

  G = nx.Graph()
  #nodes automatically added when edges added. 
  for sequence in nodes: #loop through and add size attribute for num of sequences
    G.add_node(sequence)
    G.node[sequence]['size'] = distance_dict[sequence][1] #size represented by the node
    if color:
        G.node[sequence]['color'] = (0,1,0)
  for i_node1 in range(len(nodes)):
    dist_list = distance_dict[nodes[i_node1]][-2] #list of distances
    for i_node2 in range(i_node1+1, len(nodes)):
        G.add_edge(nodes[i_node1], nodes[i_node2], 
                   weight = weighting_function(dist_list[i_node2]))
  return G

That is not exactly what I have for color, since different nodes are assigned different colors, but it is the basic idea.

like image 263
Hannah Avatar asked Feb 15 '15 01:02

Hannah


1 Answers

I ran into the exactly the same issue. The normal way to set coloring in NetworkX does not get exported to the GEXF format. By reading the export code of NetworkX and GEXF documentation, I have found out how to correctly export to GEXF and in turn import into Gephi.

NetworkX does export coloring if the coloring follows the same structure of GEXF. The data has to be added to a node inside a graph. So you add a key 'viz' standing for visualization to the node. You set 'viz' to another dictionary, where you add a key 'color' with in turn a dictionary with values for keys 'r','g','b', and 'a'.

I made a very simple example that demonstrates the solution:

import networkx as nx
""" Create a graph with three nodes"""
graph = nx.Graph()
graph.add_node('red')
graph.add_node('green')
graph.add_node('blue')
""" Add color data """
graph.node['red']['viz'] = {'color': {'r': 255, 'g': 0, 'b': 0, 'a': 0}}
graph.node['green']['viz'] = {'color': {'r': 0, 'g': 255, 'b': 0, 'a': 0}}
graph.node['blue']['viz'] = {'color': {'r': 0, 'g': 0, 'b': 255, 'a': 0}}
""" Write to GEXF """
# Use 1.2draft so you do not get a deprecated warning in Gelphi
nx.write_gexf(graph, "file.gexf", version="1.2draft")

This exports a graph with a red, a green, and a blue node to GEXF.

You have to change your example where you try to set the color to:

if color:
    G.node[sequence]['viz'] = {'color': {'r': 0, 'g': 1, 'b': 0, 'a': 0}} # line changed
for i_node1 in range(len(nodes)):
like image 185
snorberhuis Avatar answered Nov 02 '22 17:11

snorberhuis