How to display the mean value and error bars in a

2019-07-13 03:49发布

I've been trying to make a percent bar chart to show mortality of two species of tadpoles on three different backgrounds (for a camouflage study) My dataset is:

[[1]]
    campanha fundo sobreviventes especie intactos percentsob
1         5 light            10      Bs        9   66.66667
2         5 mixed             8      Bs        5   53.33333
3         5  dark             8      Bs        8   53.33333
4         6 light            15      Bs       13  100.00000
5         6 mixed            15      Bs       11  100.00000
6         6  dark            14      Bs       11   93.33333
7         5 light             7      Sm        5   46.66667
8         5 mixed            10      Sm        9   66.66667
9         5  dark            12      Sm       10   80.00000
10        6 light            14      Sm        6   93.33333
11        6 mixed            14      Sm        6   93.33333
12        6  dark            15      Sm        9  100.00000

and my script is (file name=odonatapint, and 15 = total number of individuals used per trial):

odonatapint$percentsob<-odonatapint$sobreviventes*100/15

ggplot(data=odonatapint,aes(x=fundo,y=percentsob,fill=especie)) + 
   geom_bar(method="mean",stat="identity",position="dodge") + 
   scale_fill_manual(values=c("#999999", "#000000")) + 
   xlab("Background type (natural)") + 
   ylab("Tadpoles surviving (%)")

However I noticed the graph to show the highest value for each category instead of the mean (I tried to post the graph but I wasn't allowed because I just registered).

What should I do to fix it? And how can I add error bars after I get to display the mean value?

标签: r ggplot2
2条回答
\"骚年 ilove
2楼-- · 2019-07-13 04:15

I don't know that much about geom_bar(), so this takes a slightly different approach, but it works with example datasets. It computes the error bar values by bootstrapping, which may be computationally intensive with larger datasets.

ggplot(data=odonatapint,aes(x=fundo,y=percentsob,fill=especie)) +
    stat_summary(geom='bar', fun.y='mean', position='dodge') +
    stat_summary(geom='errorbar', fun.data='mean_cl_boot', position='dodge')
查看更多
兄弟一词,经得起流年.
3楼-- · 2019-07-13 04:23

This is what I did, first calculate the mean and standard deviation (for error bars)

library(dplyr)
odonatapint <- odonatapint %>% group_by(fundo,especie) %>% mutate(mean = mean(percentsob), sd = sd(percentsob))

then plot using ggplot (first plot bars using geom_bar, then use geom_errorbar to add error bars

ggplot(data=odonatapint,aes(x=fundo,y=mean,fill=especie)) + 
  geom_bar(method="mean",stat="identity",position=position_dodge()) + 
  geom_errorbar(aes(ymax = mean + sd, ymin = mean - sd), position = position_dodge()) + 
  scale_fill_manual(values=c("#999999", "#000000")) + 
  xlab("Background type (natural)") + 
  ylab("Tadpoles surviving (%)")

The figure generated is shown below

enter image description here

查看更多
登录 后发表回答