在ggplot中绘制置信区间

时间:2013-10-25 21:48:26

标签: r plot ggplot2

我想使用ggplot执行以下绘图:

GgPlot of Confidence Intervals by Group

这是我的df结构的一个例子(有点,不按比例绘制数据):

example.df = data.frame(mean = c(0.3,0.8,0.4,0.65,0.28,0.91,0.35,0.61,0.32,0.94,0.1,0.9,0.13,0.85,0.7,1.3), 
                            std.dev = c(0.01,0.03,0.023,0.031,0.01,0.012,0.015,0.021,0.21,0.13,0.023,0.051,0.07,0.012,0.025,0.058),
                            class = c("1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"),
                            group = c("group1","group2","group1","group2","group1","group2","group1","group2","group1","group2","group1","group2","group1","group2","group1","group2"))

该数据框由16个重复组成,每个重复具有给定的平均值和给定的标准偏差。

对于每个复制,我想绘制置信区间,其中我的图例中的大点是平均估计值,条形的长度是标准偏差的两倍。

此外,我想在同一行中绘制两个不同的重复,但颜色不同,按类着色,红色为1级,蓝色为2级。

最后,我想把整个情节分成两个不同组的两个面板(在同一行)。

我试过调查这个网站,http://www.cookbook-r.com/Graphs/Plotting_means_and_error_bars_(ggplot2)/但是无法弄清楚如何为这个结构的任何数据框自动化这个,X组的数量(在这种情况下为2),每组重复K次(在这种情况下,8级,4级,4级,4级)。

使用ggplot或标准r pkg库有没有好方法呢?

1 个答案:

答案 0 :(得分:4)

我认为您提供的示例数据框架不是以适当的方式构建的,因为group1中的所有值都有class 1,而group2中的所有值都是类{ {1}}。所以我创建了新的数据框,还添加了名为2的新列,其中显示了每个replicate中的重复次数(四次重复(包含两个class值))。

group

现在,您可以使用example.df = data.frame(mean = c(0.3,0.8,0.4,0.65,0.28,0.91,0.35,0.61,0.32,0.94,0.1, 0.9,0.13,0.85,0.7,1.3), std.dev = c(0.01,0.03,0.023,0.031,0.01,0.012,0.015,0.021,0.21, 0.13,0.023,0.051,0.07,0.012,0.025,0.058), class = c("1","2","1","2","1","2","1","2","1","2","1", "2","1","2","1","2"), group = rep(c("group1","group2"),each=8), replicate=rep(rep(1:4,each=2),time=2)) 获取置信区间点数和geom_pointrange()来为每个组制作情节。

facet_wrap()

enter image description here