简体   繁体   中英

Python: networkx customize graph node labels?

I have the following example code:

import pandas as pd
import networkx as nx

import matplotlib.pyplot as plt


def view_graph(graph, labels):
    '''
        Plots the graph
    '''
    pos = nx.spring_layout(graph)

    nx.draw(graph, pos, with_labels=True)
    nx.draw_networkx_edge_labels(graph, pos,edge_labels=labels)
        
    plt.axis('off')
    plt.show()

index_to_name = {1: "Paul", 2: "Magda", 3: "Paul", 4: "Anna", 5: "Marie", 6: "John", 7: "Mark"}
relation = {}
g = nx.DiGraph()

g.add_edge(1, 4)
relation[(1,4)] = "dad"
g.add_edge(2, 4)
relation[(2,4)] = "mom"

g.add_edge(1, 5)
relation[(1,5)] = "dad"
g.add_edge(2, 5)
relation[(2,5)] = "mom"

g.add_edge(3, 6)
relation[(1,6)] = "dad"
g.add_edge(4, 6)
relation[(2,6)] = "mom"

g.add_edge(3, 7)
relation[(1,7)] = "dad"
g.add_edge(4, 7)
relation[(2,7)] = "mom"

view_graph(g, relation)

My illustration window eg looks like that: 在此处输入图像描述

I have two problems and don't really know how to solve that:

  1. Is their a possibility to show the names from the dictionary index_to_name in the illustration instead of the indexes I introduce to ensure unique nodes (in the dictionary the name Paul occurs two times and so the name "Paul" should have two nodes).
  2. How can I fix the problem with the edge labels marked in the illustration with red rectangles. My aim is to add these labels so its clear which edge is being referenced?

I hope you can help me with this two problems.

W.r.t. problem 1), you would set with_labels to False (or simply omit the argument), and then add a function call to nx.draw.networkx_labels :

在此处输入图像描述

import matplotlib.pyplot as plt
import networkx as nx

def view_graph(graph, node_labels, edge_labels):
    '''
        Plots the graph
    '''
    pos = nx.spring_layout(graph)
    nx.draw(graph, pos, node_color='lightgray')
    nx.draw_networkx_labels(graph, pos, labels=node_labels)
    nx.draw_networkx_edge_labels(graph, pos, edge_labels=edge_labels)
    plt.axis('off')
    plt.show()

index_to_name = {1: "Paul", 2: "Magda", 3: "Paul", 4: "Anna", 5: "Marie", 6: "John", 7: "Mark"}

relation = {}
relation[(1, 4)] = "dad"
relation[(2, 4)] = "mom"
relation[(1, 5)] = "dad"
relation[(2, 5)] = "mom"
relation[(3, 6)] = "dad"
relation[(4, 6)] = "mom"
relation[(3, 7)] = "dad"
relation[(4, 7)] = "mom"

g = nx.from_edgelist(relation, nx.DiGraph())

view_graph(g, index_to_name, relation)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM