0

I have a pandas dataframe called df_sort with the following structure,

Structure:

Topic Links         Topic_method_1
ML    Data Mining   1
ML    Data Analysis 1
ML    ggplot2       2
ML    R             3
ML    python        3

Question:

I want to create a network graph for my dataframe and color the nodes by the values of column 'Topic_method_1'

Attempt so far:

import networkx as nx
import matplotlib.pyplot as plt

# Build your graph
G=nx.from_pandas_edgelist(df_sort, 'Topic', 'Links')

# Plot it
nx.draw(G, with_labels=True)
plt.show()

Problem:

How do I add colors to my nodes? I see that there is a node_attribute in the documentation.

Anubhav Dikshit
  • 1,729
  • 6
  • 25
  • 48
  • Try this post. https://stackoverflow.com/a/52683100/6361531 – Scott Boston Nov 12 '19 at 19:00
  • The question is not clear, how do you want to add the colors ? I am assuming, for example, in first row, there is an edge between `ML` and `Data Mining`, so you want to assign color `1` to both nodes ? if that is the case, what do you want to do in the third row, when color changes to `2` but one of the nodes is still the same, i.e. `ML` ? – Gambit1614 Nov 13 '19 at 10:28
  • The node 'ML' (column 'Topic') remains the same colored, while the nodes under column 'Topic_model_1' will be colored. – Anubhav Dikshit Nov 13 '19 at 16:09

1 Answers1

0

So I figured the error, the trick is knowing that 'node_color' needs n+1 sized array. Where n is the number of rows.

import networkx as nx
import matplotlib.pyplot as plt
import numpy as np

# Build your graph
G=nx.from_pandas_edgelist(df_sort, 'Topic', 'Links')
cbbPalette = ["#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2"]
values = np.where(df_sort['Topic_method_1']==0, cbbPalette[0], 
              np.where(df_sort['Topic_method_1']==1, cbbPalette[1], 
                       np.where(df_sort['Topic_method_1']==2, cbbPalette[2], cbbPalette[3])))

values = np.append(values,cbbPalette[4])
# Plot it
nx.draw(G, with_labels=True, node_color = values)
plt.show()
Anubhav Dikshit
  • 1,729
  • 6
  • 25
  • 48