program 13.quarto

Author

sirisha BA

Write an R program to create multiple dot plots for grouped data , comparing the distribution of variable across different using ggplot2’s position dodge function .

Step 1: Load the library

# Load the necessary 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

Step2 : Load the built-in dataset.

# Load the ToothGrowth dataset
data("ToothGrowth")
str(ToothGrowth)
'data.frame':   60 obs. of  3 variables:
 $ len : num  4.2 11.5 7.3 5.8 6.4 10 11.2 11.2 5.2 7 ...
 $ supp: Factor w/ 2 levels "OJ","VC": 2 2 2 2 2 2 2 2 2 2 ...
 $ dose: num  0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 ...
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: conversion

# Convert 'dose' to a factor to ensure it is treated as a categorical variable
ToothGrowth$dose <- as.factor(ToothGrowth$dose)
ToothGrowth$dose
 [1] 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 1   1   1   1   1   1   1   1   1  
[20] 1   2   2   2   2   2   2   2   2   2   2   0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5
[39] 0.5 0.5 1   1   1   1   1   1   1   1   1   1   2   2   2   2   2   2   2  
[58] 2   2   2  
Levels: 0.5 1 2

Step3: create dot plots

# Create the dot plot
ggplot(ToothGrowth, aes(x = factor(dose), y = len, color = supp)) +
  geom_dotplot(
    binaxis = "y",        # Stack the dots along the y-axis
    stackdir = "center",  # Center the dots
    position = position_dodge(width = 0.8),  # Separate dots by 'supp' using position dodge
    dotsize = 0.6,   # Adjust dot size for clarity
    binwidth = 1.5   # width of the bin
  ) +
  labs(
    title = "Dot Plot of Tooth Length by Dose and Supplement Type",
    x = "Dose(mg/day) ",
    y = "Tooth Length (mm)",
    color = "Supplement Type"
  ) +
  theme_minimal()