0828
Chapter 2 ggplot2 入门
- ggplot2图像的三个基本构成
1.数据
2.图形属性映射,设定变量如何射映到图层的图形属性上
3.几何对象,至少一层,用于指定绘图所用的几何对象
ggplot(mpg,aes(x = displ,y = hwy))+geom_point()

ggplot(economics,aes(date,unemploy))+geom_line()

ggplot(mpg,aes(cty))+geom_histogram()

ggplot(mpg,aes(displ,cty,colour=class))+
geom_point()

ggplot(mpg,aes(displ,hwy)) + geom_point(aes(colour="blue"))

ggplot(mpg,aes(displ,hwy)) + geom_point(colour="blue")

0829颜色和形状适合分类数据,大小适合连续数据
2.5 Facetting
ggplot(mpg,aes(displ,cyl))+
geom_point()+
facet_wrap(~class)

2.6 gemo( )
- 点图+平滑曲线
- method="gam" 家在广义模型,用于大数据
ggplot(mpg,aes(displ,hwy))+
geom_point()+
geom_smooth()

geom_smooth()smooth程度可以调整
ggplot(mpg,aes(displ,hwy))+
geom_point()+
geom_smooth(span=0.2)

-
又或者把默认的lowess回归改成直线回归
2.6.2 Boxplots and jittered points
- 扰动点图
geom_jitter() - 箱线图
geom_boxplot() - 小提琴图
geom_violin()
可以更改colour和fill来调整轮廓和填充颜色
| geom_point() | geom_jitter() | geom_boxploy() | geom_violin() |
|---|---|---|---|
![]() |
![]() |
![]() |
![]() |
Histgrams and fréquencey polygons
ggplot(mpg,aes(hwy))+
geom_histogram()
| geom_histogram() | geom_freqpoly() |
|---|---|
![]() |
![]() |
-
geom_freqpoly()可以设置binwidth=
ggplot(mpg,aes(displ,colour=drv))+
geom_freqpoly(binwidth=0.5)
ggplot(mpg,aes(displ,fill=drv))+
geom_histogram(binwidth=0.5)+
facet_wrap(~drv,ncol=1)
| geom_freqpoly() | geom_histogram() |
|---|---|
![]() |
![]() |
2.6.4 Bar Charts
ggplot(mpg, aes(manufacturer))+
geom_bar()

2.6.5 Time series
year<-function(x)as.POSIXlt(x)$year+1900
ggplot(economics, aes(unemploy / pop, uempmed)) +
geom_path(colour = "grey50") +
geom_point(aes(colour = year(date)))

2.7 修饰坐标轴
ggplot(mpg,aes(cty,hwy))+geom_point(alpha=1/3)

ggplot(mpg,aes(cty,hwy))+geom_point(alpha=1/3)+
xlab("city driving(mpg)")+ylab("highway driving(mpg)")

ggplot(mpg,aes(drv,hwy))+
geom_jitter(width=0.25,na.rm=T)+
xlim("f","r")+
ylim(NA,30)

ggplot(mpg,aes(drv,hwy))+
geom_jitter(width=0.25,na.rm=T)+
ylim(NA,30)

2.8 输出
p<-ggplot(mpg,aes(displ,hwy,colour=factor(cyl)))+
geom_point()
print(p)

- 保存
ggsave("plot.png",width=5,heigh=5)
2.9 快速绘图
qplot()
qplot(displ,hwy,data=mpg,colour="blue")

qplot(displ,hwy,data=mpg,colour=I("blue"))









