48

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

import networkx as nx import matplotlib.pyplot as plt g1=nx.petersen_graph() nx.draw(g1) 
1
  • 2
    also make sure you are using an interactive backend. What does matplotlib.get_backend() return? Commented Oct 6, 2013 at 20:02

4 Answers 4

75

Add to the end:

plt.show() 

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

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.

Sign up to request clarification or add additional context in comments.

2 Comments

show() helped. Thanks for this. I ended up saving figures without show().
That was a perfect explanation; thank you, @unutbu . I have another question though: How do networkx and matplotlib interact each other? Are there any dependencies or a sort of a relation between them?
5

in ipython notebook, just type in magic

%matplotlib inline 

or

%matplotlib notebook 

Comments

5

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 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, nx.spring_layout(G, random_state=100)) 

enter image description here

And here the example with bokeh and holoview:

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.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.

Comments

2

It works fine by adding:

import matplotlib.pyplot as plt plt.show() 

to your code. mine worked fine.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.