R - boxplot with multiple factor labels

*爱你&永不变心* 提交于 2019-12-12 07:13:45

问题


I'm working on trying to make a boxplot in R-cran that is categorized by two different factors on the x-axis. My problem lies in creating labels for one factor with +20 levels that spans the entire graph appropriately while using a legend to label the second factor which has only 2 to 3 levels.

Here is a test script that roughly mimics my actual dataset:

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

Thanks for any help


回答1:


FWIW, a ggplot2 solution:

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




回答2:


If you want a label at the middle of each group of 3 boxes, try something like this:

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

To generalise, this would be:

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


来源:https://stackoverflow.com/questions/10441214/r-boxplot-with-multiple-factor-labels

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