Making stacked bar plot with specified error bar values in R

一笑奈何 提交于 2019-12-02 13:35:41

问题


I'm trying to make a stacked bar plot in R with error bars for a value that I want to predefine, rather than calculate, but each bar has a different value.

For example, if my data frame was:

x<-data.frame(
  Period = c("B1","D1a"),
  Sample = c("Glucose","Glucose"),
  Mi = c(2,3),
  M0 = c(4,6)
)

I can make the bar plot I need with this code:

mx <- melt(x,  id.vars=1:2)
ggplot(mx, aes(x=Period, y=value, fill=variable), xLabels=NA) +
  geom_bar(stat="identity") +
  facet_grid(~Sample) +
  scale_fill_manual(values = c("grey69","black")) +
  theme_bw() +
  xlab("") + 
  ylab ("")

So how do I add an error bar for each one, if my confidence intervals for each one is B1, Mi = 0.5, B1, M0 = 0.2, D1a, Mi = 0.1, D1a, M0 = 0.2

How can I make error bars on each of the sections of the bar chart?

Thanks


回答1:


First, add the upper and lower bounds to your mx dataframe:

library(dplyr)
mx <- mx %>% group_by(Period) %>%
  mutate(pos = cumsum(value)) %>%
  ungroup() %>%
  mutate(ci = c(.5, .1, .2, .2),
         upper = pos + ci/2,
         lower = pos - ci/2)

Then, add a geom_errorbar to your plot:

ggplot(mx, aes(x=Period, y=value, fill=variable), xLabels=NA) +
  geom_bar(stat="identity") +
  geom_errorbar(aes(ymin = lower, ymax = upper), width = .2, col = "red") +
  facet_grid(~Sample) +
  scale_fill_manual(values = c("grey69","black")) +
  theme_bw() +
  xlab("") + 
  ylab ("")



来源:https://stackoverflow.com/questions/39383954/making-stacked-bar-plot-with-specified-error-bar-values-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!