Density curve by group

Author

Manoj

Develop an R function to draw a density curve representing the probability density function of a continuous variable, with seperate curves for each group, usign ggplot2.

Steps

  • Step 1: Load the required libraries
  • Step 2: Define function to draw density curve
  • Step 3: Improve the visualization
  • Step 4: Use the custom colors
  • Disucssion

Step 1: Load the required libraries

we need to use ggplot2 package to crate density plots

# install.packages('ggplot2')
library(ggplot2)

Step 2: Define function to draw density curve

We will create a function called plot_density_by_group(), which accepts a data frame, the name of a continuous variable and a grouping variable - Draws density curves by group. It allows additional custom color schemes.

plot_density_by_group= function(data, continuous_var, grou_var, fill_colors=NULL){
  #check if the specified columns exist
  if(!(continuous_var %in% names(data)) || !(grou_var %in% names(data))){
    stop("Invalid column names, make sre both variables exist in the dataset")
  }
  
  
  # Create ghe ggplot object
  p= ggplot(data, aes_string(x=continuous_var, color=grou_var, fill=grou_var))+
    geom_density(alpha=0.4)+
    labs(
      title='Density plot',
      x= 'Cont Var',
      y= 'Density'
    )+
    theme_minimal()+theme(legend.position = 'top')
  
  
  if(!is.null(fill_colors)){
    p=p+scale_fill_manual(values=fill_colors)+
      scale_color_manual(values=fill_colors)
  }
  
  return(p)
}
plot_density_by_group(iris, 'Sepal.Length', 'Species')
Warning: `aes_string()` was deprecated in ggplot2 3.0.0.
ℹ Please use tidy evaluation idioms with `aes()`.
ℹ See also `vignette("ggplot2-in-packages")` for more information.

plot_density_by_group(iris, 'Sepal.Width', 'Species')

plot_density_by_group(iris, 'Petal.Length', 'Species')

plot_density_by_group(iris, 'Petal.Width', 'Species')