如何为Matplotlib折线图添加鼠标悬停展示实际日期的数据标签功能
实现matplotlib绘图悬停显示自定义日期标签方案
使用mplcursors库可以快速实现你需要的悬停展示自定义日期标签的效果,具体操作如下:
步骤1:安装依赖包
执行如下命令安装mplcursors:
pip install mplcursors
步骤2:修改绘图代码
你只需要在原有代码基础上增加悬停回调逻辑即可,完整修改后的代码如下:
import matplotlib.pyplot as plt import numpy as np import seaborn as sns import mplcursors fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 8), constrained_layout=True) colors = ['skyblue', 'coral', 'mediumaquamarine'] Xticks = np.arange(1880, 2021, 20) # 保存绘制的折线对象用于后续绑定悬停事件 snow.plot(x='Snow Year', y=['First DOS', 'Last DOS'], color=colors, ax=ax1) snow.plot(x='Snow Year', y=['Snow length'], color='mediumaquamarine', ax=ax2) # 绘制回归曲线 sns.regplot(x='Snow Year', y='First DOS', data=snow, fit_reg=True, ax=ax1) sns.regplot(x='Snow Year', y='Last DOS', data=snow, fit_reg=True, ax=ax1) sns.regplot(x='Snow Year', y='Snow length', data=snow, fit_reg=True, ax=ax2) ax1.legend(bbox_to_anchor=(1, 1), loc="upper left") ax2.legend(bbox_to_anchor=(1, 1), loc="upper left") # 绑定悬停事件,仅对原始观测折线生效,不触发回归线悬停 cursor = mplcursors.cursor([ax1.lines[0], ax1.lines[1], ax2.lines[0]], hover=True) @cursor.connect("add") def on_add(sel): # 获取当前点对应的雪年 year = int(sel.target[0]) # 匹配雪年找到对应数据行 row = snow[snow['Snow Year'] == year].iloc[0] # 根据当前选中的折线类型返回对应标签 if sel.artist == ax1.lines[0]: # 降雪初日曲线 sel.annotation.set_text(f"雪年:{year}\n初日日序:{int(sel.target[1])}\n实际日期:{row['First Date']}") elif sel.artist == ax1.lines[1]: # 降雪终日曲线 sel.annotation.set_text(f"雪年:{year}\n终日日序:{int(sel.target[1])}\n实际日期:{row['Last Date']}") elif sel.artist == ax2.lines[0]: # 雪期长度曲线 sel.annotation.set_text(f"雪年:{year}\n雪期长度:{int(sel.target[1])}天") plt.show()
补充说明
你可以根据自己DataFrame中实际的日期列名,替换代码里row['First Date']、row['Last Date']对应的字段名,也可以通过修改sel.annotation的属性自定义悬停标签的背景色、字体大小等样式。
内容的提问来源于stack exchange,提问作者Huong Truong
相关产品推荐
相关产品推荐

