我正在尋找一種使用 ggplot 創建堆疊條形圖變體的方法。更像是“進度條”圖表。我在 x 軸上有日期,在 y 軸上有一個分類變數“活動”。每個活動都有“紅色”、“黃色”或“綠色”狀態。我想隨著時間的推移繪制每個活動的狀態。問題是我沒有要提供的數字輸入。而且日期顯示很奇怪,也沒有按時間順序排列。希望您可以通過查看下面的情節和代碼來了解我正在嘗試做什么:
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"))

uj5u.com熱心網友回復:
實作所需結果的一種選擇是切換到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"))

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/381240.html
上一篇:您如何制作一個回圈,以便一遍又一遍地創建相同的圖形,但每次都針對不同的變數?
下一篇:ggplot2垂直顏色條標題居中
