【问题标题】:How to add plot labels of different axes to the same legend in Python?如何将不同轴的绘图标签添加到Python中的同一个图例?
【发布时间】:2015-08-28 23:27:25
【问题描述】:

我正在尝试在两个 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

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

【问题讨论】:

标签: python matplotlib plot axes


【解决方案1】:

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

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

结果:

【讨论】:

    猜你喜欢
    • 2016-07-09
    • 2022-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-19
    • 2019-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多