假设我有以下数据:
behaviorm <- structure(list(sentential_connective = c("IF", "IF",
"Because", "IF", "Because", "IF", "Because", "IF", "IF", "Because", "IF",
"Because", "IF", "Because", "IF", "IF", "Because", "IF", "Because",
"IF", "Because", "IF", "IF", "Because", "IF", "Because", "IF",
"Because"), mentioned_object = c("Same", "Different", "Same",
"Same", "Same", "Different", "Different", "Same", "Different",
"Same", "Same", "Same", "Different", "Different", "Same", "Different",
"Same", "Same", "Same", "Different", "Different", "Same", "Different",
"Same", "Same", "Same", "Different", "Different"),
agent_mood = c("Sad", "Sad", "Happy", "Happy", "Sad", "Happy",
"Happy", "Sad", "Sad", "Happy", "Happy", "Sad", "Happy", "Happy",
"Sad", "Sad", "Happy",
"Happy", "Sad", "Happy", "Happy", "Sad", "Sad", "Happy", "Happy",
"Sad", "Happy", "Happy"), Chosen_Box = c("SD", "SD", "SD", "SD",
"SD", "SD", "SD", "CS", "CS", "CS", "CS", "CS", "CS", "CS", "SS",
"SS", "SS", "SS", "SS", "SS", "SS", "DD", "DD", "DD", "DD", "DD",
"DD", "DD"), chose_action = c(500L, 80L, 7L, 11L, 755L, 236L,
7L, 74L, 631L, 21L, 484L, 29L, 38L, 1L, 8L, 81L, 786L, 321L,
7L, 6L, 14L, 247L, 25L, 13L, 9L, 36L, 538L, 801L)),
row.names = c(NA, -28L), class = "data.frame")
以及以下数据:
chance_level <- structure(list(sentential_connective = c("Because", "Because",
"Because", "IF", "IF", "IF", "IF"), mentioned_object = c("Different",
"Same", "Same", "Different", "Different", "Same", "Same"), agent_mood = c("Happy",
"Happy", "Sad", "Happy", "Sad", "Happy", "Sad"), chance = c(205.75,
206.75, 206.75, 204.5, 204.25, 206.25, 207.25), xmin = c(0.55,
0.55, 0.55, 1.55, 1.55, 1.55, 1.55), xmax = c(1.45, 1.45, 1.45,
2.45, 2.45, 2.45, 2.45)), row.names = c(NA, -7L), class = "data.frame")
我的图如下:
ggplot() +
geom_bar(
mapping = aes(x = sentential_connective, y = chose_action, fill = Chosen_Box),
stat = "identity",
position = position_dodge(width = 0.9, preserve = "single"),
data = behaviorm
) +
facet_grid(agent_mood ~ mentioned_object) +
geom_segment(
aes(x = xmin, xend = xmax, y = chance, yend = chance),
data = chance_level, lwd = 0.2, lty = 2
) +
theme(
panel.grid = element_blank(),
panel.border = element_blank(),
legend.position = "bottom",
axis.title = element_text(face = "bold"),
axis.line = element_line(size = 0.3, colour = "black"),
strip.background = element_blank(),
strip.text = element_text(face = "bold"),
strip.text.y = element_text(angle = 0)
)
如脚本中所示,我可以使用segments
文件中提供的_x_s和_xend_s手动添加chance_level
的宽度。
我的问题是:我们可以自动设置这些线段相对于条形图宽度的水平位置和宽度吗?
谢谢
答案 0 :(得分:0)
使用stat_summary()
尝试一下。 ..y..
的使用表示“无论y的值是什么”。
ggplot(behaviorm, aes(x = sentential_connective, y = chose_action)) +
geom_col(
aes(fill = Chosen_Box),
position = position_dodge(width = 0.9, preserve = "single")
) +
facet_grid(agent_mood ~ mentioned_object) +
stat_summary(
fun.y = mean, aes(ymax = ..y.., ymin = ..y..),
geom = "errorbar", linetype = "dashed"
)
我在这里找到了这个解决方案: R ggplot2: Add means as horizontal line in a boxplot