Plotting several groups of box plots side-by-side

2019-03-15 14:39发布

问题:

I am trying to plot two box-plots in the same plot, each within the same category. I can generate the boxplots individually, but am stumped when I try to get them onto the same graph.

Here is what I have so far:

a<-matrix(nrow=100,ncol=3,data=runif(300,max=2))
b<-matrix(nrow=100,ncol=3,data=runif(300,max=1))
colnames(a)<-c("case 1","case 2","case 3")
colnames(b)<-c("case 1","case 2","case 3")
boxplot(cbind(a,b))

This plot results in 6 boxplots, first 3 for a, then 3 for b.

Is there a trick/simple option that I am missing that will give me first value for a and b, then second and finally the third set of values, all plotted in such a way there are is only three ticks on the x-axis, one for each of the sets?

Any pointers greatly appreciated,

Iain

回答1:

boxplot(a, at = 0:2*3 + 1, xlim = c(0, 9), ylim = range(a, b), xaxt = "n")
boxplot(b, at = 0:2*3 + 2, xaxt = "n", add = TRUE)
axis(1, at = 0:2*3 + 1.5, labels = colnames(a), tick = TRUE)

Note the ylim = range(a, b) parameter. The plot scale is determined by the first command, but if b contained values out of range of values in a (not in this case, but try to swap a and b), they would lie out of the plot. That's why in general you should specify the ylim here.

You can also set tick = FALSE in the axis() command, I think it is nicer. If you don't like the space between the groups, use 0:2*2 instead of 0:2*3, and change the xlim appropriatelly.



标签: r plot boxplot