Program 13

Author

Tejaswini Reddy U

13. Write an R program to create many dotplots from the grouped data, comparing the distributions of variables across using ggplot2’s position_dodge functions.

Step 1: Load the 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
data("ToothGrowth")

Step 2: Deal with 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

Step 3: Convert dose as a factor

ToothGrowth$dose <- as.factor(ToothGrowth$dose)

Step 4: Create dotplot

ggplot(ToothGrowth, aes(x = dose, y = len, color = supp)) +
  geom_dotplot(binaxis = "y", stackdir = "center", 
               position = position_dodge(width = 0.8), 
               dotsize = 0.6, binwidth = 1.5) +
  labs(title = "Tooth Length by Dose and Supplement Type",
       x = "Dose (mg/day)",
       y = "Tooth Length",
       color = "Supplement") +
  theme_minimal()