在 R 中,我试图制作一个堆叠条形图,其中包含来自两个不同数据列的单独值,并带有误差条。但我无法找到如何创建两个 y 值相互堆叠的图形。因此,对于下面的数据,我有两个不同的产量(来自不同的物种)。将有 3 个条(每个处理),平均产量 2 堆叠在平均产量 1 之上,每个产量 1 和产量 2 都有误差条。有什么想法如何做到这一点?
治疗 | 产量1 | 产量2 |
---|---|---|
1 | 400 | 70 |
1 | 370 | 30 |
1 | 390 | 90 |
2 | 275 | 10 |
2 | 300 | 12 |
2 | 280 | 17 |
3 | 70 | 150 |
3 | 125 | 130 |
3 | 100 | 130 |
很明显我可以做一个单yield的条形图
p<- ggbarplot(df, x="Treatment", y="Yield1", add="mean_se")
但是如何在顶部堆叠 Yield2 条?
当您有多列时,第一步是将数据重塑为长格式或整齐格式。这样做你会得到一个包含可以映射到
y
上的值的列和一个包含可以映射到 fill
上的类别的列。此外,为了获得正确的堆栈顺序,我将 name
列转换为 factor
,为此我使用 forcats::fct_rev
来反转顺序。
library(ggplot2)
library(tidyr)
library(dplyr, warn = FALSE)
library(ggpubr)
df <- data.frame(
Treatment = c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L),
Yield1 = c(400L, 370L, 390L, 275L, 300L, 280L, 70L, 125L, 100L),
Yield2 = c(70L, 30L, 90L, 10L, 12L, 17L, 150L, 130L, 130L)
)
df |>
pivot_longer(-Treatment) |>
mutate(name = forcats::fct_rev(name)) |>
ggbarplot(x = "Treatment", y = "value", fill = "name", add = "mean_se")
当然,我们可以使用
ggplot2
获得相同的结果,但是这需要更多的努力,因为堆叠错误栏并不那么容易。因此,获得相同的结果需要通过计算累积和手动对误差线进行堆叠:
df |>
pivot_longer(-Treatment) |>
group_by(Treatment, name) |>
summarise(mean_se(value)) |>
mutate(across(-name, list(cum = cumsum)), name = forcats::fct_rev(name)) |>
ggplot(aes(Treatment, y, fill = name)) +
geom_col(position = "stack") +
geom_errorbar(aes(ymin = ymin_cum, ymax = ymax_cum), width = .25)
#> `summarise()` has grouped output by 'Treatment'. You can override using the
#> `.groups` argument.