如何在散点图上方制作单独的均值,误差线,以及如何制作水平均线?

时间:2019-04-25 13:01:48

标签: r ggplot2 visualization errorbar

我想用水平线(带有误差线)表示position_dodged scatter plot

我在position_dodging上遇到麻烦,stat_summary()的平均值和误差线使平均值显示为水平线。

我想证明男女均数不同。我知道每个小组都有不同的手段,但我不知道如何形象化。

download.file(url="https://ndownloader.figshare.com/files/2292169",
              destfile = "~/portal_data_joined.csv")

surveys <- read.csv

surveys_cln <- surveys %>% filter(sex=="F"|sex=="M")

ggplot(data = surveys_cln, mapping = aes(x=species_id, y=weight, color=sex))+
  geom_jitter(alpha=.6, position = position_dodge(.5))+
  stat_summary(fun.data = mean_sdl, fun.args = list(mult=1), 
               geom="errorbar", color="red", width=.5, position=position_dodge2(width=.9))
  stat_summary(fun.y=mean, geom="errorbar", color="red", width = .75, linetype = "dashed", position=position_dodge(9))

每个条件我只有一个mean+errorbar,而两组条件都没有。如果我可以分别显示两个性别的mean+errorbar,那就太好了。

这是图片

link to the resulting image

嗨! 谢谢您的帮助。这是更新的代码:

  ggplot(data = surveys_cln, mapping = aes(x=species_id, y=weight, fill=as.factor(sex), shape=as.factor(sex)))+

  geom_jitter(alpha=.6, position = position_dodge(.5))+
  stat_summary(aes(group = sex), fun.data = mean_sdl, fun.args = list(mult=1), 
  geom="errorbar", width=.5, position=position_dodge2(width=.9))+
  stat_summary(fun.y=mean, geom="errorbar", width = .75, linetype = "dotted", position=position_dodge(9))+

  scale_fill_manual(values=c("#006D2C","#DEEBF7"))+
  #scale_fill_brewer(palette="Paired")+

  theme_bw()+
  #theme(text=element_text(size=30))+
  theme(#legend.position = "none",
    plot.title = element_blank(),
    panel.grid.major.x = element_blank(),
    axis.title.x = element_text(),
    axis.text.x = element_text(),
    axis.ticks = element_blank(),
    axis.text.y = element_text(size=rel(.7)))

您能帮我解决颜色吗?我想要F =#000000和M =#73000a。

还可以在误差条之间将其均值显示为水平条吗?

这是第二次尝试

link to the resulting image

再次感谢!

2 个答案:

答案 0 :(得分:1)

您需要在aes(group = sex)中添加geom_*()

ggplot(data = surveys_cln,
       mapping = aes(x = species_id, y = weight, color = sex)) +
  geom_jitter(alpha = .6, position = position_dodge(.5)) +
  stat_summary(fun.data = mean_sdl, fun.args = list(mult = 1), 
               aes(group = sex), 
               geom = "errorbar", color = "red", width = .5, 
               position = position_dodge2(width = .9))

enter image description here

答案 1 :(得分:1)

虽然@abichat的答案是完全正确的,但是您也可以删除color="red"参数,这将导致ggplot不对数据进行分组。

这样,您的绘图将显示具有良好颜色的误差线(也许增加其厚度以提高可读性)。