R-具有多个因子标签的箱线图 [英] R - boxplot with multiple factor labels

查看:324
本文介绍了R-具有多个因子标签的箱线图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在R-cran中制作一个箱形图,该图由x轴上的两个不同因素进行分类.我的问题在于为+20级的一个因子创建标签,该标签适当地跨整个图形,而使用图例标记只有2至3级的第二个因子.

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

感谢您的帮助

推荐答案

FWIW,一种ggplot2解决方案:

FWIW, a ggplot2 solution:

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

这篇关于R-具有多个因子标签的箱线图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆