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

时间:2015-06-12 20:34:51

标签: python matplotlib plot axes

我试图在两个y轴上绘制两条曲线,如图所示。红色图(压力)是主轴,绿色(针抬起)是次轴。我正在尝试将绘图标签添加到同一个图例中。但我无法将它们添加到同一个传奇中。它重叠如图所示,Raw置于针上升。

enter image description here

我使用的代码:

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

如何将不同轴的绘图标签添加到同一图例?我希望在主轴上绘制多条线时按顺序排列它们,如下所示:

enter image description here

1 个答案:

答案 0 :(得分:4)

问题是你创建了两个传说。只有一个你得到更好的结果。为此你需要存储艺术家线:

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

结果:

enter image description here