gpt4 book ai didi

r - 错误条在堆积条形图中的位置不正确 (r)

转载 作者:行者123 更新时间:2023-12-01 03:09:47 25 4
gpt4 key购买 nike

我试图基于此制作带有误差线的堆积条形图,先前回答的问题 Making stacked bar plot with specified error bar values in R

但是,我的误差线位置不正确。我试过改变 SD 的顺序,这会相对于彼此移动误差线,但它们仍然没有与堆叠的条形对齐。

x <- data.frame(Period = c("Mon","Tue","Wed","Thu","Fri","Sat","Sun"), Sample = c("Day","Day","Day","Day","Day","Day","Day"), "12AM-6AM" = c(23.14,16.43,16,22.71,36.86,87.14,110.71), "6AM-12PM" = c(16.14,20.86,18.43,16.71,15.14,14.29,16), "12PM-6PM" = c(26.86,23.71,25.57,23.43,35.29,38,30), "6PM-12AM" =c(35.86,34.14,31.71,36.43,45.57,44,27.14))

library(dplyr)
library(reshape2)

mx <- melt(x, id.vars=1:2)
mx <- mx %>% group_by(Period) %>%
mutate(pos = cumsum(value)) %>%
ungroup() %>%
mutate(sd = c( 5.4, 2.7, 4.7, 4.4, 8.2, 13.2, 20.7,
5.6, 2.3, 5.4, 5.5, 1.6, 4.1, 3.1,
5.2, 5.6, 5.9, 3.5, 6.3, 4.5, 6.9,
3.5, 6.0, 5.9, 6.2, 8.2, 9.0, 2.4
),
upper = pos + sd/2,
lower = pos - sd/2)

days<-c("Mon", "Tue", "Wed","Thu","Fri", "Sat", "Sun")
ggplot(mx, aes(x=Period, y=value, fill=variable), xLabels=NA) +
geom_bar(stat="identity") +
facet_grid(~Sample) + geom_errorbar(aes(ymin = lower, ymax = upper),
width = .2, col = "red") +
theme_bw() + scale_x_discrete(limits = days) +
xlab(" Day of the Week") + scale_fill_grey() +
ylab ("Number of calls")

enter image description here

另外,我对 R 很陌生,甚至对堆栈溢出也很陌生(这是我的第一个问题!)-因此,对于如何更清晰或更有效地设置问题格式的建议,我总是很感激:)

最佳答案

我认为这是因为 variable在 y 轴上从上到下绘制,但总和在 cumsum(value)计算假设它们是从下到上绘制的。

我在求和之前重新排序了数据框,然后它起作用了:

x <- data.frame(Period = c("Mon","Tue","Wed","Thu","Fri","Sat","Sun"), Sample = c("Day","Day","Day","Day","Day","Day","Day"), "12AM-6AM" = c(23.14,16.43,16,22.71,36.86,87.14,110.71), "6AM-12PM" = c(16.14,20.86,18.43,16.71,15.14,14.29,16), "12PM-6PM" = c(26.86,23.71,25.57,23.43,35.29,38,30), "6PM-12AM" =c(35.86,34.14,31.71,36.43,45.57,44,27.14))

library(tidyverse)
library(reshape2)
#>
#> Attaching package: 'reshape2'
#> The following object is masked from 'package:tidyr':
#>
#> smiths

mx <- melt(x, id.vars=1:2)
mx <- mx %>%
mutate(sd = c( 5.4, 2.7, 4.7, 4.4, 8.2, 13.2, 20.7,
5.6, 2.3, 5.4, 5.5, 1.6, 4.1, 3.1,
5.2, 5.6, 5.9, 3.5, 6.3, 4.5, 6.9,
3.5, 6.0, 5.9, 6.2, 8.2, 9.0, 2.4)
) %>%
group_by(Period) %>%
arrange(desc(variable)) %>%
mutate(
pos = cumsum(value),
upper = pos + sd/2,
lower = pos - sd/2
) %>%
ungroup()

days<-c("Mon", "Tue", "Wed","Thu","Fri", "Sat", "Sun")
ggplot(mx, aes(x=Period, y=value, fill=variable), xLabels=NA) +
geom_bar(stat="identity") +
facet_grid(~Sample) + geom_errorbar(aes(ymin = lower, ymax = upper),
width = .2, col = "red") +
theme_bw() + scale_x_discrete(limits = days) +
xlab(" Day of the Week") + scale_fill_grey() +
ylab ("Number of calls")



创建于 2018-11-10 由 reprex package (v0.2.1)

关于r - 错误条在堆积条形图中的位置不正确 (r),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53241804/

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