Draw graph in NetworkX

Each Answer to this Q is separated by one/two green lines.

I’m trying to draw any graph in NetworkX, but get nothing, not even errors:

import networkx as nx
import matplotlib.pyplot as plt

Add to the end:


import networkx as nx
import matplotlib.pyplot as plt
g1 = nx.petersen_graph()

When run from an interactive shell where plt.ion() has been called, the plt.show() is not needed. This is probably why it is omitted in a lot of examples.

If you run these commands from a script (where plt.ion() has not been called), the plt.show() is needed. plt.ion() is okay for interactive sessions, but is not recommended for scripts.

in ipython notebook, just type in magic

%matplotlib inline


%matplotlib notebook

You can easily plot with networkx graphs using jupyter notebook. See first example.

OR, you can use Bokeh to plot graphs, which adds useful features.
The package holoviews makes it even simpler to plot a graphs with bokeh. It adds features like automatic highlighting and show of labels while hovering over nodes. However, editing colors etc. seems to be an issue.

%pylab inline  
# `pylab notebook`  # for interactive plots

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

ndxs = [1,2,3,4]
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, nx.spring_layout(G, random_state=100))

enter image description here

And here the example with bokeh and holoview:

%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.spring_layout).redim.range(**padding)

enter image description here

You should give it a try and plot it in your notebook to see the difference.

It works fine by adding:

import matplotlib.pyplot as plt

to your code. mine worked fine.

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .