Using bokeh: How does one plot variable size nodes, and node colors?

一个人想着一个人 提交于 2019-12-03 16:41:07
Aswani kumar Arisetty

I was trying to set the node size based on the degree centrality as well and was able to do so using

graph.node_renderer.data_source = source

I can see the differing sizes and colors (see attached image), although I could not find the reason for the below error yet

E-1010 (CDSVIEW_SOURCE_DOESNT_MATCH): CDSView used by Glyph renderer must have a source that matches the Glyph renderer's data source: GlyphRenderer(id='035dd78a-7bff-40d1-8357-d7193222ca02', ...)

    #just to make the sizes visible
    node_size = {k:5*v for k,v in G.degree().items()} 


### set node attributes
    nx.set_node_attributes(G, 'node_color', node_color)
    nx.set_node_attributes(G, 'node_size', node_size)

    source=ColumnDataSource(pd.DataFrame.from_dict({k:v for k,v in G.nodes(data=True)},orient='index'))
    mapper = LinearColorMapper(palette=pal_hex_lst, low=0, high=21)

### Initiate bokeh plot
    plot = figure(title="Resized Node Demo", x_range=(-1.1,1.1), y_range=(-1.1,1.1),
              tools="", toolbar_location=None)

    # Graph renderer using nx
    graph = from_networkx(G, nx.spring_layout, scale=2, center=(0,0))

    # Style node
    graph.node_renderer.data_source = source
    graph.node_renderer.glyph = Circle(size='node_size', fill_color={'field': 'node_color', 'transform': mapper})


    plot.renderers.append(graph)

Was looking for something similar. Maybe it helps someone else.

You can change it in the same way as changing the node size. So there is no need to use pandas which could also mix up sth. if used in the wrong way.

You can create a list where the colors for each node is stored. Then add the color information:

colors = [...]
graph.node_renderer.data_source.data['colors'] = colors
graph.node_renderer.glyph = Circle(size='degrees', fill_color='colors')

Or if you really want to use node attributes then you can do this using a dict: create a list with all colors first:

colors = [...]
colors = dict(zip(G.nodes, colors))
nx.set_node_attributes(G, {k:v for k,v in colors.items()},'colors' )
graph.node_renderer.glyph = Circle(size='degrees', fill_color='colors')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!