Develop an R program to generate facet_wrap histograms,Density Plot Function,Boxplot with Notch and Outliers,Violin Plot,Correlation Matrix Heatmap,Dot Plot with Grouped Variables
Step1: Load required libraries
library(ggplot2)library(dplyr)
Attaching package: 'dplyr'
The following objects are masked from 'package:stats':
filter, lag
The following objects are masked from 'package:base':
intersect, setdiff, setequal, union
library(tidyr)
Step 2:Multiple Histograms using facet_wrap
data(iris)p1 <-ggplot(iris, aes(x = Sepal.Length)) +geom_histogram(binwidth =0.3, fill ="skyblue", color ="black") +facet_wrap(~ Species) +labs(title ="Histogram: Sepal Length by Species", x ="Sepal Length", y ="Frequency") +theme_minimal()p1
step3:Density Plot Function
plot_density_by_group <-function(data, numeric_var, group_var, fill =TRUE) { ggplot(data, aes_string(x = numeric_var, color = group_var, fill = group_var)) +geom_density(alpha =if (fill) 0.4else0) +labs(title =paste("Density Plot of", numeric_var, "by", group_var), x = numeric_var, y ="Density") +theme_minimal() }p2 <-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.
p2
step 4:Boxplot with Notch and Outliers
p3 <-ggplot(iris, aes(x = Species, y = Sepal.Length)) +geom_boxplot(notch =TRUE, notchwidth =0.77, staplewidth =0.3, fill ="grey", color ="black", outlier.shape =15, outlier.color ="yellow") +labs(title ="Boxplot: Sepal Length by Species", x ="Species", y ="Sepal Length") +theme_minimal()p3
step 5:Violin Plot
mtcars$cyl <-as.factor(mtcars$cyl)p4 <-ggplot(mtcars, aes(x = cyl, y = mpg, fill = cyl)) +geom_violin(trim =FALSE) +labs(title ="Violin Plot: MPG by Cylinder", x ="Cylinders", y ="Miles Per Gallon") +theme_minimal() p4
step 6:Dot Plot with Grouped Variables
data(ToothGrowth)ToothGrowth$dose <-as.factor(ToothGrowth$dose)p5 <-ggplot(ToothGrowth, aes(x = dose, y = len, color = supp)) +geom_dotplot(binaxis ="y", stackdir ="center", dotsize =0.8, position =position_dodge(width =0.8)) +labs(title ="Dot Plot: Tooth Length by Dose", x ="Dose", y ="Tooth Length") +theme_minimal()p5
Bin width defaults to 1/30 of the range of the data. Pick better value with
`binwidth`.