Soerendip
Soerendip

Reputation: 9148

How to plot networkx graph with holoviews/bokeh with same location of nodes and edges?

I want to plot a graph generated with networkx using holoview and bokeh. Networkx runs an optimization of the graph, it seems as part of the drawing. When I feed the graph to holoviews the graph looks quite different. I am not sure what happens. I guess, the edge weights are not properly transferred, or the optimization is not carried out. (Code for jupyter notebook).

%pylab inline

import pandas as pd
import networkx as nx
import holoviews as hv

hv.extension('bokeh')
np.random.seed(111)
G=nx.Graph()
ndxs = [1,2,3,4]
G.add_nodes_from(ndxs)
G.add_weighted_edges_from([(1,2,0), (1,3,1), 
                           (1,4,-1), (2,4,1),
                           (2,3,-1), (3,4,10)])
nx.draw(G)
# or you set the random_state for the spring layout
# to make sure the figure is reproducible
nx.draw(G, nx.spring_layout(G, random_state=100))

asdf

hv.extension('bokeh')
%opts Graph [width=400 height=400]
padding = dict(x=(-1.1, 1.1), y=(-1.1, 1.1))
hv.Graph.from_networkx(G, nx.layout.circular_layout).redim.range(**padding)

enter image description here

How can the location of the nodes be conserved when plotting with holoviews/bokeh?

Upvotes: 0

Views: 2090

Answers (2)

yo1122
yo1122

Reputation: 321

You can save just the positions as a variable, and then use it both for nx and hv. For example:

position = nx.spring_layout(G, scale=2)
nx.draw(G,position)
hv.extension('bokeh')
%opts Graph [width=400 height=400]
padding = dict(x=(-1.1, 1.1), y=(-1.1, 1.1))
hv.Graph.from_networkx(G, position).redim.range(**padding)

Otherwise the fact that random-seeded positions are used will make it improbable that the graph will be drawn exactly the same twice in a row.

Upvotes: 0

Soerendip
Soerendip

Reputation: 9148

The example above uses nx.circular_layout if that is changed to nx.spring_layout the same optimization is performed and the plots look similar. I don't know how to set the random_state though.

enter image description here

Upvotes: 1

Related Questions