Search code examples
rggplot2geom-bar

How to drop x value from ggplot with discrete axis?


This may be something that is an easy fix.

I am creating a new dashboard in shiny and it's been asked by my company that all plots be ordered by a list. So naturally I created a list and used scale_x_discrete(limits = list). However, what is being asked for now is for values where it is equal to zero to be removed whilst still retaining the order of the list. Is this possible to do with scale_x_discrete()?

i.e the plot generated would exclude the variable "different" whilst keeping the order of names <- c("before", "same", "different").

Any help is greatly appreciated, here is a reproducible example below.

# packages ----------------------------------------------------------------
{
  library(dplyr)
  library(ggplot2)
}
# Data --------------------------------------------------------------------

names <- c("before", "same", "different")
values <- c(7, 90, 0)

df <- data.frame(names, values)


# ggplot ------------------------------------------------------------------

ggplot(df, aes(names, values))+
  geom_bar(stat = "identity")+
  scale_x_discrete(limits = names) 

Solution

  • You just subset the names when you pass in the limits:

    ggplot(df, aes(names, values))+
      geom_bar(stat = "identity")+
      scale_x_discrete(limits = names[values>0])