These exercises cover the Geoms and Aesthetics of ggplot2 for Plotting in R.
These first few exercises will run through some of the simple principles of creating a ggplot2 object, assigning aesthetics mappings and geoms.
getwd()
## [1] "/__w/Plotting_In_R/Plotting_In_R/extdata"
<- read.delim("./data/patients_clean_ggplot2.txt",sep="\t") patients_clean
library(ggplot2)
<- ggplot(data=patients_clean,
plot mapping=aes(x=BMI,y=Weight))+geom_point()
plot
<- ggplot(data=patients_clean,
plot mapping=aes(x=BMI,y=Weight,colour=Height))+geom_point()
plot
<- ggplot(data=patients_clean,
plot mapping=aes(x=BMI,y=Weight,colour=Height))+geom_point()
+facet_grid(Sex~Smokes) plot
<- ggplot(data=patients_clean,
plot mapping=aes(x=BMI,y=Weight,colour=Height))+geom_point()+
geom_smooth()
plot
## `geom_smooth()` using method = 'loess' and formula 'y ~ x'
<- ggplot(data=patients_clean,
plot mapping=aes(x=BMI,y=Weight,colour=Height))+geom_point()+
geom_smooth(method="lm",se=F)
plot
## `geom_smooth()` using formula 'y ~ x'
###Boxplots and Violin plots
<- ggplot(data=patients_clean,
plot mapping=aes(x=Smokes,y=BMI))+geom_boxplot()
plot
<- ggplot(data=patients_clean,
plot mapping=aes(x=Smokes,y=BMI,colour=Sex))+geom_boxplot()
plot
<- ggplot(data=patients_clean,
plot mapping=aes(x=Smokes,y=BMI,colour=Sex))+
geom_boxplot()+
facet_wrap(~Age)
plot
HINT - Discrete values such as in factors are used for categorical data.
<- ggplot(data=patients_clean,
plot mapping=aes(x=Sex,y=BMI,colour=factor(Age)))+
geom_boxplot()+
facet_wrap(~Smokes)
plot
<- ggplot(data=patients_clean,
plot mapping=aes(x=Sex,y=BMI,colour=factor(Age)))+
geom_violin()+
facet_wrap(~Smokes)
plot
###Histogram and Density plots
<- ggplot(data=patients_clean,
plot mapping=aes(BMI))+
geom_histogram(fill="blue")
plot
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
HINT: alpha can be used to control transparancy.
<- ggplot(data=patients_clean,
plot mapping=aes(BMI))+ geom_density(aes(fill=Sex),alpha=0.5)
plot
<- ggplot(data=patients_clean,
plot mapping=aes(BMI))+ geom_density(aes(fill=Sex),alpha=0.5)
+facet_wrap(~Grade) plot