Reputation: 1919
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'])
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'])
I wish for the opposite - keep the output the same size and have the chart change as needed.
Upvotes: 2
Views: 882
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:
# 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)
Upvotes: 1