# Load the ggplot2 package
library(ggplot2)Program 15
Develop a report on all 7 previous programs.
Program 9
Create multiple histograms using ggplot2::facet_wrap() to visualize how a variable (e.g., Sepal.Length) is distributed across different groups (e.g., Species) in a built-in R dataset.
Step 1: Load the necessary libraries
Step 2: Load and explore the dataset
# Load the iris dataset
data(iris)
# View the first few rows of the dataset
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 3: Create grouped histograms using facet_wrap
# Create histograms using facet_wrap for grouped data
ggplot(iris, aes(x = Sepal.Length)) +
geom_histogram(binwidth = 0.3, fill = "skyblue", color = "black") +
facet_wrap(~ Species) +
labs(title = "Distribution of Sepal Length by Species",
x = "Sepal Length (cm)",
y = "Frequency") +
theme_minimal()Step 4: Explanation of each line
| Code Line | Description |
|---|---|
ggplot(iris, aes(x = Sepal.Length)) |
Initializes a plot using the iris dataset and maps Sepal.Length to the x-axis. |
geom_histogram(binwidth = 0.3, ...) |
Adds a histogram layer with a bin width of 0.3. |
fill = "skyblue" |
Sets the fill color of the bars. |
color = "black" |
Sets the border color of the bars. |
facet_wrap(~ Species) |
Creates separate histograms for each species in a grid layout. |
labs(...) |
Adds a title and axis labels. |
theme_minimal() |
Applies a minimal theme for better visualization. |
Output Description
The output will be three side-by-side histograms, each showing the distribution of Sepal Length for one of the following species:
setosaversicolorvirginica
Each histogram allows us to visually compare the distribution of Sepal Length across the species.
Summary
This exercise demonstrates:
How to create grouped visualizations using
facet_wrap().How to analyze and compare distributions across categories using histograms.
Use of
ggplot2, one of the most powerful R libraries for data visualization.
Program 10
Develop an R function to draw a density curve representing the probability density function of a continuous variable, with separate curves for each group, using ggplot2.
Step 1: Load the required library
# Load the ggplot2 package
library(ggplot2)Step 2: Define the function
plot_density_by_group <- function(data, continuous_var, group_var, fill_colors = NULL) {
# Check if the specified columns exist
if (!(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) +
labs(title = paste("Density Plot of", continuous_var, "by", group_var),
x = continuous_var,
y = "Density") +
theme_minimal()
# Apply custom fill colors if provided
if (!is.null(fill_colors)) {
p <- p + scale_fill_manual(values = fill_colors) +
scale_color_manual(values = fill_colors)
}
# Return the plot
return(p)
}Step 3: Explanation of Function Components
| Code | Description |
|---|---|
data |
The dataset (e.g., iris) |
continuous_var |
Name of the continuous variable (e.g., "Sepal.Length") |
group_var |
Grouping variable (e.g., "Species") |
aes_string() |
Maps the variables using string names (for flexibility) |
geom_density(alpha = 0.4) |
Draws smoothed density curves with transparency |
facet_wrap(~ group_var) |
Not used here; instead we overlay curves in one plot |
theme_minimal() |
Clean layout with minimal gridlines |
scale_fill_manual() |
Applies custom fill colors if provided |
Step 4: Example with built-in iris data set
# Define custom colors
custom_colors <- c("setosa" = "steelblue",
"versicolor" = "forestgreen",
"virginica" = "darkorange")
# Plot with custom colors
plot_density_by_group(iris, "Petal.Length", "Species", fill_colors = custom_colors)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: Output Description
The X-axis shows the continuous variable (e.g.,
Sepal.Length).The Y-axis shows the probability density.
Each group (e.g.,
Species) is represented by a separate curve.The
alpha = 0.4setting allows curves to overlap transparently.
Program 11
Generate a basic box plot using ggplot2, enhanced with notches and outliers, and grouped by a categorical variable using an in-built dataset in R.
Step 1: Load the required library
# Load the ggplot2 package
library(ggplot2)Step 2: Load and explore the 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
str(iris)'data.frame': 150 obs. of 5 variables:
$ Sepal.Length: num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
$ Sepal.Width : num 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
$ Petal.Length: num 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
$ Petal.Width : num 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
$ Species : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
Step 3: Create a Notched Box Plot Grouped by Species
ggplot(iris, aes(x = Species, y = Sepal.Length)) +
geom_boxplot(
notch = TRUE,
notchwidth = 0.6,
outlier.color = "red",
outlier.shape = 16,
fill = "skyblue",
alpha = 0.7
) +
labs(
title = "Sepal Length Distribution by Iris Species",
subtitle = "Box Plot with Notches and Outlier Highlighting",
x = "Species",
y = "Sepal Length (cm)"
) +
theme_minimal()Box Plot: Each box summarizes the distribution of
Sepal.Lengthfor a species — showing the interquartile range (IQR), median, and potential outliers.Notches: The notches give a rough 95% confidence interval around the median. If notches of two boxes do not overlap, the medians are significantly different.
Outliers: Points that fall outside 1.5 × IQR from the quartiles are considered outliers and shown in red.
Grouping: The plot groups values based on the categorical variable
Species, helping compare between groups.Aesthetics:
theme_minimal()provides a clean background, while colors and transparency make the plot readable.
Program 12
Write a program to create a violin plot using ggplot2 in R that displays the distribution of a continuous variable with separate violins for each group using an in-built dataset.
Step 1: Load the required library
library(ggplot2)Step 2: Use an in-built dataset
We’ll use the built-in iris dataset. This dataset includes measurements of sepal and petal lengths/widths for three species of iris flowers.
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
str(iris)'data.frame': 150 obs. of 5 variables:
$ Sepal.Length: num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
$ Sepal.Width : num 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
$ Petal.Length: num 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
$ Petal.Width : num 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
$ Species : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
Step 3: Create Violin Plot
We’ll use geom_violin() from ggplot2, with custom fill and transparency.
ggplot(iris, aes(x = Species, y = Petal.Length, fill = Species)) +
geom_violin(trim = FALSE, alpha = 0.6, color = "black") +
labs(
title = "Distribution of Petal Length by Iris Species",
x = "Species",
y = "Petal Length (cm)"
) +
theme_minimal(base_size = 14)Violin plot: Combines box plot features with a kernel density plot on each side.
trim = FALSE: Ensures full density is shown rather than clipped at extreme values.
fill = Species: Automatically assigns different fill colors to each group.
alpha: Adjusts the transparency.
theme_minimal(): Applies a clean layout for the plot.
The violin plot gives a detailed visualization of the distribution and density of the Petal.Length across different iris species. It’s a powerful alternative to box plots when you want to see the full shape of the distribution.
Program 13
Write an R program to create multiple dot plots for grouped data, comparing the distributions of variables across different categories, using ggplot2’s position_dodge function.
Step 1: Load the required libraries
# Load the ggplot2 package
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
Step 2: Create multiple dot plots
Create multiple dot plots to compare the distribution of tooth length (len) across different supplement types (supp) and dosages (dose), using position_dodge for group-wise separation.
# Convert dose to a factor for grouping
ToothGrowth$dose <- as.factor(ToothGrowth$dose)
# Plot with defined binwidth
ggplot(ToothGrowth, aes(x = dose, y = len, color = supp)) +
geom_dotplot(
binaxis = 'y', # The axis to bin along y
stackdir = 'center', # Which direction to stack the dots
position = position_dodge(width = 0.8),
dotsize = 0.6, # Diameter of the dots relative to binwidth
binwidth = 1.5 # Controls spacing of dots on y-axis
) +
labs(
title = "Dot Plot of Tooth Length by Dose and Supplement Type",
x = "Dose (mg/day)",
y = "Tooth Length",
color = "Supplement Type"
) +
theme_minimal()Explanation
Dataset:
ToothGrowthcontains observations of tooth length in guinea pigs under different doses of Vitamin C and supplement types (VCorOJ)Factor Conversion:
doseis converted to a factor for categorical grouping.position_dodge(): This separates dots by
suppwithin eachdoselevel for clearer group comparison.geom_dotplot(): Plots individual data points as dots, stacked along the y-axis.
Program 14
Develop a script in R to calculate and visualize a correlation matrix for a given dataset, with color-coded cells indicating the strength and direction of correlations, using ggplot2’s geom_tile function.
Step 1: Load the required libraries
library(ggplot2)
library(tidyr)
library(dplyr)Step 2: Use built-in dataset
We use the built-in mtcars dataset.
# Use built-in mtcars dataset
data(mtcars)
# Compute correlation matrix
cor_matrix <- cor(mtcars)
# Convert matrix to a data frame for plotting
cor_df <- as.data.frame(as.table(cor_matrix))
head(cor_df) Var1 Var2 Freq
1 mpg mpg 1.0000000
2 cyl mpg -0.8521620
3 disp mpg -0.8475514
4 hp mpg -0.7761684
5 drat mpg 0.6811719
6 wt mpg -0.8676594
Explanation:
cor(mtcars)computes pairwise correlation.as.table()flattens the matrix into a long-format table.The result has 3 columns: Var1, Var2, and the correlation value (
Freq).
Step 3: Visualize using ggplot2::geom_tile
ggplot(cor_df, aes(x = Var1, y = Var2, fill = Freq)) +
geom_tile(color = "white") + # Draw tile borders
scale_fill_gradient2(
low = "blue", mid = "white", high = "red",
midpoint = 0, limit = c(-1, 1),
name = "Correlation"
) +
geom_text(aes(label = round(Freq, 2)), size = 3) + # Show values
theme_minimal() +
labs(
title = "Correlation Matrix (mtcars)",
x = "", y = ""
) +
theme(axis.text.x = element_text(angle = 45, hjust = 1))| Step | Description |
|---|---|
cor() |
Computes correlation values between numeric variables. |
as.table() + as.data.frame() |
Converts matrix into a long format suitable for plotting. |
ggplot() |
Initializes the plot using long-form data. |
geom_tile() |
Creates color-coded tiles based on correlation values. |
scale_fill_gradient2() |
Applies a diverging color scale: red (strong +ve), blue (strong -ve), white (neutral). |
geom_text() |
Adds correlation values as text in each cell. |
theme_minimal() |
Cleans up the plot visually. |
axis.text.x |
Tilts x-axis labels for better readability. |