Bah*_*har 4 r standard-error bar-chart ggplot2
我的条形图有问题 - 错误条只出现在分组变量列的一角,而不是集中显示在它们上面.我使用的代码是这样的:
a <- data.frame (Cond = c("In", "In", "Out", "Out"),
Temp = c("Hot", "Cool", "Hot", "Cool"),
Score = c(.03, -.15, 0.84, 0.25),
SE = c(.02, .08, .14, .12))
a.bar <- ggplot (data = a, aes(x = Cond, y = Score, fill = Temp)) +
theme_bw() + theme(panel.grid = element_blank ()) +
coord_cartesian (ylim = c(-0.5, 1)) +
geom_bar (aes(fill = Temp), stat = "identity", position = "dodge", width = .5) +
geom_errorbar (aes(ymin = Score - SE, ymax = Score + SE, group = Cond), position = position_dodge(.9), width = .08) +
labs(y = "Scores" , x = "Cond") +
scale_y_continuous (breaks = pretty_breaks(n=8)) +
theme(legend.title = element_blank()) +
theme(legend.position = "right")
Run Code Online (Sandbox Code Playgroud)
我尝试过的替代代码,我也无法工作,包括将"show.legend = FALSE"添加到geom_bar(); 添加"facet_wrap(~Cond)"plot.a; 并在ggplot(aes())中引入"fill = Temp".最接近的解决方案是我将position_dodge()参数更改为:
geom_bar (aes(fill = Temp), stat = "identity", position = position_dodge(width = .5)) +
geom_errorbar (aes(ymin = Score - SE, ymax = Score + SE, group = Cond), position = position_dodge(.5), width = .08) +
Run Code Online (Sandbox Code Playgroud)
(其余代码保持不变).这会将误差条移向列的中心,同时也会使列彼此相向移动,最终使它们重叠(参见附图).

我非常感谢这方面的帮助.
谢谢!
好问题.几条评论:
一般来说,在原始ggplot()调用中设置所有美学并且仅在个别geom_xyz()调用中需要时以不同的美学覆盖它们是一种很好的做法.在您的代码中,您将填充美学设置两次,一次进入ggplot,一次进入geom_bar.您还可以设置群体审美geom_errorbar().我不认为这些问题是最终的问题,但它们确实使调试代码变得更加困难.
主要问题是width参数geom_bar必须匹配position_dodge()内部的参数geom_errorbar.所以,如果你有
# ...
geom_bar(stat = "identity", position = "dodge", width = 0.5)
# ...
Run Code Online (Sandbox Code Playgroud)
然后你必须确保你的geom_errorbar()样子
# ...
geom_errorbar(width = .08, position = position_dodge(0.5))
# ...
Run Code Online (Sandbox Code Playgroud)把它们放在一起:
require(ggplot2)
require(scales)
# define data
a <- data.frame (Cond = c("In", "In", "Out", "Out"),
Temp = c("Hot", "Cool", "Hot", "Cool"),
Score = c(.03, -.15, 0.84, 0.25),
SE = c(.02, .08, .14, .12))
# return plot with everything except error bars
a.bar <- ggplot (data = a, aes(x = Cond,
y = Score,
fill = Temp,
ymin = Score - SE,
ymax = Score + SE)) +
theme_bw() +
theme(panel.grid = element_blank ()) +
coord_cartesian(ylim = c(-0.5, 1)) +
# manually setting the width means we will have to tell geom_errorbar() about the new width
geom_bar(stat = "identity", position = "dodge", width = 0.5) +
labs(y = "Scores", x = "Cond") +
scale_y_continuous(breaks = pretty_breaks(n = 8)) +
theme(legend.title = element_blank()) +
theme(legend.position = "right")
# show plot w/ errorbars, note that argument to position_dodge is same as width supplied above
a.bar + geom_errorbar(width = .08, position = position_dodge(0.5))
# save results
ggsave('SO_35424162.png')
Run Code Online (Sandbox Code Playgroud)