簡體   English   中英

R - 具有多個因子標簽的boxplot

[英]R - boxplot with multiple factor labels

我正在努力嘗試在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"))

謝謝你的幫助

FWIW,一個ggplot2解決方案:

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

在此輸入圖像描述

如果你想在每組3個盒子的中間放一個標簽,試試這樣的:

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

在此輸入圖像描述

概括來說,這將是:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM