2017-04-14 4 views
1

In der folgenden Grafik möchte ich die Anzahl der Beobachtungen (40 in diesem Fall) auf jedem Boxplot überlagern. Mein Code unten funktioniert nicht, wenn es eine fill Ästhetik gibt. Der Text muss horizontal angepasst werden (1 links, 1 Mitte, 1 in diesem Fall), so dass sie die entsprechenden Boxplots richtig überlagern.ggplot2 boxplot stat_summary Textplatzierung nach Gruppe

dt <- data.table(
    x = factor(rep(1:2, each=120)) 
    , f = rep(letters[1:3], 40) 
    , y = c(rnorm(120, 1:3), rnorm(120, 1:3*2)) 
) 
table(dt$x, dt$f) 

+--------------+ 
|  a b c | 
+--------------+ 
| 1 40 40 40 | 
| 2 40 40 40 | 
+--------------+ 

frequencyAnnotation <- function(x) { 
    c(y = (quantile(x, .75, names = F) + median(x))/2, label=length(x)) 
} 
ggplot(dt, aes(x=x, y=y, fill=f)) + 
    geom_boxplot() + 
    stat_summary(fun.data = frequencyAnnotation, geom='text') 

enter image description here

Antwort

1

Als Ihr Boxplots ausgewichen werden, wenn Sie verwenden Argument = füllen, haben Sie position_dodge() zum stat_summary() Gespräch hinzuzufügen.

ggplot(dt, aes(x=x, y=y, fill=f)) + 
     geom_boxplot() + 
     stat_summary(fun.data = frequencyAnnotation, geom='text', 
        position = position_dodge(width = 0.75)) 
+0

Danke! Ich hatte 'position_dodge()' noch nicht gefunden. Es ist kein großes Problem, aber gibt es eine Möglichkeit, die 'width = 0.75' nicht hart zu codieren? Können Sie das programmatisch machen? – Synergist

+1

Für die Boxplots und den Text ändert sich diese 0,75 nicht, wenn Sie die Anzahl der x- und f-Ebenen ändern. –

+0

Das ist magisch. Gibt es eine einfache Erklärung warum? Wenn nicht, danke trotzdem - es funktioniert super! – Synergist

Verwandte Themen