1. create a plot object:
p= ggplot(diamonds,aes(carat,price,color=cut))
dataset / mappings :aes()
2. add a layer:
a minimal layer is to specify a geom.
e.g. p=p+layer(geom="point)
p+geom_histogram(binwidth=2, fill="steelblue")
function like this:
geom_xxx(mappings, data,...,geom,position)
...:parameters for the geom or stats, such as bin_width for histogram or bandwidth for a loess smoother
mappings: specified using aes() optional
data: a dataset overrides the default plot dataset. optional
geom or stat: optional
plot and layer are all object in R, they can be stored as variables.
bestfit=geom_smooth(method="lm",se=F,color=alpha("red",0.5,size=2)
qplot(sleep_rem,sleep_total,data=msleep)+bestfit
qplot(awake, brainwt, data=msleep,log="y")+bestfit
qplot (bodywt, brainwt,data=msleetp, log="xy")+bestfit
data: must be a dataframe
replace an old dataset using %+%
Aesthetic mappings:
aes(x=weight,y=height,color=sqrt(age))
functions of variables can be used
setting vs. mapping
p=ggplot(mtcars, aes(mpg,wt))
p+geom_point(color="darkblue")
is very different than
p+geom_point(aes(color=“darkblue"))
in qplot, use color=I("darkblue") to set a value
Grouping:
you want to separate your data into groups, but render them in the same way.
p=ggplot(Oxboys, aes(age,height,group=Subject))+geom_line()
different groups on different layers
p+geom_smooth(aes(group=1),method="lm",size=2,se=F)
Override the default grouping
boysbox=ggplot(Oxboys, aes(Occasion, height))+geom_boxplot()
OVERRIDE the default grouping :
boysbox=boysbox+geom_line(aes(group=Subject),color="#3366FF")
ggplot(diamonds,aes(carat))+geom_histogram(aes(y=..density..),binwidth=0.1)
d=ggplot(diamonds, aes(carat))+xlim(0,3)
d+stat_bin(aes(ymax=..count..),binwidth=0.1)
d+stat_bin(aes(size=..density..),binwidth=0.1,geom="point",position="identify")
d+stat_bin(y=1,fill=..count..), binwidth=0.1,geom="tile",position="identify")
plot different data on the same plot:
a very common example is supplementing the data with predictions from a model.
model=lme(height~age,data=Oxboys,random=~1+age|Subject))
oplot=ggplot(Oxboys,aes(age,height,group=Subject)+geom_line()
age_grid=seq(-1,1,length=10)
subjects=unique(Oxboys$Subjects)
preds=expand.grid(age=age_grid,Subject=subjects)
preds$height=predict(model,preds)
oplot+geom_line(data=preds,color="#3366FF",size=0.4)
model2=update(model,height~age+I(age^2))
Oxboys$fitted=predict(model2)
Oxboys$resid2=with(Oxboys,fitted-height)
oplot %+%Oxboys+aes(y=resid2)+geom_smooth(aes(group=1))