Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2::geom_text(): how to display all factor levels, but suppress specific values like '0':

Here is code to give context to my question:

set.seed(1); tibble(x=factor(sample(LETTERS[1:7],7,replace = T),levels = LETTERS[1:7])) %>% group_by_all() %>% count(x,.drop = F) %>% 
ggplot(mapping = aes(x=x,y=n))+geom_bar(stat="identity")+geom_text(
    aes(label = n, y = n + 0.05),
    position = position_dodge(1),
    vjust = 0)

I want ALL of the levels of the variable x to be displayed on the x-axis (LETTERS[1:7]). For each Level with n>0, I want the value to display atop the bar for that level. For each level with n==0, I want the value label to NOT be displayed. Currently, the plot displays the 0 for 'empty' factor levels c("C","F"), and I want to suppress the display of '0's for those levels, but still display "C", and "F" on the x-axis.

current plot

I hope someone might be able to help me.

Thanks.

like image 736
HumanityFirst Avatar asked Jan 18 '26 23:01

HumanityFirst


1 Answers

A simple ifelse() will do it. You can enter any text you like for example ifelse( n>0, n , "No Data")

library( tidyr)
library( ggplot2)
library( dplyr )


set.seed(1); tibble(x=factor(sample(LETTERS[1:7],7,replace = T),levels = LETTERS[1:7])) %>% group_by_all() %>% count(x,.drop = F) %>% 
ggplot(mapping = aes(x=x,y=n))+geom_bar(stat="identity")+
    geom_text(
    aes(label = ifelse( n>0, n , ""), y = n + 0.05),
    position = position_dodge(1),
    vjust = 0)

example graph without zeros

like image 153
MatthewR Avatar answered Jan 20 '26 16:01

MatthewR