将标签与从 NetworkX 图生成的散景图上的节点对齐

Lining up labels with the nodes on a Bokeh figure generated from a NetworkX graph

我正在尝试注释来自 NetworkX 并在 Bokeh 中可视化的网络图。我能够成功地将标签添加到 ColumnDataSource,并让它们出现在图中,但坐标似乎是错误的,因为标签没有与节点对齐。任何帮助将不胜感激。

from bokeh.io import show
from bokeh.plotting import figure
from bokeh.models.graphs import from_networkx
from bokeh.models import ColumnDataSource, LabelSet


def visualise_graph(G):
    plot = figure(title="Title", tools="", x_range=(-1.5, 1.5),
              y_range=(-1.5, 1.5), toolbar_location=None)
    graph = from_networkx(G, nx.spring_layout)
    plot.renderers.append(graph)
    return plot


def prepare_labels(G, plot):
    pos = nx.spring_layout(G)
    x, y = zip(*pos.values())
    node_labels = nx.get_node_attributes(N, 'label')
    source = ColumnDataSource({'x': x, 'y': y,
                               'label': [node_labels[i] for i in range(len(x))]})
    labels = LabelSet(x='x', y='y', text='label', source=source,
                      background_fill_color='white')
    plot.renderers.append(labels)
    return plot

 plot = visualise_graph(N)
 plot_w_labels = prepare_labels(N, plot)
 show(plot_w_labels)

我发现问题是我使用 nx.spring_layout() 获取坐标,实际上生成了一个具有新坐标的新图形。相反,我使用 .layout_provider.graph_layout 从 Bokeh 图形中提取坐标,现在它可以正常工作了。

我在 Whosebug 中的第一个 post 所以不要开枪。所需的更改是这样的:

#draw graph with some layout
graph_renderer = from_networkx(graph_to_plot, nx.fruchterman_reingold_layout(graph_to_plot), scale=1, center=(0, 0))    
#x, y = zip(*pos.values())
x,y=zip(*graph_renderer.layout_provider.graph_layout.values())
graph_renderer.node_renderer.data_source.data['x']=x
graph_renderer.node_renderer.data_source.data['y']=y
.
.
label=LabelSet(x='x', y='y', text='index',level='glyph', source=graph_renderer.node_renderer.data_source)

@user2892709 - 这是给你的。

首先,使用graph_renderer.layout_provider.graph_layout

提取节点坐标
graph_renderer = from_networkx(G, nx.spring_layout, scale=1, center=(0, 0))

pos = graph_renderer.layout_provider.graph_layout
x,y=zip(*pos.values())

然后将这些值添加到 LabelSet()

source = ColumnDataSource({'x':x,'y':y, 'field': <your_node_list>})
labels = LabelSet(x='x', y='y', text='field', source=source)

最后,您可以使用以下方法将值添加到图表中:

plot.renderers.append(graph_renderer)
plot.renderers.append(labels)