Plotting several groups of box plots side-by-side in R

旧街凉风 提交于 2019-12-03 12:29:48

问题


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.



来源:https://stackoverflow.com/questions/7738510/plotting-several-groups-of-box-plots-side-by-side-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!