在R中使用指定的误差线值制作堆积的线图 [英] Making stacked bar plot with specified error bar values in R

查看:235
本文介绍了在R中使用指定的误差线值制作堆积的线图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在R中制作一个带有误差线的堆叠条形图,以表示我想要预定义而不是计算的值,但是每个条形都有一个不同的值.

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

因此,如果我对每一个的置信区间为B1,Mi = 0.5,B1,M0 = 0.2,D1a,Mi = 0.1,D1a,M0 = 0.2,那么如何为每个误差栏添加误差线

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?

谢谢

推荐答案

首先,将上下限添加到mx数据框中:

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)

然后,在您的绘图中添加geom_errorbar:

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

这篇关于在R中使用指定的误差线值制作堆积的线图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆