programm13

Author

G.GEYA 1NT23IS079

Write an R program to create a multiple dot plot for grouped variables across different categories using ggplot2’s position_dodge function.

Step 1: load required libraries

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 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
class(ToothGrowth$len)
[1] "numeric"
class(ToothGrowth$dose)
[1] "numeric"
class(ToothGrowth$supp)
[1] "factor"
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  
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$dose)

0.5   1   2 
 20  20  20 

step 3: create multiple dot graphs

ToothGrowth$dose <- as.factor(ToothGrowth$dose)         #converts the dose to data type factor
ggplot(ToothGrowth,aes(x=dose,y=len,color=supp))+       #setting aesthetics
    geom_dotplot(
    binaxis = "y",       #stack positioning is horizontally
    stackdir = "center", #plotting of grouped dots position 
    dotsize = 0.8,       #declaring size of plotted dots   
    position = position_dodge(width=0.8), #stacking isn't layered
  ) +
  labs(title = "Dot Plot of Tooth Length by Dose",  #declaring title  of graph
       x = "Dose",                                  #x-axis label
       y = "Tooth Length"                           #y-axis label
   ) +
  theme_minimal() #producing clean and clear background for plotted graph
Bin width defaults to 1/30 of the range of the data. Pick better value with
`binwidth`.