如何在Plotly折线图中df.tasks列有值的对应日期处添加垂直线
Plotly 折线图加任务垂直线实现方案
核心思路
你可以直接用 Plotly 内置的 add_vline() 方法遍历任务日期批量添加垂直线,同时可以给每条线添加悬停文本或者标注展示具体任务内容。
完整可运行代码
import plotly as plotly from plotly.offline import plot import plotly.express as px import plotly.graph_objects as go import pandas as pd import numpy as np # 原有测试数据 df = pd.DataFrame({'height': [712, 712, 716, 716, 718, np.nan, np.nan, np.nan, np.nan, np.nan], 'moisture': [0.06, 0.19, 0.18, 0.17, 0.18, np.nan, np.nan, np.nan, np.nan, np.nan], 'tasks': ['water', None, None, 'prune', None, None, 'position', None, 'prune', None]}, index=['2020-01-04', '2020-01-05', '2020-01-06', '2020-01-07', '2020-01-08', '2020-01-09', '2020-01-10', '2020-01-11', '2020-01-12', '2020-01-13']) df.index.name = 'date' # 原有生成基础折线图的代码 fig = px.line(df, x=df.index, y=df.height, title='植株高度变化与任务记录') # 原有筛选任务的代码 index_tasks = df[~df.tasks.isnull()] task_dict = index_tasks.groupby('date')['tasks'].apply(list).to_dict() # 新增:批量添加垂直线 y_max = df['height'].max() # 取高度最大值作为垂直线高度参考 for date, tasks in task_dict.items(): # 绘制垂直线 fig.add_vline( x=date, line_width=2, line_dash="dash", line_color="red", # 鼠标悬停显示任务内容 hovertext=f"任务:{'、'.join(tasks)}", hoverinfo="text" ) # 可选:在垂直线顶部添加任务标注 fig.add_annotation( x=date, y=y_max + 2, # 标注位置略高于最高数据点 text=f"{'、'.join(tasks)}", showarrow=False, font=dict(color="red", size=10) ) # 调整x轴日期显示格式可选 fig.update_xaxes(tickformat="%Y-%m-%d") # 显示图表 fig.show()
参数说明
line_dash:可以调整为solid/dot等样式修改垂直线的线型line_color:自定义垂直线颜色- 不需要标注的话可以直接删掉
add_annotation相关代码 - 如果需要离线保存图表,替换
fig.show()为plot(fig, filename='height_tasks.html')即可
内容的提问来源于stack exchange,提问作者Diop Chopra
相关产品推荐
相关产品推荐

