Home > front end >  if-statement of frequency evaluation inside ggplot2
if-statement of frequency evaluation inside ggplot2

Time:10-06

I would like to count the occurences of my groups in the ggplot and plot them as text, but only if they fulfill a condition (e.g if equal 1, as group C in my example - plot the text).

..count.. or stat(count) does what I want, but I cant attach it to an if-statement.

So I would like to basically use group_by(group) %>% summarise(count=n())) for each group, evaluate wether it equal 1 for the given group, and than print something with geom_text().

I hope my explanation is somewhat clear - Thank you

df <- data.frame(
group= c("A","A","B","B","B","C",rep("D",4)),
          value= runif(sample(1:100,10,rep=TRUE)))


ggplot(df, aes(x=as.factor(group), y=value))  
    geom_boxplot()  
    geom_text(aes(label = ..count..),y=0.5, stat = "count")

IDK how I can do that, but I would like something like this

#Code will not run

ggplot(df, aes(x=as.factor(group), y=value))  
    geom_boxplot()  
    {
     if( ???? == 1){
      geom_text( ??? )
     }
    }

CodePudding user response:

You can use ifelse on ..count... If the count doesn't meet your condition, get it to return an empty string.

ggplot(df, aes(x=as.factor(group), y=value))  
  geom_boxplot()  
  geom_text(aes(label = ifelse(..count.. == 1, ..count.., "")), 
                y = 0.5, stat = "count")

enter image description here

  • Related