You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用R绘制任务时间线流程图:求ggplot2 geom_tile替代方案

绘制团队任务状态分组瓷砖图:替代geom_tile的实用方案

嘿,我懂你想要的那种分团队展示任务状态的图表——蓝色的团队栏、绿色的已完成任务块、灰色的待办任务块,对吧?你原本考虑用ggplot2的geom_tile,其实除了这个,还有两个实用的现成方案,我给你详细说说,都能用你的示例数据直接跑起来!

首先先把你的示例数据放出来,方便大家复现:

df <- structure(list(task = 1:8, team = c("A", "A", "B", "A", "C", "B", "C", "A"), status = c("completed", "completed", "completed", "to do", "to do", "to do", "to do", "to do")), .Names = c("task", "team", "status"), class = "data.frame", row.names = c(NA, -8L ))

方案1:优化版ggplot2 geom_tile(最贴合你的初始思路)

如果你不想换工具,只是觉得原来的geom_tile没做出想要的效果,那可以给数据加个团队标识行,就能轻松实现蓝色团队栏的效果:

library(ggplot2)
library(dplyr)
library(tidyr)

# 生成团队分组的标识行,用来显示蓝色团队框
team_rows <- df %>%
  distinct(team) %>%
  mutate(task = NA, status = "team")

# 合并数据并排序,让团队行在每个团队任务的最上方
plot_df <- bind_rows(df, team_rows) %>%
  arrange(team, is.na(task))

# 绘制图表
ggplot(plot_df, aes(x = task, y = team)) +
  geom_tile(aes(fill = status), color = "white", size = 1.5) +
  # 自定义颜色:蓝色团队栏、绿色已完成、灰色待办
  scale_fill_manual(values = c(
    "completed" = "#2ecc71",
    "to do" = "#bdc3c7",
    "team" = "#3498db"
  )) +
  # 调整主题,让图表更清爽
  theme_minimal() +
  theme(
    axis.text.x = element_text(angle = 45, hjust = 1),
    panel.grid = element_blank(),
    legend.position = "bottom"
  ) +
  labs(x = "任务编号", y = "团队", fill = "任务状态")

这个方案的好处是完全基于你熟悉的ggplot2,只需要简单加工数据,就能实现你要的分组效果,颜色区分清晰,上手特别快。

方案2:用ComplexHeatmap实现专业分组热图

如果你需要更强大的扩展性(比如后续要加团队完成率注释、任务分类标签等),那ComplexHeatmap包是绝佳选择,它专门用来做带分组注释的热图/瓷砖图:

# 先安装包(如果没装过)
# install.packages("ComplexHeatmap")
library(ComplexHeatmap)
library(dplyr)
library(tidyr)

# 把数据转换成宽格式,方便绘制热图
wide_df <- df %>%
  mutate(status_num = case_when(
    status == "completed" ~ 1,
    status == "to do" ~ 0
  )) %>%
  pivot_wider(names_from = task, values_from = status_num)

# 提取矩阵和行名(团队名)
mat <- as.matrix(wide_df[, -1])
rownames(mat) <- wide_df$team

# 设置颜色映射:灰色待办,绿色已完成
col_fun <- circlize::colorRamp2(c(0, 1), c("#bdc3c7", "#2ecc71"))

# 创建蓝色的团队行注释
row_anno <- rowAnnotation(
  Team = rownames(mat),
  col = list(Team = rep("#3498db", nrow(mat))),
  show_legend = FALSE
)

# 绘制热图
Heatmap(
  mat,
  name = "任务状态",
  col = col_fun,
  row_names_side = "left",
  left_annotation = row_anno,
  cell_border = "white",
  column_names_gp = gpar(fontsize = 10),
  row_names_gp = gpar(fontsize = 10),
  heatmap_legend_param = list(
    at = c(0, 1),
    labels = c("待完成", "已完成"),
    title_position = "topcenter"
  )
)

这个方案的优势是灵活性极强,你可以轻松添加各种注释元素,比如在团队栏旁边加完成率的条形图,或者给任务加分类标签,适合需要做更专业可视化的场景。

内容的提问来源于stack exchange,提问作者Nicolas Rosewick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:58:57