Remove empty facet with ggplot
In general, facets are used when one plots the total dataset by dividing them into subsets. But due to some null data present in dataset, the plot might contain empty facets on it. To remove them from the plot we need to use facet_wrap() function present in R Programming.
Steps to remove empty facet with ggplot:
Step 1. First, we need to install and load the ggplot2 package
R
# Install and load the ggplot package install.packages ( "ggplot2" ) library (ggplot2) |
Step 2: Creation of sample data frame
R
# Creation of sample data frame df <- data.frame (x = 1:8, # Each facet on x axis is able # to represent 8 numbers y = 1:8, # Each facet on x axis is able # to represent 8 numbers g1 = rep ( LETTERS [1:4], each = 2), # The first four upper case letters # are generated each twice g2 = letters [1:4] # The first four lower case letters # are generated randomly ) |
Step 3: Plotting the facet plot using ggplot and facet_grid(). The facet_grid() is a function which is used to break down the plot into grid of plots for each combination of variables even if some facets are empty.
R
# Plotting the facet plot using ggplot and facet_grid() plot <- ggplot (df, aes (x, y)) + geom_point ()+ facet_grid (g1 ~ g2) plot |
Output:
Step 4: So from the output we can observe there are 8 empty facets. To remove them we are going to use facet_wrap() function which is responsible to produce plots for a combination of variables which only have values.
R
# Removing empty facets from the plot using facet_wrap() plot <- plot + facet_wrap (g1 ~ g2) plot |
Output:
Contact Us