1
votes

In matplotlib, I want to plot a legend, and put the legend below the figure. So I write codes like this:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(5, 7), dpi=300)
ax = fig.add_subplot(111, position=[0.1, 0.28, 0.8, 0.65])
labels = []
for i in range(20):
    ax.plot(data[i, :])
    labels.append(str(i))
ax.legend(labels, ncol=10, loc="lower center", bbox_to_anchor=(0.5, -0.15), prop={"size":6}) 
plt.show()

It works well. But, actually I'm not sure what height the legend is, for example, if I change ncol=5 or ncol=2, the legend's top and the figure's bottom would be overlapped. In my opinion, this situation appears because the first two parameters of bbox_to_anchor are the lower left corner coordinates of the bounding box. Of course changing bbox_to_anchor=(0.5, 1) to set legend above would also be a solution, but in my opinion the best solution may be setting bbox_to_anchor's parameters as the upper left corner coordinates, and letting the bbox go down from up.

So my question is, is there a way to make bbox_to_anchor's origin upper but not lower?

Thank you!

1

1 Answers

1
votes

You should use loc="upper center" in the ax.legend call. When loc and bbox_to_anchor are both used, loc specifies which part of the legend box should be put at the position given by bbox_to_anchor.