ggplot_scatter_plots.r

IanMacPro — Nov 17, 2013, 7:20 PM

library (ggplot2)
library (gcookbook)

#1. Basic scatter plot
head(heightweight[,c("ageYear", "heightIn")])
  ageYear heightIn
1   11.92     56.3
2   12.92     62.3
3   12.75     63.3
4   13.42     59.0
5   15.92     62.5
6   14.25     62.5

ggplot(heightweight, aes(x=ageYear, y=heightIn))+
  geom_point()#shape 16 (19 better for printing), size 2

plot of chunk unnamed-chunk-1


ggplot(heightweight, aes(x=ageYear, y=heightIn))+
  geom_point(shape=21)

plot of chunk unnamed-chunk-1


ggplot(heightweight, aes(x=ageYear, y=heightIn))+
  geom_point(shape=21, size=4)

plot of chunk unnamed-chunk-1


#2. Different shapes and colours
head(heightweight[,c("sex", "ageYear", "heightIn")])
  sex ageYear heightIn
1   f   11.92     56.3
2   f   12.92     62.3
3   f   12.75     63.3
4   f   13.42     59.0
5   f   15.92     62.5
6   f   14.25     62.5

ggplot(heightweight, aes(x=ageYear, y=heightIn, colour=sex))+
  geom_point(shape=21, size=4)

plot of chunk unnamed-chunk-1


ggplot(heightweight, aes(x=ageYear, y=heightIn, shape=sex))+
  geom_point (size=4)

plot of chunk unnamed-chunk-1


ggplot(heightweight, aes(x=ageYear, y=heightIn, colour=sex, shape=sex))+
  geom_point (size=4)+
  scale_shape_manual(values=c(1,2))+
  scale_colour_brewer(palette="Set1") #or scale_colour_manual(values=c(1,2))

plot of chunk unnamed-chunk-1


#3. More colour, shape & fill
hw <- heightweight

hw$weightGroup <- cut(hw$weightLb, breaks=c(-Inf,100,Inf),
                      labels=c("<100", ">100"))

hw$ageGroup <- cut(hw$ageYear, breaks=c(-Inf,14,Inf),
                      labels=c("<14", ">14"))

#Use shape, colour and fill in addition to x, y axis
# which is 5 variables
ggplot(hw, aes(x=ageYear, y=heightIn, shape=sex, colour=ageGroup, fill=weightGroup))+
  geom_point (size=3)+
  scale_shape_manual(values=c(21,24))+
  scale_colour_manual(values=c(1,2)) +
  scale_fill_manual(values=c(NA, "black"),
                    guide=guide_legend(override.aes=list(shape=21))) 

plot of chunk unnamed-chunk-1