Search code examples
pythonnetworkx

networkx : Plot a graph with common attributes


I am trying to create a graph with nodes and edges. The data I had was divided into Members and topics taken by them. Now I processed the data in this form where for each topic i have found the members who take that topic:

T498    ['M1', 'M3', 'M5', 'M7', 'M16', 'M20']                  
T611    ['M2', 'M3', 'M4', 'M6', 'M7', 'M8', 'M9', 'M10', 'M11', 'M12', 'M13', 'M14', 'M15', 'M17', 'M18', 'M19']

How can I join these member nodes to that topic? Also if i have responses for each member like "Yes", "No" , how can i use them as weights?


Solution

  • The nodes and edges are like dictionaries which can hold any sort of information you want. For example, you can label each node whether it's a topic or member and when it's time to plot, you can define its label, size, color, font size, etc based on that information.

    Here is a basic example where you change the color of each edge based on the member's response, instead of its thickness or some other attribute.

    import matplotlib.pyplot as plt
    import networkx as nx
    
    topics = {
        'T498': [('M1', 0), ('M3', 1), ('M5', 1), ('M7', 0), ('M8', 0)],
        'T611': [('M2', 1), ('M3', 1), ('M4', 0), ('M6', 1), ('M7', 0)],
    }
    
    G = nx.Graph()
    for topic, members in topics.items():
        # You just need `G.add_node(node)`, everything else after that is an attribute
        G.add_node(topic, type='topic')
        for member, response in members:
            if member not in G.nodes:
                G.add_node(member, type='member')
            # `G.add_edge(node1, node2)`, the rest are attributes
            G.add_edge(topic, member, response=response)
    
    node_sizes = [1000 if attrs['type'] == 'topic' else 500 for attrs in G.nodes.values()]
    node_colors = ['r' if attrs['type'] == 'topic' else '#1f78b4' for attrs in G.nodes.values()]
    edge_colors = ['y' if attrs['response'] else 'k' for attrs in G.edges.values()]
    pos = nx.spring_layout(G)
    nx.draw_networkx_labels(G, pos)
    nx.draw(G, pos, node_size=node_sizes, node_color=node_colors, edge_color=edge_colors)
    plt.show()
    

    Output

    1