How To Pass Node Attributes From NetworkX To Bokeh
Solution 1:
GOT IT
The color attribute I was seeing everyone set through the various attributes (like degree of centrality, etc...) was done through a color map instance, but that is NOT required for setting sets of nodes as different colors or sizes.
The key here is the way the ColumnDataSource (CDS) was constructed. By using the line:
nodes_source = ColumnDataSource(dict(x=nodes_xs, y=nodes_ys,name=nodes)
There is no assignment of color or size as an attribute. Worse, I wasn't able to see what the CDS actually looked like. (Which I now know you can view as a pandas DF by calling the CDS.to_df()) So, I experimented and found that I can add a column by:
node_color=pd.DataFrame.from_dict({k:v for k,v in network.nodes(data=True)},orient='index').color.tolist()
color = tuple(node_color)
nodes_source = ColumnDataSource(dict(x=nodes_xs, y=nodes_ys,name=nodes, _color_= color)
This assigned the attribute that I retrieved from networkX as a value for each node as a function of its ID, passed it to a tuple, then placed it in the CDS which will be retrieved by asking the Bokeh construction to retrieve data from the column who's name is passed as a** STRING**:
plot = figure(plot_width=800, plot_height=400,tools=['tap', hover, 'box_zoom', 'reset'])
r_circles = plot.circle('x', 'y', source=nodes_source, size=10,fill_color="_color_", level = 'overlay')
To answer all 3 questions:
from_networkx retrieves all the characteristics of the nodes, [at least] if retrieved through the from_graphml() function.
The easy way to assign a columndatavalue is to pass it a tuple, as demonstrated above with a color attribute. However, this is where you can add things into the CDS that you may retrieve from the hover tool. For me, this will be very useful.
Construct a pandas DF with all the attributes you want, then use the CDS.from_df() function to pass it to a CDS for bokeh to analyze.
Solution 2:
Maybe the answers under this question can help you: https://stackoverflow.com/a/54475870/8123623
Create a dict where the nodes are the keys and the colors the values.
colors = [...]
colors = dict(zip(network.nodes, colors))
nx.set_node_attributes(network, {k:v for k,v in colors.items()},'colors' )
graph.node_renderer.glyph = Circle(size=5, fill_color='colors')
This is how you can use from_network()
graph = from_networkx(G, nx.dot, scale=1, center=(0,0))
Post a Comment for "How To Pass Node Attributes From NetworkX To Bokeh"