ggplot in R

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))



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值