Program-13

Author

Greeshma PM(1nt23is078)Section-B

13.Write a R program to create multiple dot plots comparing distribution of variables, across different categories using ggplot2’s position dodge function.

Step1: 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

Step2: load required 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)
      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"
class(ToothGrowth$supp)
[1] "factor"
table(ToothGrowth$dose)

0.5   1   2 
 20  20  20 

Step 3:Create multiple dotplots

ToothGrowth$dose <- as.factor(ToothGrowth$dose)
ggplot(ToothGrowth, aes(x= dose,y=len,color= supp)) +
  geom_dotplot(
    binwidth= 1.5, #controls spacing of dots on y-axis
    binaxis ="y",  #aligns the bins along y-axis 
    dotsize=0.6, # sets size of each dot
    stackdir = "center", # centers the stacking of dots
    position =position_dodge(width=0.8)
  )+
  labs(title = "Dot Plot of Tooth Length by Dose", #title of graph
       x="Dose", #sets the x axis to dose variable
       y= "Tooth Length",  # y axis-label
       color = "Supplement Type")+
  theme_minimal()