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

旧城冷巷雨未停 提交于 2019-12-24 20:12:23

问题


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)

回答1:


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.



来源:https://stackoverflow.com/questions/48389481/lining-up-labels-with-the-nodes-on-a-bokeh-figure-generated-from-a-networkx-grap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!