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.