问题
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