R - 具有多个因子标签的boxplot

时间:2012-05-04 00:33:50

标签: r label boxplot

我正在努力尝试在R-cran中制作一个由x轴上的两个不同因素分类的箱线图。我的问题在于为一个因子创建标签,其中+20级别适当地跨越整个图形,同时使用图例标记第二个因子,只有2到3个级别。

这是一个大致模仿我的实际数据集的测试脚本:

d<-data.frame(x=rnorm(1500),f1=rep(seq(1:20),75),f2=rep(letters[1:3],500))
# first factor has 20+ levels
d$f1<-factor(d$f1)
# second factor a,b,c
d$f2<-factor(d$f2)

boxplot(x~f2*f1,data=d,col=c("red","blue","green"),frame.plot=TRUE,axes=FALSE)

# y axis is numeric and works fine
yts=pretty(d$x,n=5)
axis(2,yts)

# I know this doesn't work; what I'd like is to spread the factors out 
# so the each group of three(a,b,c) is labeled correctly
axis(1,at=seq(1:20))

# Use the legend to handle the f2 factor labels
legend(1, max(d$x), c("a", "b","c"),fill = c("red", "blue","green"))

感谢您的帮助

2 个答案:

答案 0 :(得分:13)

FWIW,ggplot2解决方案:

library(ggplot2)
ggplot(data = d, aes(x = f1, y = x)) + 
  geom_boxplot(aes(fill = f2), width = 0.8) + theme_bw()

enter image description here

答案 1 :(得分:5)

如果您想在每组3个盒子的中间放置一个标签,请尝试以下方法:

axis(1,at=seq(2,60,3),labels=1:20,cex.axis=0.7)

enter image description here

概括来说,这将是:

groups <- 20
numbox <- 3
total <- groups * numbox
xpoints <- seq(median(1:numbox),total,numbox)