gpt4 book ai didi

r - 在 ggplot() 中将误差线放置在列中心时出现问题

转载 作者:行者123 更新时间:2023-12-01 22:19:54 25 4
gpt4 key购买 nike

我的条形图有问题 - 误差线仅出现在分组变量的列的角上,而不是以集中的方式出现在它们上。我使用的代码是这样的:

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")

我尝试过的替代代码也无法工作,包括将“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) +

(其余代码保持不变)。这将误差线移向列的中心,同时也将列移向彼此,最终使它们重叠(参见附图)。 see attached figure

我非常感谢对此的帮助。

谢谢!

最佳答案

问得好。一些评论:

  1. 一般来说,最好在原始 ggplot() 调用中设置所有美学,并且仅在单独的 geom_xyz 中需要时才使用不同的美学覆盖它们() 调用。在您的代码中,您设置了两次填充美学,一次在 ggplot 中,一次在 geom_bar 中。您还可以在 geom_errorbar() 中设置组美感。我不认为这些事情是最终的问题,但它们确实使调试代码变得更加困难。

  2. 主要问题是 geom_bar 中的 width 参数必须与 geom_errorbar 中的 position_dodge() 参数相匹配。所以如果你有

    # ...
    geom_bar(stat = "identity", position = "dodge", width = 0.5)
    # ...

    然后你必须确保你的geom_errorbar()看起来像

    # ...
    geom_errorbar(width = .08, position = position_dodge(0.5))
    # ...

把它们放在一起:

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')

Final graph

关于r - 在 ggplot() 中将误差线放置在列中心时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35424162/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com