Basic Multiple Density Plot

To make multiple density plots with coloring by variable in R with ggplot2, we firstly make a data frame with values and category. Then we draw the ggplot2 density plot using the geom_desnity() function. To color them according to the variable we add the fill property as a category in the ggplot() function.

Syntax: 

ggplot(dataFrame, aes( x, color, fill)) + geom_density()

Example:

We get multiple density plots in the ggplot of two colors corresponding to two-level/values for the second categorical variable. If our categorical variable has n levels, then ggplot2 would make multiple density plots with n densities/color.

R




# load library
library(tidyverse)
  
set.seed(1234)
  
# create the dataframe
df <- data.frame(
    category=factor(rep(c("category1", "category2","category3"),
                        each=1000)),
    value=round(c(rnorm(1000, mean=65, sd=5),
                  rnorm(1000, mean=85, sd=5),
                 rnorm(1000, mean=105, sd=5))))
  
  
  
# Basic density plot with custom color
# color property to determine the color of plot
# fill property to determine the color beneath plot
ggplot(df, aes(x=value, color=category, fill=category)) +
geom_density(alpha=0.3)


Output:

How to Add Vertical Lines By a Variable in Multiple Density Plots with ggplot2 in R

In this article, we will discuss how to add vertical lines by a variable in multiple density plots with ggplot2 package in the R  Programming language. 

To do so first we will create multiple density plots colored by group and then add the line as a separate element.

Similar Reads

Basic Multiple Density Plot:

To make multiple density plots with coloring by variable in R with ggplot2, we firstly make a data frame with values and category. Then we draw the ggplot2 density plot using the geom_desnity() function. To color them according to the variable we add the fill property as a category in the ggplot() function....

Adding Line by a variable

...