在 ggplot2 中,在具有多个自变量的数据中跨 Facets 生成误差条
In ggplot2, generate error bars across Facets in a data with multiple independent variables
我正在尝试将误差条放在数据框的平均值上,该数据框具有三个自变量并绘制为 facet_grid。但是,下面的图将错误栏放在了错误的方面。谁能帮帮我?
请参阅下面的示例数据和相关代码:
life <- rep(c("1d", "2d", "4d"), 2, each = 2)
trt <- rep(c("c1", "c2"), 6)
species <- rep(c("SP1", "SP2"), each = 6)
mean_v <- runif(12, 12, 45)
sem_v <- runif(12, 1, 4)
data1 <- data.frame(life, trt, species, mean_v, sem_v)
plot1 <- ggplot(data1, aes(x = trt, y = mean_v, group = species, fill = species))
plot1 + geom_bar(stat = "identity", position = "dodge") +
facet_grid(~life) +
geom_errorbar(aes(ymin = data1$mean_v - data1$sem_v,
ymax = data1$mean_v + data1$sem_v,
width = 0.2),
position = position_dodge(width = 0.90),
group = data1$trt)
非常感谢。
解决方案似乎是在 geom_bar
和 geom_errorbar
中指定 position=position_dodge(width=0.9)
。
library(ggplot2)
plot1 <- ggplot(data1, aes(x=trt, y=mean_v, group=species, fill=species)) +
geom_bar(stat="identity", position=position_dodge(width=0.9)) +
facet_grid(. ~ life) +
geom_errorbar(aes(ymin=mean_v - sem_v, ymax=mean_v + sem_v),
width=0.2, position=position_dodge(width=0.9))
ggsave("dodged_barplot.png", plot=plot1, height=4, width=6, dpi=150)
我正在尝试将误差条放在数据框的平均值上,该数据框具有三个自变量并绘制为 facet_grid。但是,下面的图将错误栏放在了错误的方面。谁能帮帮我?
请参阅下面的示例数据和相关代码:
life <- rep(c("1d", "2d", "4d"), 2, each = 2)
trt <- rep(c("c1", "c2"), 6)
species <- rep(c("SP1", "SP2"), each = 6)
mean_v <- runif(12, 12, 45)
sem_v <- runif(12, 1, 4)
data1 <- data.frame(life, trt, species, mean_v, sem_v)
plot1 <- ggplot(data1, aes(x = trt, y = mean_v, group = species, fill = species))
plot1 + geom_bar(stat = "identity", position = "dodge") +
facet_grid(~life) +
geom_errorbar(aes(ymin = data1$mean_v - data1$sem_v,
ymax = data1$mean_v + data1$sem_v,
width = 0.2),
position = position_dodge(width = 0.90),
group = data1$trt)
非常感谢。
解决方案似乎是在 geom_bar
和 geom_errorbar
中指定 position=position_dodge(width=0.9)
。
library(ggplot2)
plot1 <- ggplot(data1, aes(x=trt, y=mean_v, group=species, fill=species)) +
geom_bar(stat="identity", position=position_dodge(width=0.9)) +
facet_grid(. ~ life) +
geom_errorbar(aes(ymin=mean_v - sem_v, ymax=mean_v + sem_v),
width=0.2, position=position_dodge(width=0.9))
ggsave("dodged_barplot.png", plot=plot1, height=4, width=6, dpi=150)