gpt4 book ai didi

r - ggplot2 - 向分组条形图添加差异

转载 作者:行者123 更新时间:2023-12-04 01:44:51 25 4
gpt4 key购买 nike

我在 ggplot 上绘制以下数据:

library(ggplot2)

DF <- structure(list(Type = structure(c(1L, 2L, 1L, 2L, 1L, 2L, 1L,
2L), .Label = c("Observed", "Simulated"), class = "factor"),
variable = structure(c(1L, 1L, 2L, 2L, 3L, 3L, 4L, 4L), .Label = c("EM to V6",
"V6 to R0", "R0 to R4", "R4 to R9"), class = "factor"), value = c(28,
30, 29, 35, 32, 34, 26, 29)), row.names = c(NA, -8L), .Names = c("Type",
"variable", "value"), class = "data.frame")

ggplot(DF, aes(variable, value)) +
geom_bar(aes(fill = Type), position = "dodge", stat="identity", width=.5) +
geom_text(aes(label=value, group=Type), position=position_dodge(width=0.5), vjust=-0.5) +
theme_bw(base_size = 18) +
ylab('Duration (days)') + xlab('Growth stages')

enter image description here

我想知道是否有任何图形方式可以将每组条形图之间的差异添加到图表中?

这是要添加差异的数据框:

DF2 <- data.frame(variable=c("EM to V6", "V6 to R0", "R0 to R4", "R4 to R9"), value=c(2,6,2,3)

最终图表看起来像这样(注意彩色条):

enter image description here

来源:https://www.excelcampus.com/charts/variance-clustered-column-bar-chart/

使用 ggplot 可以吗?

最佳答案

按照rawr的建议,您可以在当前的bars后面添加一层宽度稍小的bars:

library(tidyverse)
diff_df = DF %>%
group_by(variable) %>%
spread(Type, value) %>%
mutate(diff = Simulated - Observed)

ggplot(DF, aes(variable, value)) +
geom_bar(aes(y = Simulated), data = diff_df, stat = "identity", fill = "grey80", width = 0.4) +
geom_bar(aes(fill = Type), position = "dodge", stat="identity", width=.5) +
geom_text(aes(label=value, group=Type), position=position_dodge(width=0.5), vjust=-0.5) +
geom_text(aes(label = diff, y = Simulated), vjust=-0.5, data = diff_df, hjust = 2, colour = scales::muted("red")) +
theme_bw(base_size = 18) +
ylab('Duration (days)') + xlab('Growth stages')

更新代码以处理 Observed 有时高于 Simulated:

library(tidyverse)
diff_df = DF %>%
group_by(variable) %>%
spread(Type, value) %>%
mutate(diff = Simulated - Observed,
max_y = max(Simulated, Observed),
sim_higher = Simulated > Observed)

ggplot(DF, aes(variable, value)) +
geom_bar(aes(y = max_y), data = diff_df, stat = "identity", fill = "grey80", width = 0.4) +
geom_bar(aes(fill = Type), position = "dodge", stat="identity", width=.5) +
geom_text(aes(label=value, group=Type), position=position_dodge(width=0.5), vjust=-0.5) +
geom_text(aes(label = diff, y = max_y), vjust=-0.5, data = diff_df %>% filter(sim_higher),
hjust = 2, colour = scales::muted("red")) +
geom_text(aes(label = diff, y = max_y), vjust=-0.5, data = diff_df %>% filter(!sim_higher),
hjust = -1, colour = scales::muted("red")) +
theme_bw(base_size = 18) +
ylab('Duration (days)') + xlab('Growth stages')

关于r - ggplot2 - 向分组条形图添加差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44378666/

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