0

I am trying to put a legend below a graph but keeping the figure size fixed. Is this possible?

I saw How to put the legend out of matplotlib plot and https://stackoverflow.com/a/4701285/7746941 but the first one does not address fitting the legend within a predefined figure size while the second one does not do this generically (there is an example where the axes width is shrunk by 0.8 to accommodate the legend) .

Below is my current solution that anchors the legend at the bottom of the graph but the legend does not fit the figure.

I cannot figure out how to determine the height of the legend box to move the axis up by that amount.

import pandas as pd
df = pd.DataFrame({'a': [1,2,3], 'b': [4,5,6]})
ax = df.plot(figsize=(4,4))
tight_box = ax.transAxes.inverted().transform(ax.get_tightbbox(ax.figure.canvas.get_renderer()))
leg = ax.legend(bbox_to_anchor=(0,tight_box[0][1],1,0), loc='upper center')
user3124206
  • 375
  • 1
  • 7
  • 16
  • 1
    I think you'll find useful stuff in this answer https://stackoverflow.com/a/4701285/7746941 – nahusznaj Jul 03 '18 at 15:50
  • Did you read my answer to [this question](https://stackoverflow.com/questions/42994338/creating-figure-with-exact-size-and-no-padding-and-legend-outside-the-axes)? It seems to me this is exactly what you want. – ImportanceOfBeingErnest Jul 03 '18 at 16:19
  • Yes, this is perfect! Not sure how I missed that question. In my own attempt to do this, I missed the ax.figure.canvas.draw() bit. Thank you! – user3124206 Jul 03 '18 at 16:48
  • I can't figure out a way to close this as a duplicate, can you please mark it as such? – user3124206 Jul 03 '18 at 16:50

0 Answers0