R How to Draw a ggplot2 Barchart with Empty Factor Levels (Example Code)

This tutorial illustrates how to create a barchart that shows empty factor levels in R.

Setting up the Example

my_df <- data.frame(group = LETTERS[1:4],    # Creating some example data
                    values = c(6, 3, 0, 4))
my_df <- my_df[my_df$values > 0, ]
my_df                                        # Printing example data
#   group values
# 1     A      6
# 2     B      3
# 4     D      4
install.packages("ggplot2")                  # Install ggplot2 package
library("ggplot2")                           # Load ggplot2 package
my_plot <- ggplot(my_df,                     # Draw ggplot2 plot with default specifications
                  aes(x = group,
                      y = values,
                      fill = group)) +
  geom_bar(stat = "identity")
my_plot                                      # Draw barplot

r graph figure 1 r draw ggplot2 barchart empty factor levels

Example: Draw Barplot with Empty Factor Levels

my_plot +                                    # Creating barplot again with scale_x_discrete
  scale_x_discrete(drop = FALSE)

r graph figure 2 r draw ggplot2 barchart empty factor levels

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed