Smith Pay
Smith Pay

Reputation: 49

Showing a level that doesn't exist in your data in a bar chart using ggplot in R

I have generated some data to illustrate the problem that I am having:

m <- matrix(rep(c(2:7), 38), ncol=19, nrow=38, byrow=T)


C1 <- data.frame(factor(m,levels = c(1:7)));C1

cols <- "C"
colnames(C1) <- cols

Cog = C1 %>% group_by(C ) %>%
summarise(count=n()) %>%
mutate(pct=count/sum(count)) 

ggplot(Cog, aes(x=C , y=pct, colour=C , fill=C )) +
geom_bar(stat="identity") +
scale_y_continuous(labels=percent, limits=c(0,0.50)) + 
geom_text(data=Cog, aes(label=paste0(round(pct*100,1),"%"),
                      y=pct+0.012), size=4)

You can see that the data that I am generating (m) does not have 1's and my actual data does not have 1's as well. But I would like to show in a bar graph that 1's does exist in my data but has 0%.

Upvotes: 0

Views: 352

Answers (1)

Wimpel
Wimpel

Reputation: 27732

add scale_x_discrete( drop = FALSE ) to your plot

library( ggplot2 )
library( scales )
ggplot(Cog, aes(x=C , y=pct, colour=C , fill=C )) +
  geom_bar(stat="identity") +
  scale_y_continuous( labels = percent, limits=c(0,0.50)) + 
  geom_text(data=Cog, aes(label=paste0(round(pct*100,1),"%"),
                          y=pct+0.012), size=4) +
  scale_x_discrete( drop = FALSE )

enter image description here

alternative 'solution'

bind the data into your dataframe (feels a bit like cheating, but gets the job done).

Cog = C1 %>% group_by(C ) %>%
  summarise(count=n()) %>%
  mutate(pct=count/sum(count)) %>%
  rbind(c(1,0,0))  #  <--------------  add an empty '1' category to plot


ggplot(Cog, aes(x=C , y=pct, colour=C , fill=C )) +
  geom_bar(stat="identity") +
  scale_y_continuous( labels = percent, limits=c(0,0.50)) + 
  geom_text(data=Cog, aes(label=paste0(round(pct*100,1),"%"),
                          y=pct+0.012), size=4) 

enter image description here

Upvotes: 2

Related Questions