用NetworkX图形生成的Bokeh图中的节点排列标签

用NetworkX图形生成的Bokeh图中的节点排列标签

本文介绍了用NetworkX图形生成的Bokeh图中的节点排列标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图对来自NetworkX的网络图进行注释,并在Bokeh中对其进行可视化。我能够成功地将标签添加到ColumnDataSource中,并将它们显示在图上,但坐标似乎是错误的,因为标签没有与节点排列在一起。任何帮助将不胜感激。

I am trying to annotate a network graph which comes from NetworkX and which is visualised in Bokeh. I was able to successfully add the labels to the ColumnDataSource, and have them appear on the figure, but the coordinates appear to be wrong as the labels are not lined up with the nodes. Any help would be greatly appreciated.

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)


推荐答案

我发现了这个问题, $ c> nx.spring_layout()来获得实际上用新坐标生成新图形的坐标。相反,我使用 .layout_provider.graph_layout 从Bokeh图中拉出坐标,现在它可以按照需要运行。

I discovered the problem which was that I was using nx.spring_layout() to get the coordinates which actually generates a new graph with new coordinates. Instead I pulled the coordinates from the Bokeh figure using .layout_provider.graph_layout and it now works as desired.

这篇关于用NetworkX图形生成的Bokeh图中的节点排列标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 04:46