1

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.

2
  • stat_summary(fun.data = n_fun, geom = "text", position = position_dodge(.9))? Commented Oct 5, 2015 at 22:53
  • @lukeA Great! that should be an answer. It also might help to explain why position = dodge does not work but position= position_dodge() does the job Commented Oct 5, 2015 at 23:04

1 Answer 1

2

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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.