Tech talk ggplot2

Post on 26-Jan-2015

120 views 3 download

Tags:

description

A quick introduction to the ggplot2 R package by Hadley Wickham which implements the Grammar of Graphics paradigm in the R language.

Transcript of Tech talk ggplot2

ggplot2

Jeff AllenQuantitative Biomedical Research Center

3.18.13

Slides adapted/stolen from Garret Grolemund/RStudio’s Data Visualization Course

Getting Started

install.packages(c("ggplot2", "hexbin","ggmap", "maps", "RColorBrewer",

"scales","ReadImages"))library(ggplot2)library(hexbin)library(ggmap)library(maps)library(RColorBrewer)library(scales)library(ReadImages)

Grammar of Graphics

• Framework for describing visualized data– Mapping data onto a coordinate system

• Created by Leland Wilkinson

Your First ggplot2 Plot

> library(ggplot2)> head(mpg) manufacturer model displ year cyl trans drv cty hwy fl class1 audi a4 1.8 1999 4 auto(l5) f 18 29 p compact2 audi a4 1.8 1999 4 manual(m5) f 21 29 p compact3 audi a4 2.0 2008 4 manual(m6) f 20 31 p compact4 audi a4 2.0 2008 4 auto(av) f 21 30 p compact5 audi a4 2.8 1999 6 auto(l5) f 16 26 p compact6 audi a4 2.8 1999 6 manual(m5) f 18 26 p compact

Your First ggplot2 Plot

ggplot(data=mpg, aes(x=cty, y=hwy))

+ geom_point()

Your First ggplot2 Plot

ggplot(data=mpg, aes(x=cty, y=hwy))

+ geom_point()

The data.frame

to plot

Your First ggplot2 Plot

ggplot(data=mpg, aes(x=cty, y=hwy))

+ geom_point()

Aesthetic Mappings

The data.frame

to plot

Your First ggplot2 Plot

ggplot(data=mpg, aes(x=cty, y=hwy))

+ geom_point()

Aesthetic Mappings

The data.frame

to plot

What geom to

use in plotting

Your First ggplot2 Plot

library(ggplot2)ggplot(data=mpg, aes(x=cty, y=hwy)) + geom_point()

Improvements

Problem: verbosity

ggplot(data=mpg, aes(x=cty, y=hwy)) + geom_point()

ggplot(mpg, aes(cty, hwy)) + geom_point()

Improvements

Problem: OverplottingSolution: Different geoms

ggplot(mpg, aes(cty, hwy)) + geom_jitter()

Improvements

Problem: OverplottingSolution: Different geoms

ggplot(mpg, aes(cty, hwy)) + geom_bin2d()

Colors & Groups

ggplot(mpg, aes(cty, hwy, color=drv)) + geom_jitter()

Colors & Groups

ggplot(mpg,aes(drv, hwy)) + geom_boxplot()

Adding Layers

ggplot(mpg,aes(drv, hwy)) + geom_jitter() + geom_boxplot()

Adding Layers

ggplot(mpg, aes(cty, hwy)) + geom_jitter() + geom_smooth()

Adding Layers

ggplot(data, aes(TIME, Y, color=GROUP)) + geom_line() + geom_smooth()

Faceting

ggplot(mpg, aes(cty, hwy)) + geom_jitter()+ facet_grid(drv ~ class)

Refining Plots

ggplot(mpg, aes(cty, hwy)) + geom_jitter() + xlab("City MPG") + ylab("Hwy MPG") + ggtitle("City vs Highway MPG")

Etc.

Etc.

Etc.

Etc.

Etc.

Etc.

Etc.

Etc.