gpt4 book ai didi

r - 如何制作带有嵌套分组变量的堆叠条形图?

转载 作者:行者123 更新时间:2023-12-03 02:29:08 25 4
gpt4 key购买 nike

我正在尝试制作一个包含两个变量的堆叠条形图。我想要的结果如下:

this

这是我的数据的第一部分。还有 220 行:

      Type      Week Stage
<chr> <dbl> <dbl>
1 Captured 1 2
2 Captured 1 1
3 Captured 1 1
4 Captured 1 2
5 Captured 1 1
6 Captured 1 3
7 Captured 1 NA
8 Captured 1 3
9 Captured 1 2
10 Captured 1 1

到目前为止我还没有取得任何进展,这是我到目前为止的代码

library(data.table)
dat.m <- melt(newrstudio2, id.vars="Type")
dat.m

library(ggplot2)
ggplot(dat.m, aes(x=Type, y=value, fill=variable)) +
geom_bar(stat="identity")

我想我需要计算每种类型每周每个阶段的观察次数?我已经尝试过长数据和宽数据,但我需要将周与类型结合起来?我不知道,我很茫然。

最佳答案

替代方式:

set.seed(123)
# sample data
my_data <- data.frame(Type = sample(c("W", "C"), 220, replace = TRUE),
Week = sample(paste0("Week ", 1:4), 220, replace = TRUE),
Stage = sample(paste0('S', 1:4), 220, replace = TRUE))
head(my_data)
library(ggplot2)

ggplot(my_data, aes(x = Type, fill = Stage)) +
geom_bar(aes(y = (..count..)/sum(..count..)), position = "fill") +
facet_grid(. ~ Week, switch="both") +
scale_y_continuous(labels = scales::percent) +
ylab("Stage [%]") +
theme(strip.background = element_blank(),
strip.placement = "outside",
panel.spacing = unit(0, "lines"))

enter image description here

关于r - 如何制作带有嵌套分组变量的堆叠条形图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54667358/

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