Search code examples
pandasnetworkxbokeh

failed to validate StaticLayoutProvider(id='p1075' ... expected an element of Dict(Int, Seq(Any)), got {'A': array([-7.94707039, 3.45521447]),


I am trying to draw network graphs following from this example.

Below is what I am trying to do.

`data = {
    'source': ['A', 'C', 'B', 'F', 'G'],
    'target': ['B', 'D', 'E', 'C', 'E'],
    'weight': [5, 3, 10, 4, 7]
}
df = pd.DataFrame(data=data)
G = networkx.from_pandas_edgelist(df, 'source', 'target', 'weight')
# Choose a title!
title = 'Graph Network'

# Establish which categories will appear when hovering over each node
HOVER_TOOLTIPS = [("Character", "@index")]
# Create a plot — set dimensions, toolbar, and title
plot = figure(tooltips=HOVER_TOOLTIPS,
              tools="pan,wheel_zoom,save,reset", active_scroll='wheel_zoom',
              x_range=Range1d(-10.1, 10.1), y_range=Range1d(-10.1, 10.1), title=title)

network_graph = from_networkx(G, networkx.spring_layout, scale=10, center=(0, 0))

# Set node size and color
network_graph.node_renderer.glyph = Circle(size=15, fill_color='skyblue')

# Set edge opacity and width
network_graph.edge_renderer.glyph = MultiLine(line_alpha=0.5, line_width=1)

# Add network graph to the plot
plot.renderers.append(network_graph)

return plot`

The error I get is as below;

failed to validate StaticLayoutProvider(id='p1075', ...).graph_layout: expected an 
element of Dict(Int, Seq(Any)), got {'A': array([-7.94707039,  3.45521447]), 'B': 
array([-6.60505319,  4.31869148]), 'C': array([ 8.38746457, -6.26423001]), 'D': 
array([ 6.7178286 , -6.63523276]), 'E': array([-5.66671517,  5.25260372]), 'F': 
array([10.        , -6.53836091]), 'G': array([-4.88645443,  6.41131401])}

The error is self-explanatory. The engine expects an integer as a key, but I pass a String into it.

This error is similar to this stack overflow question

However in this case, the error specifies expected an element of Dict(Either(String, Int), Seq(Any)) that both String and Int are allowed. While in my case, the error specifies that only ints are allowed.

And indeed if I simulate the source and target as integers, the graph is drawn successfully.

If it helps, I am using networkx~=2.8.8 and bokeh==3.0.3.

Can anyone help me identify what I am doing wrong.


Solution

  • I think it is still an open bug in https://github.com/bokeh/bokeh/issues/12651

    My solution is to create new Graph H, and relabel it with integer.

    mapping = dict((n, i) for i, n in enumerate(G.nodes))
    H = networkx.relabel_nodes(G, mapping)
    

    Then draw from the graph H.