[英]Create Stacked "Progress" Bar Chart in R with ggplot
我正在尋找一種使用 ggplot 創建堆疊條形圖的變體的方法。 更像是一個“進度條”圖表。 我在 x 軸上有日期,在 y 軸上有一個分類變量“活動”。 每個活動都有“紅色”、“黃色”或“綠色”狀態。 我想 plot 隨着時間的推移每個活動的狀態。 問題是我沒有要提供的數字輸入。 日期顯示很奇怪,也不按時間順序排列。 希望您可以通過查看我的 plot 和下面的代碼來了解我想要做什么:
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
這是我生成 plot 的代碼。
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 %>%
group_by(activity) %>%
mutate(date_end = date + lubridate::days(7)) %>%
ungroup()
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"))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.