我有一个如下所示的数据框。在实际数据集中,有14个dv和9个条件。
dv condition mean sd
dv1 1 4 1
dv1 2 5 1
dv1 3 3 2
dv2 1 3 1
dv2 2 6 2
dv2 3 4 1
我知道我可以按照以下方式分别绘制这些图形。我可以为每个dv创建一个单独的数据框,然后对其进行图形处理。
dv1 <- df[1:3,]
dv1_graph <- ggplot(dv1, aes(x=condition, y = mean, fill = condition)) +
geom_bar(stat = "identity", color = "black", position = position_dodge()) +
labs(title = "DV1") +
geom_errorbar(aes(ymin = mean-sd, ymax = mean+sd), width = 0.2, position = position_dodge(.9))
是否可以同时为每个dv创建带有误差线的单独条形图?
答案 0 :(得分:2)
我想你想要这个:
ggplot(df, aes(condition, mean)) +
geom_col(color = "black", position = position_dodge()) +
geom_errorbar(aes(ymin = mean - sd, ymax = mean + sd), width = 0.2,
position = position_dodge(.9)) +
facet_wrap(~dv)
更新:针对一堆个别地块
library(dplyr)
library(purrr)
plotter <- function(df, dv) {
plot(ggplot(df, aes(condition, mean)) +
geom_col(color = "black", position = position_dodge()) +
geom_errorbar(aes(ymin = mean - sd, ymax = mean + sd), width = 0.2,
position = position_dodge(.9)) +
ggtitle(dv))
}
nested_df <-
df %>%
group_by(dv) %>%
nest()
walk2(nested_df$data, nested_df$dv, plotter)