import networkx as nx import matplotlib.pyplot as plt import StringIO from matplotlib.figure import Figure class MyGraph(nx.Graph): def _repr_svg_(self): plt.ioff() # turn off interactive mode fig=plt.figure(figsize=(2,2)) ax = fig.add_subplot(111) nx.draw_shell(self, ax=ax) output = StringIO.StringIO() fig.savefig(output,format='svg') plt.ion() # turn on interactive mode return output.getvalue() g=nx.random_graphs.binomial_graph(10,.5) f=MyGraph(g) f f.remove_nodes_from([0,3,7,5] ) f # this triggers the _repr_svg function in the notebook import matplotlib.pyplot as plt from io import BytesIO def graph_to_svg(g): """return the SVG of a matplotlib figure generated from a graph""" fig=plt.figure(figsize=(2,2)) ax = fig.add_subplot(111) nx.draw_shell(g, ax=ax) output = BytesIO() fig.savefig(output, format='svg') plt.close(fig) return output.getvalue() from IPython.display import display, SVG display(SVG(graph_to_svg(g))) formatter = get_ipython().display_formatter.formatters['image/svg+xml'] formatter.for_type(nx.Graph, graph_to_svg) g g.remove_nodes_from([0,3,7,5]) g # this triggers the graph_to_svg function in the notebook