Converting networkx graph to Gephi

Viewed 405

I am trying to convert a Python networkx graph to a Gephi compatible file. However, I am running into some issues which I don't understand how to solve:

Questions:

  1. How can we incorporate node feature vectors into gexf files? I keep getting the error: "TypeError: attribute value type is not allowed: <class 'numpy.ndarray'>". If I remove the node features code below, then it works, but ideally I would like to include node features.

  2. When I load the .gexf file into Gephi, nothing is showing up for some reason - why might this be happening? I managed to get a gexf file when I removed the node feature part of the code below. (The app starts, I can visualize the other test data-sets, but when I load the file below, it shows the nodes and edges counter in the top right corner, but the actual graph doesn't show up... Do I need to press something else? I watched some of the YouTube tutorials and the graph always loads for those people)

I know there are lots of posts, but after looking through quite a few and trying the solutions I just decided to make a post.

Example code: I have made some mock-up code to showcase what I am doing:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import networkx as nx
%matplotlib inline

# Make the networkx graph
G = nx.Graph()

# Add some cars (just do 4 for now)
G.add_nodes_from([
      (1, {'y': 0}),
      (2, {'y': 1}),
      (3, {'y': 2}),
      (4, {'y': 3}),
      (5, {'y': 4}),
])

# Add some edges --> A = [(0, 1, 0, 1, 1), (1, 0, 1, 1, 0), (0, 1, 0, 0, 1), (1, 1, 0, 0, 0), (1, 0, 1, 0, 0)]
G.add_edges_from([
                  (1, 2), (1, 4), (1, 5),
                  (2, 3), (2, 4),
                  (3, 2), (3, 5), 
                  (4, 1), (4, 2),
                  (5, 1), (5, 3)
])

# add the price data to the graph as node features
for node in G.nodes():
  G.nodes[node]['x'] = np.random.rand(5) * 5

# This code mounts the google drive
from google.colab import drive
drive.mount('/content/drive')

# convert the graph to Gephi
nx.write_gexf(G, '/content/drive/MyDrive/cars_test.gexf', version="1.2draft")

Then I get the error: "TypeError: attribute value type is not allowed: <class 'numpy.ndarray'>"

Any help would be appreciated.

1 Answers

It appears there is no numpy support at the moment, so one way around this is to store data as lists:

# add the price data to the graph as node features
for node in G.nodes():
    G.nodes[node]["x"] = {"price": list(np.random.rand(5) * 5)}

Note that the node attribute is stored as a dictionary.

Related