Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove padding from matplotlib plotting

I am plotting an image in matplotlib, and it keeps giving me some padding. This is what I have tried:

def field_plot():
    x = [i[0] for i in path]
    y = [i[1] for i in path]
    plt.clf()
    plt.axis([0, 560, 0, 820])
    im = plt.imread('field.jpg')
    field = plt.imshow(im)
    for i in range(len(r)):
        plt.plot(r[i][0],r[i][1],c=(rgb_number(speeds[i]),0,1-rgb_number(speeds[i])),linewidth=1)
    plt.axis('off')
    plt.savefig( IMG_DIR + 'match.png',bbox_inches='tight', transparent="True")
    plt.clf()

This is how i see the image

like image 872
andresmechali Avatar asked Jul 24 '12 19:07

andresmechali


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 .

What is padding in Matplotlib?

pad: This parameter is used for padding between the figure edge and the edges of subplots, as a fraction of the font size. h_pad, w_pad: These parameter are used for padding (height/width) between edges of adjacent subplots, as a fraction of the font size.

How do I make Axis invisible in Matplotlib?

MatPlotLib with Python Plot x and y points using the plot() method with linestyle, labels. To hide the grid, use plt. grid(False).

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.


2 Answers

Just add plt.tight_layout() before plt.savefig() !!

plt.figure(figsize=(16, 10))

# ... Doing Something ...

plt.tight_layout()
plt.savefig('wethers.png')
plt.show()
like image 38
SHIM Avatar answered Sep 18 '22 21:09

SHIM


Try using pad_inches=0, i.e.

plt.savefig( IMG_DIR + 'match.png',bbox_inches='tight', transparent="True", pad_inches=0)

From the documentation:

pad_inches: Amount of padding around the figure when bbox_inches is ‘tight’.

I think the default is pad_inches=0.1

like image 135
Keith Flower Avatar answered Sep 21 '22 21:09

Keith Flower