首页 > 解决方案 > 创建一个图形,节点为带有文本的圆圈

问题描述

使用 Networkx,我正在创建一个图表,

我想将每个节点创建为一个圆圈,然后定义边缘。

    from tkinter import *
    import networkx as nx
    G=nx.Graph()
    G.add_node(0) # text say ,"Hello" placed in circle/rectangle 

此处给出的示例中,我尝试使用画布创建文本标签

Canvas.drawText(10, 20, "A Text String")

我收到以下错误,

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'Canvas' has no attribute 'drawText'

有关如何解决此问题的任何建议,或者是否有任何替代方法可以将每个节点创建为包含文本的圆形/矩形?

标签: pythoncanvasgraphnetworkx

解决方案


绘制 Networkx 图的最简单方法是通过它的绘图API。

例如:

import networkx as nx
import matplotlib.pyplot as plt

G = nx.barabasi_albert_graph(20, 2)
nx.draw_networkx(G, with_labels=True, labels={node : 'some text {}'.format(node) for node in G.nodes()})
plt.show()

将导致类似: 在此处输入图像描述


推荐阅读