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
Write a program to create multiple dot plots for grouped data, comparing the distribution of variable across different categories using ggplot2’s position dodge function.
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
head(ToothGrowth)
len supp dose
1 4.2 VC 0.5
2 11.5 VC 0.5
3 7.3 VC 0.5
4 5.8 VC 0.5
5 6.4 VC 0.5
6 10.0 VC 0.5
$dose <- as.factor(ToothGrowth$dose)
ToothGrowth
# Create dot plot
ggplot(ToothGrowth, aes(x = dose, y = len, color = supp)) +
# Initializes a ggplot object, mapping 'dose' to the x-axis, 'len' to the y-axis, and 'supp' to the color aesthetic.
geom_dotplot(
# Adds a dot plot geometry to the ggplot.
binaxis = 'y',
# Specifies that the dots should be stacked along the y-axis.
stackdir = 'center',
# Centers the stacked dots.
position = position_dodge(width = 0.8),
# Uses the dodge position adjustment to prevent overlapping dots for different supplement types, with a specified width.
dotsize = 0.6,
# Sets the size of each dot.
binwidth = 1.5
# Sets the width of the bins used to stack the dots along the y-axis.
+
) labs(
# Sets the labels for various plot elements.
title = "Tooth Length by Supplement and Dose",
# Sets the title of the plot.
x = "Dose (mg/day)",
# Sets the label for the x-axis.
y = "Tooth length",
# Sets the label for the y-axis.
color = "supplement length"
# Sets the title for the color legend.
+
) theme_minimal()
# Applies a minimal theme to the plot, removing background grids and unnecessary visual elements.