You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为使用Pandas数据的多Y轴绘图添加图例?现有绘制效果满意仅缺图例

你可以通过为每个绘图对象指定label参数,再合并双轴的图例元素的方式添加所需图例,修改后完整代码如下:

# data from pandas df's
zoom_plot = fc1_dataset.loc['2021-8-9'].between_time('5:00', '17:00')
_no_vfd_sig = zoom_plot[['fc1_flag','duct_static','duct_static_setpoint']]
_vfdsig = zoom_plot.vfd_speed


# using subplots() function
fig, ax = plt.subplots(figsize=(25,8))
plt.title('Visually verify FDD is flagging OK')
 
# using the twinx() for creating another
# axes object for secondary y-Axis
ax2 = ax.twinx()
# 给左侧Y轴的三个数据序列添加label
lines1 = ax.plot(zoom_plot.index, _no_vfd_sig, label=['fc1_flag','duct_static','duct_static_setpoint'])
# 给右侧Y轴的风扇转速序列添加label
lines2 = ax2.plot(zoom_plot.index, _vfdsig, color = 'r', label='vfd_speed')

# 合并两个轴的图例元素
all_lines = lines1 + lines2
all_labels = [line.get_label() for line in all_lines]
# 生成图例,loc参数可调整图例位置,避免遮挡数据
ax.legend(all_lines, all_labels, loc='upper right')
 
# giving labels to the axises
ax.set_xlabel('Date')
ax.set_ylabel('Duct Pressure and FDD Flag')

# secondary y-axis label
ax2.set_ylabel('% Fan Speed')

# defining display layout
plt.tight_layout()
 
# show plot
plt.show()

如果希望图例不遮挡绘图区域,也可以将ax.legend一行替换为如下代码,将图例放在图外侧:

ax.legend(all_lines, all_labels, loc='upper left', bbox_to_anchor=(1.15, 1))

内容的提问来源于stack exchange,提问作者bbartling

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 07:45:02