2

I am plotting similar information with subplots using matplotlib. I have 2 plots on a 1x2 grid, all with the same number of lines. I am trying to make a common legend for both plots. I have seen suggested the function get_legend_handles_labels in different places. Currently, my code is the following:

import matplotlib.pyplot as plt

fig, ax = plt.subplots(1,2, figsize=(10,5), sharey=True, sharex=True)
plt.tight_layout()

ax[0].plot(time, mindist_A, zorder=1, label='Minimum distance between protein A and its period image')
ax[1].plot(time, mindist_B, zorder=1, label='Minimum distance between protein B and its period image', color='g')
ax[0].hlines(y=1, xmin=0.0, xmax=2000000.0, color='r', lw=2, zorder=2)
ax[1].hlines(y=1, xmin=0.0, xmax=2000000.0, color='r', lw=2, zorder=2, label='Cut-off')

plt.ticklabel_format(axis='x', style='sci', scilimits=(0,0), useOffset=False)
ax[0].set_ylabel('Distance')
ax[0].set_xlabel('Time')
ax[1].set_xlabel('Time')

handles, labels = ax.get_legend_handles_labels()
fig.legend(handles, labels, loc='upper center')

plt.show()

In my legend I would like to see "Minimum distance between protein A and its period image", "Minimum distance between protein B and its period image" and "Cut-off".

I am getting the following error:

AttributeError: 'numpy.ndarray' object has no attribute 'get_legend_handles_labels'

I assume I have an error when I apply get_legend_handles_labels but I do not see how to solve it.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
mariofp77
  • 115
  • 5
  • 2
    `handles, labels = ax[1].get_legend_handles_labels()` – BigBen Mar 04 '20 at 20:21
  • In that case, I do not get printed the legend corresponding to the first plot. I am editing my question now to make it more clear. – mariofp77 Mar 04 '20 at 20:25
  • IIUC, [this answer](https://stackoverflow.com/a/57484812/9245853) may be useful then. – BigBen Mar 04 '20 at 20:27
  • Great! Thank you very much! – mariofp77 Mar 04 '20 at 20:28
  • Does this answer your question? [how do I make a single legend for many subplots with matplotlib?](https://stackoverflow.com/questions/9834452/how-do-i-make-a-single-legend-for-many-subplots-with-matplotlib) – mkrieger1 Mar 04 '20 at 21:29
  • I initially took the idea from https://stackoverflow.com/a/46921590/8605536 in that question, but @BigBen's answer solved my problem. Many thanks! – mariofp77 Mar 04 '20 at 22:28

0 Answers0