I wonder to know whether is possible to plot automatically a figure like this one using R:

enter image description here

I must say that the previous image was done manually by using Inkscape. However, I'd like to know whether is possible to construct such kind of image automatically using R. It would save an enormous time.

I have the original data:

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

The first column is the category (in this case there are only two categories, 1 and 2). The upper row in each category is the upper 95%CL and the lower row in each category is the lower 95%CL. The other rows are the mean.

In this case, I have 6 different samples, which are shown in 6 columns after the category column.

1

There are 1 answers

0
josliber On BEST ANSWER

You could do this in ggplot by first reshaping your data so each row is a confidence interval, getting the appropriate x-axis spacing for your grouped data:

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

Then you could plot, using geom_rect and geom_segment to get the shapes:

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

enter image description here