Saving a matplotlib/networkx figure without margins

Aya picture Aya · Jul 2, 2012 · Viewed 9.6k times · Source

When I draw a figure using matplotlib how do I save it without extra margins? Usually when I save it as

plt.savefig("figure.png") # or .pdf

I get it with some margins:

enter image description here

Example:

import matplotlib.pyplot as plt
import networkx as nx

G=nx.Graph()

G.add_edge('a','b',weight=1)
G.add_edge('a','c',weight=1)
G.add_edge('a','d',weight=1)
G.add_edge('a','e',weight=1)
G.add_edge('a','f',weight=1)
G.add_edge('a','g',weight=1)

pos=nx.spring_layout(G)
nx.draw_networkx_nodes(G,pos,node_size=1200,node_shape='o',node_color='0.75')

nx.draw_networkx_edges(G,pos,
                width=2,edge_color='b')

plt.axis('off')
plt.savefig("degree.png", bbox_inches="tight")
plt.show() 

Update 2:

The spaces are set inside the axes.. This is clear if I remove plt.axis('off')
So I think there is some trick to use with the package Networkx.

Answer

BrenBarn picture BrenBarn · Jul 2, 2012

Try plt.savefig("figure.png", bbox_inches="tight").

Edit: Ah, you didn't mention you were using networkx (although now I see it's listed in a tag). bbox_inches="tight" is the way to crop the figure tightly. I don't know what networkx is doing, but I imagine it's setting some plot parameters that are adding extra space to the axes. You should look for a solution in networkx rather than matplotlib. (It may be, for instance, that networkx is adding the space inside the axes, not the figure; what does it look like if you remove that axis('off') call?)