2012-05-04 19 views
7

Sto lavorando per provare a creare un boxplot in R-cran che è classificato da due fattori diversi sull'asse x. Il mio problema sta nel creare etichette per un fattore con livelli di +20 che copre l'intero grafico in modo appropriato mentre si utilizza una legenda per etichettare il secondo fattore che ha solo 2 o 3 livelli.R - boxplot con più etichette di fattore

Ecco uno script di test che circa imita il mio attuale set di dati:

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

Grazie per qualsiasi aiuto

risposta

13

FWIW, una soluzione 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

+0

Non mi sono mai reso conto che potresti avere tema trame 'ggplot'! Sono sempre stato spento usando loro a causa del brutto sfondo grigio. Grazie per avermelo mostrato – thelatemail

+0

@thelatemail, il tema consente a quasi tutti gli elementi nel grafico di essere modificati/modificati. –

+0

@thelatemail - consultare [qui] (https://github.com/hadley/ggplot2/wiki/Themes) per una panoramica dei temi. – Chase

5

Se si vuole un'etichetta a metà di ogni gruppo di 3 scatole, provare qualcosa di simile :

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

enter image description here

Per generalizzare, questo sarebbe:

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

Grazie a tutti e due, esattamente quello che stavo cercando. – Kerry

+0

@Kerry - Nessun problema! In tal caso, non dimenticare di darci entrambi un upvote (freccia su) e scegliere una risposta (il simbolo del tick sotto le frecce) – thelatemail

Problemi correlati