Home > Blockchain >  stat_summary add string as text
stat_summary add string as text

Time:04-05

I am trying to create a boxplot which includes the number of samples per group. The code I am using so far looks something like this and works fine:

set.seed(123)
plot_df <- data.frame(x_val=factor(sample(1:2, 90, replace = T)),
           y_val=runif(90),
           split=factor(sample(1:3, 90, replace = T)))


give.n <- function(x,ypos){
  return(c(y = ypos, label = length(x))) 
}

ggplot(plot_df, aes(x=x_val, y=y_val, fill=split)) 
  geom_boxplot(width=0.3) 
  geom_jitter(width=0.01,size=0.7) 
  facet_wrap(~split) 
  stat_summary(fun.data = give.n, geom = "text", fun.args = list(ypos=-0.1),size=6) 

I only want to modify one thing. Instead of simply adding the number of samples, I also want to add a small text, something like n=. However, if I modify give.n like this

give.n <- function(x,ypos){
  return(c(y = ypos, label = paste0("n=",length(x))))
}

I get the following error: Error: Discrete value supplied to continuous scale.

Can tell me, how I can add text to stat_summary?

Any help is much appreciated!

CodePudding user response:

You should have change it to a dataframe instead of vector in your give.n function. You can use the following code:

set.seed(123)
plot_df <- data.frame(x_val=factor(sample(1:2, 90, replace = T)),
                      y_val=runif(90),
                      split=factor(sample(1:3, 90, replace = T)))


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

ggplot(plot_df, aes(x=x_val, y=y_val, fill=split)) 
  geom_boxplot(width=0.3) 
  geom_jitter(width=0.01,size=0.7) 
  facet_wrap(~split) 
  stat_summary(fun.data = give.n, geom = "text", fun.args = list(ypos=-0.1),size=6)

Output:

enter image description here

  • Related