Skip to content
Related Articles
Open in App
Not now

Related Articles

Create Boxplot with respect to two factors using ggplot2 in R

Improve Article
Save Article
  • Last Updated : 18 Jul, 2021
Improve Article
Save Article

Multiple variable distributions can be visualized with boxplots. ggplot2 allows us to create beautiful boxplots quickly. It is possible to have multiple subgroups for a variable of interest. In those situations, it is very useful to visualize using “grouped boxplots”. The ggplot2 package in R programming language provides a number of options for visualizing such grouped boxplots. 

Now talking about Boxplot, then each boxplot is created for every category or level in that factor that is represented by a factor and a numerical column. geom_boxplot also allows us to plot both factors using the fill argument when there are two factors. Geom_boxplot() is the key function


geom_boxplot(width,notch,color,size,linetype, fill,outliner.color, outliner.size, outliner.shape)


  • width: width of the boxplot
  • notch: if it is true then it will create a notched boxplot and notches are used to compare boxplots.
  • color, size,line type: borderline, color, size and shape.
  • fill: used to fill box plot areas.
  • outlier.colour, outlier.shape, outlier.size: The color, the shape and the size for outlying points.

Now let us look at few implementations.

Example 1:


# create a Data Frame
# creating a boxplot


Example 2:


# load ggplot2 package if already installed
# create a data frame with two factors 
df <- data.frame(Factor1=factor(rbinom(30, 1, 0.55), 
                   Factor2=factor(rbinom(30, 1, 0.45), 
# Now make a interaction between two factors 
# on x axis  
df$Factor1Factor2 <- interaction(df$Factor1, df$Factor2) 
# now Plot Boxplot with fill color according
# to factor1 and factor2
ggplot(aes(y = Values, x = Factor1Factor2), data = df) + 


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!