如何在 R 中用置信区间和均值的数值数据绘制图形,比较每个类别的不同样本?

How can I plot a figure with numerical data of confidence intervals and means, comparing different samples per categories, in R?

我想知道是否可以使用 R 自动绘制像这样的图形:

我必须说,之前的图像是使用 Inkscape 手动完成的。但是,我想知道是否可以使用 R 自动构建这种图像。这将节省大量时间。

我有原始数据:

1   10.73   9.31    10.75   7.72    5.98    7.97
1   9.27    8.61    9.28    7.00    6.25    8.50
1   8.49    7.80    8.50    6.26    6.54    9.11
2   11.45   10.00   11.46   8.47    6.58    8.86
2   10.76   10.00   10.03   7.75    6.88    9.45
2   10.00   9.34    9.25    7.00    7.19    10.12

第一列是类别(在本例中只有两个类别,1 和 2)。每个类别中的上一行是上 95%CL,每个类别中下一行是下 95%CL。其他行是平均值。

在这种情况下,我有 6 个不同的样本,它们显示在类别列之后的 6 列中。

您可以在 ggplot 中执行此操作,方法是首先重塑数据,使每一行都是一个置信区间,为您的分组数据获取适当的 x 轴间距:

plot.dat <- data.frame(x=c(seq(.8, 1.2, length.out=6), seq(1.8, 2.2, length.out=6)),
                       lb=unlist(c(dat[3,-1], dat[6,-1])),
                       mid=unlist(c(dat[2,-1], dat[5,-1])),
                       ub=unlist(c(dat[1,-1], dat[4,-1])))
plot.dat
#       x    lb   mid    ub
# 1  0.80  8.49  9.27 10.73
# 2  0.88  7.80  8.61  9.31
# 3  0.96  8.50  9.28 10.75
# 4  1.04  6.26  7.00  7.72
# 5  1.12  6.54  6.25  5.98
# 6  1.20  9.11  8.50  7.97
# 7  1.80 10.00 10.76 11.45
# 8  1.88  9.34 10.00 10.00
# 9  1.96  9.25 10.03 11.46
# 10 2.04  7.00  7.75  8.47
# 11 2.12  7.19  6.88  6.58
# 12 2.20 10.12  9.45  8.86

然后你可以绘图,使用 geom_rectgeom_segment 得到形状:

library(ggplot2)
ggplot(plot.dat, aes(xmin=x-.03, xmax=x+.03, ymin=lb, ymax=ub)) +
  geom_rect(fill=NA, color="black") +
  geom_segment(aes(x=x-.03, xend=x+.03, y=mid, yend=mid)) +
  theme_bw() +
  scale_x_continuous(breaks=c(1, 2)) +
  ylim(0, max(plot.dat$ub)) +
  xlab("Group") +
  ylab("Value")