2

I want to save a matplotlib figure as a png file with a width/height ratio of 1.25. I specified this ratio via the figsize argument. But when I save the figure using the option bbox_inches = "tight" then the output png has a size of 553 to 396 pixels which is a ratio of 1.39. I would like to keep the bbox_inches = "tight" option to prevent unnecessary white space in the figure borders. I tried different approaches suggested in similar posts on stackoverflow but couldn't figure out a solution.

Here is example code:

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(figsize = (3, 2.4), dpi = 150)
ax = plt.subplot(111)

for i in range(3):
    ax.plot(np.random.random(10), np.random.random(10), "o", label = i)
ax.legend(bbox_to_anchor=(1, 0.6), title = "Title")
plt.ylabel("Label")
plt.xlabel("Label")
plt.title("Title", loc = "left")
plt.savefig("test.png", format = "png", dpi = 150, bbox_inches = "tight")

This is the output png enter image description here

needRhelp
  • 2,948
  • 2
  • 24
  • 48

1 Answers1

3

The bbox_inches = "tight" explicitely tells matplotlib to crop or expand the figure; any settings for the figure size will hence be lost. Thus you cannot use this option if you want to have control over the figure size.

Other options you have:

Define BBox

  • Define your own bbox_inches, which does have the desired aspect. The dimensions of the Bbox would be [[x0,y0],[x1,y1]].

    import matplotlib.transforms
    bbox = matplotlib.transforms.Bbox([[-0.2, -0.36], [3.45, 2.56]])
    plt.savefig("test.png", format = "png", dpi = 150,bbox_inches =bbox)
    

    enter image description here
    This image is now 547 x 438 pixels, thus having an aspect of 1.2488, which is as close as you can get to 1.25.

Adjust padding

  • Use the original figure size of (3, 2.4) and adjust the padding, such all elements fit into the figure. This would be done using fig.subplots_adjust().

    fig = plt.figure(figsize = (3, 2.4), dpi = 150)
    fig.subplots_adjust(top=0.89,
                        bottom=0.195,
                        left=0.21,
                        right=0.76)
    

    enter image description here
    This image now has the expected size of (3, 2.4)*150 = 450 x 360 pixels.

  • For an automatic determination of the subplot parameters, also look at this question: Creating figure with exact size and no padding (and legend outside the axes)

In general, I would recommend reading this answer to "How to put the legend out of the plot`.

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712