EN VI

Plot all levels of factor within a boxplot in ggplot2?

2024-03-12 17:30:04
How to Plot all levels of factor within a boxplot in ggplot2

I want to make a boxplot with the iris dataframe. The field Species is factor with 3 levels of setosa, versicolor and virginica. When I filter out setosa, it removes the boxplot from the graph but what I want is for setosa to still be there on the x axis. How can I do this?

library(tidyverse)
iris%>%
  filter(Species!="setosa")%>%
  ggplot(aes(x=Species, y=Sepal.Length,fill=Species)) + 
  geom_boxplot()

Solution:

Add drop=FALSE to the x and/or fill scale and if you are using ggplot2 >= 3.5.0 additionally add show.legend=TRUE to geom_boxplot (otherwise the key symbol will not be shown in the fill legend):

library(tidyverse)

iris %>%
  filter(Species != "setosa") %>%
  ggplot(aes(x = Species, y = Sepal.Length, fill = Species)) +
  geom_boxplot(show.legend = TRUE) +
  scale_x_discrete(drop = FALSE) +
  scale_fill_discrete(drop = FALSE)

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login