Search code examples
pythonmatplotlibpython-imaging-library

Save only the inside area of the plot


I would like to save only the inside are of the plot. The plot (the area I must save) has a fixed aspect ratio.

So, instead of saving this, I must save only this.

What's the simplest way to do it?

What I tried:

I can save the original file first and then crop it using PIL. That works, but if the size of the graph changes I must manually set all four values again by trial and error...

im.crop((left, top, right, bottom))

Simply disabling the axes visualisation and saving the complete area of the figure isn't ideal for my specific application.

I also tried this solution, but my axes don't start and end exactly at a tick so I can not do it that way.


Solution

  • The answer you linked is relevant, but instead of starting with the specific data values you can start with ax.get_position(), which gives you the axes bounding box as figure fraction. Then you can use the fig.transFigure transform to get from figure fraction to pixel space. Then, like the previous answer use the inverted dpi_scale_trans transform to get from pixel space to inches.

    I also here set the spines to invisible so you don't get a black line around the edge of the image.

    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots()
    ax.set_facecolor("palegreen")
    ax.set_aspect(1)
    ax.plot(range(5), "o-")
    ax.spines[:].set_visible(False)
    
    bbox = ax.get_position().transformed(fig.transFigure).transformed(fig.dpi_scale_trans.inverted())
    
    fig.savefig("test.png", bbox_inches=bbox)
    

    enter image description here