How to add plot labels of different axes to the same legend in Python?

1.3k views Asked by At

I am trying to plot two curves on two y-axes as shown in figure. The red plot (pressure) the primary axis and green (needle lift) the secondary axis. And I am trying to add the plot labels to the same legend. But I cannot add them to the same legend. It overlaps as shown in figure, Raw placed above Needle lift.

enter image description here

The code I used:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import ticker as mtick
data = np.genfromtxt("secondary_axis.dat", skiprows = 2, delimiter = ',')
time = data[:, 0]
pressure = data[:, 1] * 0.006894759086775369
pressure_charge = data[0, 0]
needle_lift = data[:, 2]
figure = plt.figure(figsize=(5.15, 5.15))
figure.clf()
plot = plt.subplot(111)
plot.plot(time, pressure, label = r'\textit{Raw}')
plot.set_xlabel(r'\textit{X}', labelpad=6)
plot.set_ylabel(r'\textit{Y}', labelpad=6)
primary_ticks = len(plot.yaxis.get_major_ticks())
ax2 = plot.twinx()
ax2.plot(time, needle_lift, label = r'\textit{Needle lift}', color='#4DAF4A')
plot.set_zorder(ax2.get_zorder()+2)
plot.patch.set_visible(False)
ax2.grid(False)
ax2.set_ylabel(r'\textit{Z}', labelpad=6)
ax2.yaxis.set_major_locator(mtick.LinearLocator(primary_ticks))
plot.legend(loc = 'center left', bbox_to_anchor = (1.2, 0.5))
ax2.legend(loc = 'center left', bbox_to_anchor = (1.2, 0.5))
plt.show()

The data is available here

How to add plot labels of different axes to the same legend? I want them to be ordered as you when multiple lines are plot on the primary axis as given below:

enter image description here

1

There are 1 answers

0
hitzg On BEST ANSWER

The problem is that you create two legends. You get nicer results with only one. For that you need to store the line artists:

l1, = plot.plot(time, pressure, label=r'\textit{Raw}')

# ...

l2, = ax2.plot(time, needle_lift, label=r'\textit{Needle lift}', color='#4DAF4A')

And then you can use them to create the legend, by supplying the artists and the desired labels (you could also provide the strings here directly):

plt.legend((l1, l2), (l1.get_label(), l2.get_label()), loc='center left', 
        bbox_to_anchor=(1.2, 0.5))

Result:

enter image description here