Lets look at some boxplots
data("ToothGrowth")
Lets change the dose to a factor, and look at the top of the dataframe
ToothGrowth$dose <- as.factor(ToothGrowth$dose)
head(ToothGrowth,4)
## 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
Lets load ggplot
library(ggplot2)
Lets set the theme for our plots to classic
theme_set(
theme_bw()+
theme(legend.position = "top")
)
Lets start with a very basic boxplot with dose vs length
tg <- ggplot(ToothGrowth,aes(x=dose,y=len))
tg+geom_boxplot()
Now lets look at a boxplot with points for the mean
tg +geom_boxplot(notch = TRUE,fill="lightgrey")+
stat_summary(fun.y=mean,geom="point",shape=18,size=2.5,color="indianred")
## Warning: The `fun.y` argument of `stat_summary()` is deprecated as of ggplot2 3.3.0.
## ℹ Please use the `fun` argument instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
We can also change the scale number of variables included, and their order
tg + geom_boxplot()+
scale_x_discrete(limits=c("0.5","2"))
## Warning: Removed 20 rows containing missing values (`stat_boxplot()`).
Let put our x axis in descending order
tg + geom_boxplot()+
scale_x_discrete(limits=c("2","1","0.5"))
We can also change boxplot colors by groups
tg+geom_boxplot(aes(color =dose))+
scale_color_manual(values=c("indianred","blue1","green2"))
What if we want to display our data subset data subset by oj vs vitamin c?
tg2 <- tg + geom_boxplot(aes(fill=supp),position=position_dodge(0.9))+
scale_fill_manual(values = c("#999999","#E69F00"))
tg2
We can also arrange this as two plots with facet_wrap
tg2+facet_wrap(~supp)