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

标签 python matplotlib plot axes

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

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

最佳答案

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

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

关于python - 如何在 Python 中将不同轴的绘图标签添加到同一图例中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30811772/

相关文章:

python - 如何将非线性模型转换为线性模型?

python - 根据 GPS 数据计算距离 [经度和纬度]

python - 从管理命令运行时,Django-nose 测试用例给出断言错误

python - 使用 host_subplot 时如何创建不同大小的子图?

python - 在 Networkx 图中绘制跟随其边缘的标签

python - 如何在 matplotlib 中删除环形图的偏离中心部分?

matlab:数据结束后绘图区域继续

python - 如何仅替换\n 之后有一些字符

python - 仅初始化 mongo 副本集一次

python - spines 在 matplotlib 中的位置