0

There are several questions in StackOverflow regarding the position of the legend in Python's matplotlib.pyplot. For a single graph, the problem can often be solved by tweaking parameters location and bbox_to_anchor. In the following example, the legend can be placed above the graph with bbox_to_anchor = (0.5,1.3).

industry_capm_df.plot.bar
ax = plt.axes()
ax.legend(bbox_to_anchor=(0.5,1.3))

enter image description here

Yet, for this other graph, the same parameters (0.5,1.3) result in a legend slightly out of alignment.

industry_raw_df.plot.bar
ax = plt.axes()
ax.legend(bbox_to_anchor=(0.5,1.3))

enter image description here

Since I got several graphs to plot, I would like legend alignment to be automatic, without having to tweak bbox_to_anchor every time. How could I solve this?

Zephyr
  • 11,891
  • 53
  • 45
  • 80
Incognito
  • 331
  • 1
  • 5
  • 14
  • This answer may be useful to you, they describe how to automatically place the legend according to the axis (by transforming to figure coordinates) https://stackoverflow.com/a/45846024/11080708 – M-Wi Jul 20 '20 at 19:00
  • @Incognito do you want same width and height or only that the left edge be aligned with the axis? – BlackBear Jul 20 '20 at 19:24
  • Only the alignment – Incognito Jul 20 '20 at 21:57

1 Answers1

0

You should add loc='lower left' to specify that the coordinates in bbox_to_anchor refer to the lower left corner of the legend:

ax.legend(loc='lower left', bbox_to_anchor=(0, 1.03), borderaxespad=0)

borderaxespad is to disable padding outside the box, so that the left edge is perfectly aligned with the axis. Then we add a bit of padding (0.03) so that the bottom edge is slightly above the top of the chart.

Reference: https://matplotlib.org/3.2.1/api/_as_gen/matplotlib.pyplot.legend.html

BlackBear
  • 22,411
  • 10
  • 48
  • 86