Add labels on a bar plot when the value is zero

Hello everyone!

I've got a barplot and I coded it to keep a space for the categories with a 0% value. I also added a code to display the labels for the values (in %). However, this does not work for my categories with a 0% value.

ggplot(df, aes(x=var)) +
    geom_bar() +
    scale_x_discrete(drop=F)+
    geom_text(aes(label = scales::percent(..prop..), group = 1), stat= "count") 

Any idea how to fix that?

Many thanks!

Hello.
Thanks for providing code , but you could take further steps to make it more convenient for other forum users to help you.

Share some representative data that will enable your code to run and show the problematic behaviour.

You might use tools such as the library datapasta, or the base function dput() to share a portion of data in code form, i.e. that can be copied from forum and pasted to R session.

Reprex Guide

Hello,

I created a random variable so anyone can see how the graph looks like.
So I get a space for the value "c" on my bar chart but I would like to add a 0%. Please note that this code will be included in a function to automatically generate graphs so I would like to avoid adding "0%" manually.

library(ggplot2)
vari <- factor(c("a", "a","b", "a", "a", "b"), levels=c("a","b","c"))
dfr <- as.data.frame(vari)

ggplot(dfr, aes(x=vari)) +
  geom_bar() +
  scale_x_discrete(drop=F)+
  geom_text(aes(label = scales::percent(..prop.., accuracy=1), group = 1), stat= "count", vjust=-1, size=4)+
  labs(y="Proportion of respondents") 

Many thanks

I would approach the task in this way:

library(tidyverse)
vari <- factor(c("a", "a","b", "a", "a", "b"), levels=c("a","b","c"))
dfr <- as.data.frame(vari)

(dfrsummary <- group_by(dfr,
                       vari,.drop=FALSE) %>% 
                  summarise(n=n()) %>% 
                  mutate(fraction=n/sum(n)))

ggplot(dfrsummary, aes(x=vari,y=n)) +
  geom_col() +
  geom_text(aes(label = scales::percent(fraction, accuracy=1)),
            vjust=-1, size=4)+
  labs(y="Proportion of respondents")

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.