DeanLa
DeanLa

Reputation: 1919

Matplotlib force figure size of output image

I'm creating a matplotlib figure. And I want the size (or at least the aspect ratio) of the output image to be consistent. It seems like using figsize changes the contained figure but not the image.

fig, ax = plt.subplots(figsize=(9,9))
ax.barh([0,1,2],[1,5,3])
ax.set_yticks([0,1,2])
ax.set_yticklabels(['a','b','c'])

Creates the following: enter image description here

While a change in the ticklabels enlarges the image

fig, ax = plt.subplots(figsize=(9,9))
ax.barh([0,1,2],[1,5,3])
ax.set_yticks([0,1,2])
ax.set_yticklabels(['a really really really really really really long name','b','c'])

enter image description here

I wish for the opposite - keep the output the same size and have the chart change as needed.

Upvotes: 2

Views: 882

Answers (1)

Sheldore
Sheldore

Reputation: 39072

I was able to devise the following solution. It does the trick somewhat although I do not claim it to be the best solution. The idea is the following:

  1. Get the width of the y-ticklabels in inches (I used this method)
  2. Extract the maximum width i.e. for the longest tick-label
  3. Reset the figure size at the end using width = 9-max(label width)

# Rest of your code

fig.canvas.draw()

# Get the labels' widths in inches
label_widths = [item.get_window_extent().transformed(fig.dpi_scale_trans.inverted()).width 
                for item in ax.get_yticklabels()]

Since the original size was 9 inches by 9 inches, rescale the size
fig.set_size_inches((9-max(label_widths)), 9)

enter image description here

Upvotes: 1

Related Questions