简体   繁体   English

在 python3 中标记图形

[英]Labelling a graph in python3

I am trying to build a graph with networkx, using nodes as class objects.我正在尝试使用 networkx 构建一个图形,使用节点作为 class 对象。 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.我期望通过在节点 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). “状态”属性的原因是因为我想根据节点的 state 更改节点的颜色(这是另一个问题)。 The output is below: output如下:

在此处输入图像描述

No edges appear.没有边缘出现。 Can you help me?你能帮助我吗?

The networkx package does not create the graph based on the attributes in your Node class. networkx package 不会根据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) .显示这些值的原因是您在使用G.add_node(n1.name)将新节点添加到图中时传递了它们。 Similarly in order to add edges you need to call to call the add_edge method.同样,为了添加边,您需要调用add_edge方法。 Please refer to the tutorial请参考 教程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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