Program 13

Author

Kusuma B M 1NT23IS108

Write an R program to create multiple dot plots or group data , comparing the distribution of variables across different categories, using ggplot2’s position_dodge function.

Step 1: Load the required library

library(ggplot2)
Warning: package 'ggplot2' was built under R version 4.4.3
library(dplyr)
Warning: package 'dplyr' was built under R version 4.4.3

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:Load the dataset

str("ToothGrowth")
 chr "ToothGrowth"
data("ToothGrowth")
table(ToothGrowth$len)

 4.2  5.2  5.8  6.4    7  7.3  8.2  9.4  9.7   10 11.2 11.5 13.6 14.5 15.2 15.5 
   1    1    1    1    1    1    1    1    2    2    2    1    1    3    2    1 
16.5 17.3 17.6 18.5 18.8 19.7   20 21.2 21.5 22.4 22.5   23 23.3 23.6 24.5 24.8 
   3    2    1    1    1    1    1    1    2    1    1    1    2    2    1    1 
25.2 25.5 25.8 26.4 26.7 27.3 29.4 29.5 30.9 32.5 33.9 
   1    2    1    4    1    2    1    1    1    1    1 
table(ToothGrowth$dose)

0.5   1   2 
 20  20  20 

Step 3:Create a dot plot

ToothGrowth$dose <- as.factor(ToothGrowth$dose)
ggplot(ToothGrowth, aes(x = dose, y = len, color = supp)) +
  geom_dotplot(
    binaxis = 'y',
    stackdir = 'center',#direction to stack the dots
    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()