Plotly甘特图功能求助:实现鼠标悬停时任务条高亮
实现Plotly甘特图任务条悬停高亮
我为日志分析制作了一个Plotly甘特图,想要实现鼠标悬停在任务条上时,该任务条自动高亮的效果。尝试使用Figure Widget功能,但没达到预期目标。我的代码如下:
def create_gantt_data(df): tasks = {} gantt_data = [] for _, row in df.iterrows(): task = row['FileType'] start = row['timestamp'].to_pydatetime() # 转换为Python datetime对象 end = row['Endtime'].to_pydatetime() # 转换为Python datetime对象 method = row['Method'] # 获取Method列 if task not in tasks: tasks[task] = [] # 检查是否重叠 overlap = False for t in tasks[task]: if (start < t['end'] and end > t['start']): overlap = True break if overlap: # 为重叠任务创建新条目 task += " (重叠)" if task not in tasks: tasks[task] = [] tasks[task].append({'start': start, 'end': end}) gantt_data.append(dict( Task=task, Start=start, Finish=end, Method=method, HoverText=f"开始时间: {start}<br>结束时间: {end}<br>方法: {method}" )) return gantt_data gantt_data = create_gantt_data(df1) # 创建甘特图 fig = ff.create_gantt(gantt_data, index_col='Task', show_colorbar=True, group_tasks=True)

实现悬停高亮的方法
要实现悬停时任务条高亮,可通过FigureWidget绑定自定义悬停回调来处理,具体代码如下:
import plotly.figure_factory as ff import plotly.graph_objects as go def create_gantt_data(df): tasks = {} gantt_data = [] for _, row in df.iterrows(): task = row['FileType'] start = row['timestamp'].to_pydatetime() end = row['Endtime'].to_pydatetime() method = row['Method'] if task not in tasks: tasks[task] = [] overlap = False for t in tasks[task]: if (start < t['end'] and end > t['start']): overlap = True break if overlap: task += " (重叠)" if task not in tasks: tasks[task] = [] tasks[task].append({'start': start, 'end': end}) gantt_data.append(dict( Task=task, Start=start, Finish=end, Method=method, HoverText=f"开始时间: {start}<br>结束时间: {end}<br>方法: {method}" )) return gantt_data gantt_data = create_gantt_data(df1) # 转为FigureWidget以支持交互事件 fig = go.FigureWidget(ff.create_gantt(gantt_data, index_col='Task', show_colorbar=True, group_tasks=True)) # 保存所有任务条的原始颜色 original_colors = [trace.marker.color for trace in fig.data] def on_hover(trace, points, state): # 重置所有任务条颜色为原始状态 for i in range(len(fig.data)): fig.data[i].marker.color = original_colors[i] # 高亮当前悬停的任务条 if points.point_inds: fig.data[points.point_inds[0]].marker.color = '#ff4500' # 自定义高亮颜色 # 为每个任务条绑定悬停事件 for trace in fig.data: trace.on_hover(on_hover) # 显示图表 fig
关键说明
- 必须使用
FigureWidget而非普通Figure,才能绑定交互回调函数 - 保存原始颜色用于悬停结束后恢复样式
- 回调函数中先重置所有任务条颜色,再单独高亮当前悬停的条目
- 可自行修改
#ff4500为你需要的高亮颜色
内容的提问来源于stack exchange,提问作者Pratyush Nagpal
相关产品推荐
相关产品推荐

