Search code examples
pythonpython-3.xdirected-graph

Why are my colors not mapping correctly when plotting this community graph?


I have source and target nodes that I am trying to graph in toyplot. Some are in community 0 and some are in community 1. I want to plot the community 0's as green and community 1's as orange (as shown in the color map) but they aren't being colored correctly. When I remap the nodes as named as 0 through 9 (source2 and target2), everything is colored correctly in the produced graph. What am I missing?

import numpy as np
import pandas as pd
import toyplot

nodes = ['1001', '1002', '1006', '100e', '010c', '0521', '0513', '0710', '0711', '1005']

mapped_nodes = ['0','1','2','3','4','5','6','7','8','9']
event_map = dict(zip(nodes,mapped_nodes))

edges = pd.DataFrame()
edges['source'] = ['010c','0513','0513','0513','0513','0513','0521','0521','0521','0521','0710','0710','0710','1001','1002','1006']
edges['target'] = ['0521','0521','0710','0711','1001','1005','0710','1001','1002','1006','1006','0711','1005','1006','1006','100e']
edges['source2'] = edges['source'].map(event_map)
edges['target2'] = edges['target'].map(event_map)
print('display edges')
display(edges)

# With this, the nodes's community is colored correctly
# i.e., 6, 7, 8 and 9 are clustered together with the correct color value of 1
# edges = np.array(edges[['source2','target2']].values.tolist())

# With this, the nodes's community is colored incorrectly
# i.e., 1005, 0711, 0513 and 0710 should be colored as 1, as found mapped in the "assigned" dataframe 
edges = np.array(edges[['source','target']].values.tolist())

print('print edges')
print(edges)

assigned = pd.DataFrame()
assigned['target'] = ['1001','1002','1006','100e','010c','0521','0513','0710','0711','1005']
assigned['target2'] = assigned['target'].map(event_map)
assigned['community'] = [0,0,0,0,0,0,1,1,1,1]
print('display assigned')
display(assigned)
assigned = np.array(assigned[['target','target2','community']].values.tolist())
print('print assigned')
print(assigned)

colormap = toyplot.color.brewer.map("Set2")
display(colormap)

ecolor = "lightgrey"
vlstyle = {"fill":"white"}
vcolor = assigned[:,2].astype(int)
toyplot.graph(edges, ecolor=ecolor, vsize=20, vlstyle=vlstyle, vcolor=(vcolor, colormap))

Solution

  • Turns out, you have to sort/order your assigned community

    sorted_assigned = assigned.sort_values('target')
    vcolor = sorted_assigned['community'].values
    toyplot.graph(edges, ecolor=ecolor, vsize=20, vlstyle=vlstyle, vcolor=(vcolor, colormap))