library(ggplot2)program 10
Develop an r function to draw a density curve representing the probablitlity density function of a continuous varaiable,with seperate curves for each group,using ggplot2.
step1:load the necessary libraray
step2:define the 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("invalid column names.make sure both varaiables exist in the dataset.")
}
p <- ggplot(data,aes_string(x = continuous_var , color = group_var , fill = group_var))+
geom_density(aplha = 0.4)+
labs(title = paste("density plot of",continuous_var,"by",group_var),
x = "continous_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)
}step3::Load dataset
data(iris)
head(iris) Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa
step 4: call the function with example
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.
Warning in geom_density(aplha = 0.4): Ignoring unknown parameters: `aplha`