library(ggplot2)pr10
step 1:
step 2: Define function
plot_density_by_group <- function(data,continuous_var,group_var,fill_colors = NULL){
if(!(continuous_var %in% names(data)) || !(group_var %in% names(data)))
{
stop("Invaild column names.Make sure both variable exist in the dataset.")
}
p <- ggplot(data,aes_string(x = continuous_var,color = group_var,fill = group_var))+
geom_density(alpha=0.4)+
labs(title = paste("Density plot of",continuous_var,"by",group_var),
x = continuous_var,
y = "Density")+
theme_minimal()
if(!is.null(fill_colors)){
p <- p + scale_fill_manual(values = fill_colors)+
scale_color_manual(values = fill_colors)
}
return(p)
}# Basic usage
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.
custom_colors <- c("setosa" = "steelblue",
"versicolor" = "forestgreen",
"virginica"= "darkorange")
plot_density_by_group(iris,"Petal.Length","Species",fill_colors = custom_colors)custom_colors <- c("setosa" = "steelblue",
"versicolor" = "forestgreen",
"virginica"= "darkorange")
plot_density_by_group(iris,"Sepal.Length","Species",fill_colors = custom_colors)custom_colors <- c("setosa" = "steelblue",
"versicolor" = "forestgreen",
"virginica"= "darkorange")
plot_density_by_group(iris,"Petal.Width","Species",fill_colors = custom_colors)custom_colors <- c("setosa" = "steelblue",
"versicolor" = "forestgreen",
"virginica"= "darkorange")
plot_density_by_group(iris,"Sepal.Width","Species",fill_colors = custom_colors)