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 |
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 |
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 |
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
Example: Draw Barplot with Empty Factor Levels
my_plot + # Creating barplot again with scale_x_discrete scale_x_discrete(drop = FALSE) |
my_plot + # Creating barplot again with scale_x_discrete scale_x_discrete(drop = FALSE)