PROGRAM 13

Author

BALAJI SINGH

Dot Plot for Grouped Data using ggplot2

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

# Load required library
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

Objective

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',
    stackdir = 'center',
    position = position_dodge(width = 0.8),
    dotsize = 0.6,
    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: ToothGrowth contains observations of tooth length in guinea pigs under different doses of Vitamin C and supplement types (VC or OJ)

  • Factor Conversion: dose is converted to a factor for categorical grouping.

  • position_dodge(): This separates dots by supp within each dose level for clearer group comparison.

  • geom_dotplot(): Plots individual data points as dots, stacked along the y-axis.