Remove empty facet with ggplot
Last Updated :
27 Mar, 2023
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.packages ( "ggplot2" )
library (ggplot2)
|
Step 2: Creation of sample data frame
R
df <- data.frame (x = 1:8,
y = 1:8,
g1 = rep ( LETTERS [1:4], each = 2),
g2 = letters [1:4]
)
|
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
plot <- ggplot (df, aes (x, y)) +
geom_point ()+
facet_grid (g1 ~ g2)
plot
|
Output:
Plot with Empty Facets
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
plot <- plot + facet_wrap (g1 ~ g2)
plot
|
Output:
Plot without Empty Facets
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...