2017-08-23 4 views
0

Ich habe eine Frage, wie man mehrere Box-Plots pro Gruppe stratifizieren. Dies ist, was ich für einen Beispielcode habenPutting mehrere Box-Plots pro Gruppe stratifiziert

library(ggplot2) 

mtcars$vs <- as.character(as.numeric(mtcars$vs)) 

y6 <- ggplot(mtcars, aes(x=vs,y=hp)) + 
    geom_boxplot(aes(group = vs),outlier.shape=NA, size=1, width = 0.6, fatten = 1) + 
    geom_jitter(aes(x=vs, y=hp, pch = factor(cyl)), position=position_jitter(width=.1, height=0), size = 2) + 
    scale_shape_manual(name ="X", values = c(1,2,3)) + 
    coord_cartesian(ylim=c(0, 350)) 

enter image description here

Dies ist, was ich aus der Kurve zu erhalten. Ich hoffe, die Graphen pro X-Achse durch die Legende zu stratifizieren, was insgesamt 6 Box-Plots ergibt (3 pro X-Achse; 3 für "1" und 3 für "2"). Gibt es eine Möglichkeit, dies zu tun? Ich habe ein Bild davon unten angehängt:

enter image description here

Vielen Dank für Ihre Meinung! Hier

Antwort

1

ist der Code für Sie:

library(ggplot2) 

ggplot(mtcars, aes(x=vs,y=hp,fill = factor(cyl))) + 
    geom_boxplot(aes(fill = factor(cyl)),outlier.shape=NA, size=1, width = 0.6, fatten = 1) + 
    coord_cartesian(ylim=c(0, 350)) 

enter image description here

I fill= Argument in ggplot() verwendet haben/Gruppe durch Spalte cyl die Daten zu teilen.

Wenn Sie näher betrachten mtcars Daten und Ihr Grundstück, Sie haben tatsächlich nicht 3 eindeutige Werte von cyl für vs = 1, nur zwei (8) .. Daher erhalten Sie insgesamt 5 Boxen

0

Ist das, was du fragst?

ggplot(mtcars, aes(vs, hp)) + 
    geom_boxplot() + 
    facet_wrap(~cyl) + 
    theme_bw() 

enter image description here

Es sind keine Werte für vs wenn cyl==8 und nur einen Wert für vs wenn cyl==4.

table(mtcars$cyl, mtcars$vs) 
# 0 1 
# 4 1 10 
# 6 3 4 
# 8 14 0 

Wenn Sie ein Fan von Einfärben der Parzellen sind, können Sie es tun mit dem fill Parameter.

ggplot(mtcars, aes(vs, hp, fill=as.factor(cyl))) + 
    geom_boxplot() + 
    facet_wrap(~cyl) + 
    theme_bw() 

enter image description here

Verwandte Themen