如何为使用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
相关产品推荐
相关产品推荐

