#325 Map colour to the edges of a Network

This chart follows the chart #324 where we learned how to map a color to each nodes of a network. This time, we suppose that we have a feature for each edge of our network. For example, this feature can be the amount of money that this links represents (numerical value), or on which continent it happened (categorical value). We want the edge to be different according to this variable, and here is how to do it:

  •  

     

     

     

    Here we use a color palette to represent the intensity of the flow (darker = stronger). The variable we want to map is a column of the links data frame. It is then easy to provide it to the edge color argument!

     

     

     

     

     

     

    
    # libraries
    import pandas as pd
    import numpy as np
    import networkx as nx
    import matplotlib.pyplot as plt
    
    # Build a dataframe with your connections
    df = pd.DataFrame({ 'from':['A', 'B', 'C','A'], 'to':['D', 'A', 'E','C'], 'value':[1, 10, 5, 5]})
    df
    
    # Build your graph
    G=nx.from_pandas_dataframe(df, 'from', 'to', create_using=nx.Graph() )
    
    # Custom the nodes:
    nx.draw(G, with_labels=True, node_color='skyblue', node_size=1500, edge_color=df['value'], width=10.0, edge_cmap=plt.cm.Blues)
    
    
  •  

     

     

     

    Here I have 2 types of connection: type A and B. They are both represented with a different colour.

    Note that we need to transform our categorical variable (A, B, ..) to something numeric with the pd.Categorical function!

     

     

     

     

     

     

    
    # libraries
    import pandas as pd
    import numpy as np
    import networkx as nx
    import matplotlib.pyplot as plt
    
    # Build a dataframe with your connections
    df = pd.DataFrame({ 'from':['A', 'B', 'C','A'], 'to':['D', 'A', 'E','C'], 'value':['typeA', 'typeA', 'typeB', 'typeB']})
    df
    
    # And I need to transform my categorical column in a numerical value typeA->1, typeB->2...
    df['value']=pd.Categorical(df['value'])
    df['value'].cat.codes
    
    # Build your graph
    G=nx.from_pandas_dataframe(df, 'from', 'to', create_using=nx.Graph() )
    
    # Custom the nodes:
    nx.draw(G, with_labels=True, node_color='skyblue', node_size=1500, edge_color=df['value'].cat.codes, width=10.0, edge_cmap=plt.cm.Set2)
    
    

 

Leave a Reply

Your email address will not be published.