library(ggplot2)
Program 10
Develop an R function to draw a density curve representing the probability density function of a contionous variable, with seperate curves for each group, using ggplot2
Step 1:Load the required libraries
Step 2: Define the function
<- function(data, continuous_var, group_var, fill_colors = NULL) {
plot_density_by_group if (!(continuous_var %in% names(data)) || !(group_var %in% names(data))) {
stop("Invalid column names. Make sure both variables exist in the dataset.")
}<- ggplot(data, aes_string(x = continuous_var, color = group_var, fill = group_var)) +
p 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 + scale_fill_manual(values = fill_colors) +
p scale_color_manual(values = fill_colors)
}return(p)
}
Step 3: Built-in Dataset
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.
Step 5: With Custom colors
# Define custom colors
<- c("setosa" = "steelblue",
custom_colors "versicolor" = "forestgreen",
"virginica" = "darkorange")
# Plot with custom colors
plot_density_by_group(iris, "Petal.Length", "Species", fill_colors = custom_colors)