Develop an R program to draw a density curve representing the probability density function of a continuous variable, with separate curves for each group, using ggplot2.
# Load required packagelibrary(ggplot2)# Define a function to draw density plotsplot_density_by_group <-function(data, continuous_var, group_var, fill_colors =NULL) {# Check if the columns exist in the datasetif (!(continuous_var %in%names(data)) ||!(group_var %in%names(data))) {stop("Invalid column names: Make sure both variables exist in the dataset.") }# Create the ggplot object p <-ggplot(data, aes_string(x = continuous_var, color = group_var, fill = group_var)) +geom_density(alpha =0.4) +# semi-transparent filllabs(title =paste("Density Plot of", continuous_var, "by", group_var),x = continuous_var,y ="Density" ) +theme_minimal() +theme(plot.title =element_text(hjust =0.5)) # center the title# If custom fill colors are providedif (!is.null(fill_colors)) { p <- p +scale_fill_manual(values = fill_colors) +scale_color_manual(values = fill_colors) }# Return the plotreturn(p)}# Example usage with iris dataset# Plot Sepal.Length by Speciesplot_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.