简体   繁体   English

使用 ggplot 在 R 中创建堆叠的“进度”条形图

[英]Create Stacked "Progress" Bar Chart in R with ggplot

I am looking for a way to use ggplot to create a variation of a stacked bar chart.我正在寻找一种使用 ggplot 创建堆叠条形图的变体的方法。 More of like a "progress bar" chart.更像是一个“进度条”图表。 I have Dates on the x axis, and a categorical variable "activity" on the y axis.我在 x 轴上有日期,在 y 轴上有一个分类变量“活动”。 Each activity has a "Red", "Yellow", or "Green" status.每个活动都有“红色”、“黄色”或“绿色”状态。 I want to plot the status of each activity over time.我想 plot 随着时间的推移每个活动的状态。 Problem is I don't have a numeric input to supply.问题是我没有要提供的数字输入。 And the dates are displaying weird and also not in chronological order.日期显示很奇怪,也不按时间顺序排列。 Hopefully you can get the idea of what I'm trying to do by looking at my plot and code below:希望您可以通过查看我的 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

Here is my code to generate the plot.这是我生成 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"))

在此处输入图像描述

One option to achieve your desired result would be to switch to geom_rect .实现所需结果的一种选择是切换到geom_rect

As you have a categorial column to be mapped on y I transform it to a numeric which requires to put the labels back on the now continuous scale.由于您有一个要在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM