Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving a matplotlib/networkx figure without margins

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.

like image 595
Aya Avatar asked Jul 02 '12 18:07

Aya


People also ask

How do I remove the margins in Matplotlib?

The python plotting library matplotlib will by default add margins to any plot that it generates. They can be reduced to a certain degree through some options of savefig() , namely bbox_inches='tight' and pad_inches=0 .

How do I save a Matplotlib figure without white space?

Hide the Whitespaces and Borders in Matplotlib Figure To get rid of whitespace around the border, we can set bbox_inches='tight' in the savefig() method. Similarly, to remove the white border around the image while we set pad_inches = 0 in the savefig() method.

What is BBOX in Matplotlib?

BboxTransformTo is a transformation that linearly transforms points from the unit bounding box to a given Bbox. In your case, the transform itself is based upon a TransformedBBox which again has a Bbox upon which it is based and a transform - for this nested instance an Affine2D transform.


1 Answers

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?)

like image 160
BrenBarn Avatar answered Sep 19 '22 06:09

BrenBarn