gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 03:33:40 25 4
gpt4 key购买 nike

我正在寻找一种使用 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"))

enter image description here

最佳答案

实现所需结果的一个选项是切换到 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"))

关于r - 使用 ggplot 在 R 中创建堆叠的 "Progress"条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70309540/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com