如何用Plotly复现R中vistime绘制的甘特图?
用Plotly复现vistime风格的甘特图
问题说明
使用vistime生成的甘特图包含案例结束标记点,且hover提示信息完整;但用ggplot+plotly实现的版本缺少结束点,且分段的hover文本与vistime不一致,需调整代码实现效果对齐。
解决方案
要对齐vistime的效果,需完成三处关键修改:
- 添加结束点标记:用
geom_point映射每个活动的结束时间点 - 自定义hover提示文本:模拟vistime的hover内容,包含活动ID、案例ID、起止时间等信息
- 统一颜色与视觉样式:复用vistime的调色板,匹配背景、网格风格
完整修改后的代码
# 导入库 -------------------------------------------------------- library(readxl) # 读取xlsx文件 library(vistime) # 生成甘特图 library(plotly) # 交互式图表 library(RColorBrewer) library(dplyr) # 数据处理 # 读取并处理数据 ------------------------------------------------ mdat = read_excel('gantt_data.xlsx') # 时间格式转换 mdat$start = strptime(mdat$start, "%Y-%m-%d %H:%M:%S") %>% as.POSIXct(tz = 'GMT', format = "%Y-%m-%d %H:%M:%OS") mdat$complete = strptime(mdat$complete, "%Y-%m-%d %H:%M:%S") %>% as.POSIXct(tz = 'GMT', format = "%Y-%m-%d %H:%M:%OS") # 定义调色板(与vistime保持一致) coul <- brewer.pal(12, "Set3") n_labels = length(unique(mdat$ActivityID)) coul <- colorRampPalette(coul)(n_labels) mdat$cols <- factor(mdat$ActivityID, labels = coul) # vistime版本甘特图(原代码保留) ------------------------------------------------------ vistime(mdat, col.event = 'ActivityID', col.group = 'CaseID', col.start = 'start', col.end = 'complete', col.color = 'cols', optimize_y = F, show_labels = F, linewidth = 25 ) %>% layout(yaxis=list(fixedrange=TRUE, tickfont=list(size=8), tickangle=-30, showgrid = T), title = "最长耗时案例甘特图", plot_bgcolor = "#e5ecf6" ) # Plotly复现版本 ------------------------------------------------------- # 自定义hover文本 mdat <- mdat %>% mutate(end = coalesce(complete, start), hover_text = paste0("活动ID: ", ActivityID, "<br>", "案例ID: ", CaseID, "<br>", "开始时间: ", format(start, "%Y-%m-%d %H:%M"), "<br>", "结束时间: ", format(end, "%Y-%m-%d %H:%M"))) p <- ggplot(mdat, aes(x=start, xend=end, y=CaseID, yend=CaseID, color=ActivityID, group=CaseID, text=hover_text)) + theme(legend.position="none", plot.background = element_rect(fill = "#e5ecf6"), panel.grid.major = element_line(color = "white")) + # 匹配vistime的背景和网格 geom_segment(size=8) + # 线段宽度与vistime一致 geom_point(aes(x=end), size=3) + # 添加结束点标记 labs(title='最长耗时案例甘特图', x='时间', y='案例ID') + scale_color_manual(values = coul) # 用之前定义的调色板 # 转换为plotly并设置tooltip ggplotly(p, tooltip = "text") %>% layout(yaxis=list(fixedrange=TRUE, tickfont=list(size=8), tickangle=-30, showgrid = TRUE), plot_bgcolor = "#e5ecf6")
修改细节说明
- 结束点添加:通过
geom_point(aes(x=end))在每个活动的结束时间位置添加标记点,大小设为3匹配vistime视觉效果 - hover文本自定义:用
mutate生成富文本格式的hover内容,在ggplotly中指定tooltip="text"确保显示自定义信息 - 视觉风格统一:复用vistime的调色板,同时调整ggplot的背景色、网格样式,让整体视觉与vistime版本一致
内容的提问来源于stack exchange,提问作者AndCh
相关产品推荐
相关产品推荐

