如何在Python中将不同轴的绘图标签添加到同一个图例中?

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

我正在尝试在两个 y 轴上绘制两条曲线,如图所示。红色图(压力)为主轴,绿色(针升力)为次轴。我正在尝试将绘图标签添加到同一个图例中。但我不能将它们添加到同一个图例中。如图所示重叠,Raw 放在 Needle lift 上方。

我使用的代码:

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()

数据可用here

如何在同一个图例中添加不同坐标轴的绘图标签?当在主轴上绘制多条线时,我希望它们像您一样订购,如下所示:

问题是您创建了两个图例。只有一个你会得到更好的结果。为此,您需要存储线条艺术家:

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

# ...

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

然后您可以使用它们来创建图例,方法是提供艺术家和所需的标签(您也可以直接在此处提供字符串):

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

结果: