分享一個(gè)ggplot2畫雙誤差線條形圖的實(shí)際例子保屯,喜歡的小伙伴可以關(guān)注我的公眾號R語言數(shù)據(jù)分析指南刽辙,持續(xù)分享更多優(yōu)質(zhì)資源
可以將上述圖看成以下2副圖拼接而成
首先吹由,我們先繪制藍(lán)色的條形圖和它們的誤差線棵帽,然后繪制了綠色和紅色的條形圖和它們的誤差線
library(tidyverse)
df <- tribble(
~Condition, ~Referent, ~Accuracy,
"Primacy", "Single", 0.63,
"Primacy", "Primacy", 0.59,
"Recency", "Single", 0.63,
"Recency", "Recency", 0.5,
"Both", "Single", 0.63,
"Both", "Primacy", 0.5,
"Both", "Recency", 0.31) %>%
mutate(error_low = runif(7, .04, .06),
error_high = runif(7, .04, .06),
Condition_name = factor(Condition,
levels = c("Primacy", "Recency", "Both")),
Condition = as.numeric(Condition_name),
Referent = factor(Referent,
levels = c("Single", "Recency", "Primacy")),
left = Referent == "Single",
color = case_when(Referent == "Single" ~ "#29476B",
Referent == "Primacy" ~ "#AD403D",Referent == "Recency" ~ "#9BBB58"))
ggplot(df,aes(x = Condition, y = Accuracy, fill = color)) +
geom_col(
data = filter(df, left),
width = .3,
color = "white",
position = position_nudge(x = -.3),
)+
geom_errorbar(
aes(ymin = Accuracy - error_low, ymax = Accuracy + error_high),
data = filter(df, left),
width = .1,
position = position_nudge(x = -.3)
)+
geom_col(
data = filter(df, !left),
color = "white",
width = .3,)+
geom_errorbar(
aes(y = y, ymin = y - error_low, ymax = y + error_high),
data = filter(df, !left) %>%
group_by(Condition) %>%
mutate(y = accumulate(Accuracy, sum)),
width = .1
) +
geom_hline(
aes(yintercept = .25),
linetype = 2,
size = 1,
) +
geom_text(
aes(x = 3.4, y = .29),
label = "Chance",
family = "Adelle",
color = "grey20",
inherit.aes = FALSE) +
scale_fill_identity(
labels = c("Single", "Primacy", "Recency"),
guide = guide_legend(
title = NULL,
direction = "horizontal",
override.aes = list(fill = c("#29476B", "#AD403D", "#9BBB58")))) +
scale_x_continuous(
breaks = 1:3 - .15,
labels = levels(df$Condition_name),
expand = expansion(c(.1, .05))) +
scale_y_continuous(
breaks = scales::pretty_breaks(6),
labels = scales::percent_format(1),
limits = 0:1,
expand = expansion(0)) +
labs(title = "Accuracy by Condition and Referent",
y = NULL) +
theme_classic(base_size = 16) +
theme(plot.title.position = "plot",
plot.title = element_text(margin = margin(0, 0, 1, 0, "cm")),
legend.position = c(.35, .9),
axis.title.x = element_text(margin = margin(t = .4, unit = "cm")),
plot.margin = margin(1, 1, .7, 1, "cm"))