简体   繁体   中英

Labelling a graph in python3

I am trying to build a graph with networkx, using nodes as class objects. I have already labelled the nodes, but I am not being able to show labeled edges (actually, not edges at all). I was expecting to do so by defining the neighbouring nodes inside the Node class. I show my code below:


# Packages

import random as rd
import networkx as nx
from matplotlib import pyplot as plt

# Classes

class Node:
    def __init__(self, name):
        self.name = name
        self.state = rd.choice([-1, 0, 1])
        self.neighbour = None

    def get_name(self):
        return self.name
    def get_state(self):
        return self.state
    def get_neighbour(self):
        return self.neighbour

# Nodes and neighbours

n1 = Node(1)
n2 = Node(2)
n3 = Node(3)

n1.neighbour = n2
n2.neighbour = n3

# Graph

G = nx.Graph()

G.add_node(n1.name)
G.add_node(n2.name)
G.add_node(n3.name)

pos = nx.spring_layout(G)

nx.draw_networkx_nodes(G, pos)
nx.draw_networkx_edges(G, pos)
nx.draw_networkx_labels(G, pos)
#nx.draw_spectral(G, with_labels=True)   # I also tried this suggestion, but unsuccessfully

plt.savefig('jupyter_graph.png')

The reason for the "state" attribute is because I want to change the colours of the nodes depending on their state (that's another issue). The output is below:

在此处输入图像描述

No edges appear. Can you help me?

The networkx package does not create the graph based on the attributes in your Node class. The reason the values are displayed is that you pass them when adding a new node into the graph with G.add_node(n1.name) . Similarly in order to add edges you need to call to call the add_edge method. Please refer to the tutorial

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