使用 ggplot 在 R 中创建堆叠 "Progress" 条形图

Create Stacked "Progress" Bar Chart in R with ggplot

我正在寻找一种使用 ggplot 创建堆叠条形图变体的方法。更像是一个“进度条”图表。我在 x 轴上有日期,在 y 轴上有一个分类变量“activity”。每个 activity 都有“红色”、“黄色”或“绿色”状态。我想随着时间的推移绘制每个 activity 的状态。问题是我没有要提供的数字输入。而且日期显示很奇怪,而且也不按时间顺序排列。希望您可以通过查看下面的情节和代码了解我正在尝试做的事情:

activity    date     status
a          11-10-21   red
a          11-17-21   red
a          11-24-21   yellow
a          12-01-21   green
b          11-10-21   red
b          11-17-21   yellow
b          11-24-21   green
b          12-01-21   green
c          11-10-21   yellow
c          11-17-21   green
c          11-24-21   green
c          12-01-21   green

这是我生成情节的代码。

activity <- c("a", "a", "a", "a", "b", "b", "b", "b", "c", "c", "c", "c")
date <- c("2021-11-10", "2021-11-17", "2021-11-24", "2021-12-01", "2021-11-10", "2021-11-17", 
"2021-11-24", "2021-12-01", "2021-11-10", "2021-11-17", "2021-11-24", "2021-12-01")
status <- c("red", "red", "yellow", "green", "red", "yellow", "green", "green", "yellow", 
"green", "green", "green")


df <- data.frame(activity, date, status)

df$activity <- as.factor(df$activity)
df$date <- as.Date(df$date)
df$status <- as.factor(df$status)

ggplot(df, aes(x=date, y=activity, fill = status)) + geom_bar(stat = "identity") +
scale_fill_manual(values = c("#6FC750", "#CC5939", "#D1CB28"))

实现您想要的结果的一个选择是切换到 geom_rect

由于您有一个要映射到 y 上的分类列,我将其转换为数字,这需要将标签放回到现在的连续刻度上。

library(ggplot2)
library(dplyr)
library(lubridate)

df <- df %>% 
  mutate(date_end = date + lubridate::days(7))

width = .6

breaks <- seq(levels(factor(activity)))
labels <- levels(factor(activity))
ggplot(df, aes(fill = status)) + 
  geom_rect(aes(xmin = date, xmax = date_end, 
                ymin = as.numeric(factor(activity))  - width / 2, 
                ymax = as.numeric(factor(activity))  + width / 2)) +
  scale_y_continuous(breaks = breaks, labels= labels) +
  scale_fill_manual(values = c("#6FC750", "#CC5939", "#D1CB28"))

编辑

set.seed(42)

df <- df %>% 
  mutate(date_end = date + lubridate::days(sample(3:7, nrow(.), replace = TRUE)))

width = .6

breaks <- seq(levels(factor(activity)))
labels <- levels(factor(activity))
ggplot(df, aes(fill = status)) + 
  geom_rect(aes(xmin = date, xmax = date_end, 
                ymin = as.numeric(factor(activity))  - width / 2, 
                ymax = as.numeric(factor(activity))  + width / 2)) +
  scale_y_continuous(breaks = breaks, labels= labels) +
  scale_fill_manual(values = c("#6FC750", "#CC5939", "#D1CB28"))