0

I am using matplotlib to create multiple bar plots using the following code:

fig = plt.figure(figsize=(4, 4))
plt.barh(y=y, width=width, height=0.5)
plt.yticks(y, labels)
plt.xlabel("Contribution")
plt.tight_layout()
plt.show()

Since the length of my y-ticks labels can vary, the plot can get squeezed together as in the case below:

squeezed matplotlib plot

In other cases the plot looks fine:

enter image description here

Now, I was wondering, if there is an option in matplotlib to keep the plot size constant, but scale the figure size automatically (in horizontal direction)? My goal is that the plot size stays always the same, independent of the y-label length (because they vary inbetween plots). Thank you!

lux7
  • 1,600
  • 2
  • 18
  • 34
  • It is happening in your current case that figure (whole image) is of constant size and your axes are getting squeezed. Maybe I just understand you incorrectly but aren't you wanting to have fixed size axes (plot) and then expand whole figure to be able to fit in all axes and labels? – Roman Pavelka May 24 '21 at 12:22
  • 1
    @RomanPavelka Yes, you are right. I would like that the plot size stays always the same (or as you said fixed size axes) and automatically expand the figure to fit all labels – lux7 May 24 '21 at 12:41
  • You could try using `set_box_aspect`, so that the aspect ratio of the two axes is always a fixed value https://matplotlib.org/devdocs/api/_as_gen/matplotlib.axes.Axes.set_box_aspect.html#matplotlib.axes.Axes.set_box_aspect – Matt Pitkin May 24 '21 at 12:42
  • These two sources should help you, but I would just keep figsize large enough for all cases... https://stackoverflow.com/questions/19306510/determine-matplotlib-axis-size-in-pixels https://stackabuse.com/change-figure-size-in-matplotlib/ – Roman Pavelka May 24 '21 at 12:48
  • My comment about using `set_box_aspect` will work to keep the axes boxes the same size, but unfortunately it will just cause the tick mark text to get truncated by the figure boundary, so probably isn't what your looking for. – Matt Pitkin May 24 '21 at 12:58

0 Answers0