program 13

Author

kumkum mk 1nt23is106

13 . Write a R program to create multiple dot plots for grouped data comparing the distribution of variable across different categories using ggplot’2 position_dodge function.

Step 1: 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

Step 2: Load the dataset

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
summary(ToothGrowth) #provides summary statistics for each variable in the ToothGrowth dataset
      len        supp         dose      
 Min.   : 4.20   OJ:30   Min.   :0.500  
 1st Qu.:13.07   VC:30   1st Qu.:0.500  
 Median :19.25           Median :1.000  
 Mean   :18.81           Mean   :1.167  
 3rd Qu.:25.27           3rd Qu.:2.000  
 Max.   :33.90           Max.   :2.000  
class(ToothGrowth)
[1] "data.frame"
class(ToothGrowth$dose)
[1] "numeric"
table(ToothGrowth$dose)

0.5   1   2 
 20  20  20 

Step 3: Create multiple dotplots

#Converts the dose column from a numeric variable to a factor, so it's treated as a categorical variable in the plot.
ToothGrowth$dose <- as.factor(ToothGrowth$dose)

#Comment: Initializes the ggplot object using the ToothGrowth dataset.
ggplot(ToothGrowth,aes(x=dose,y=len,color=supp))+
    geom_dotplot(
      binwidth = 1.5, #controls the spacing of dots on y axis
    binaxis = "y",       
    stackdir = "up",# centers the stracking of dots
    stackratio = 1,
    dotsize = 0.6,      # set the size of each dots 
    position = position_dodge(width=0.8)
  
  ) +
  # Adds labels to the plot:
  labs(title = "Dot Plot of Tooth Length by Dose and Supplement Type",
       x = "Dose",
       y = "Tooth Length") +
  #for a clean and simple appearance
  theme_minimal()