Matias Andina
Matias Andina

Reputation: 4230

Automatic n plotting with ggplot and stat_summary

This is a question related to this one. I'm dealing with a boxplot of two groups and used the function n_fun proposed in that question with a small modification (I used y=10 to locate the "n = " because I find it disturbing above the median).

Here's the function:

n_fun <- function(x){
  return(data.frame(y = 10, label = paste0("n = ",length(x))))
} 

ggplot(mtcars, aes(x=factor(cyl), mpg, fill=factor(am))) +  
geom_boxplot() + stat_summary(fun.data = n_fun, geom = "text")

The thing is that the function recognizes that there are two different "n = " to be plotted but they get plotted together on a single 'y'. I've tried to enter a vector on the y position of the n_fun and it is accepted. However, I get two overplotted "n= ". I'm looking for something like "position = dodge" for the stat_summary or another way to tell the ggplot that it must plot those texts in the same way that it plot's the dodged boxplots.

Upvotes: 1

Views: 887

Answers (1)

lukeA
lukeA

Reputation: 54277

Well, as the help ?position_dodge states: Dodging things with different widths can be tricky. You may need to explicitly specify the width for dodging. In your case:

ggplot(mtcars, aes(x=factor(cyl), mpg, fill=factor(am))) +  
  stat_summary(fun.data = n_fun, geom = "text", 
               position = position_dodge(.9))

Upvotes: 2

Related Questions