ggplot2
1 ggplot2准备工作
ggplot2便是在上述图形语法的框架下应运而生。使用ggplot2之前需要先安装R软件,步骤如下。
#install.packages ("ggplot2")
library(ggplot2)
2 ggplot2基础绘图
本节选取Hadle Wickham的《ggplot2 Elegant Graphics for Data Analysis》第二章有关1999-2008年美国流行车耗油量的数据集(mpg)进行叙述。
- cty和hwy——城市和高速路行驶中的耗油量
- displ——排气量
- drv——动力传感系统
- model——车的模型,数据中包括38种
- class——车的类型,双人座、SUV、紧凑型等
每一个ggplot2图有三个关键组件: - 1. 数据 - 2. 数据变量和可见属性的图形映射 - 3. 至少一层描述如何表达可见性的图层。
2.1 散点图
ggplot (mpg, aes (x = displ, y = hwy)) +
geom_point()

- 数据:mpg
- 映射:displ映射至x轴,hwy映射至y轴
- 图层:用点显示数据
代码解析: 第一行用ggplot () 调入数据mpg,aes () 函数选择变量,并映射到x和y轴,第二行代码利用函数geom_point () 将数据表现为黑色圆点。从中可以看出ggplot2代码简洁,易懂易学。
2.2 散点图-添加拟合曲线
ggplot(mpg, aes(displ, hwy)) +
geom_point() +
geom_smooth(method= "lm")

最后一行代码表示在新的图层添加拟合曲线,代码之间使用了符号“+”。一幅图形背后的设计是若干图形语法的叠加,外在的表现是若干R对象的相加。ggplot2对加号的扩展,可以说是神来之笔。
2.3 散点图-着色
ggplot(mpg, aes (displ, hwy, colour=class)) +
geom_point()

图形属性包括颜色、形状和大小等,在aes () 函数中将某一变量设置为颜色属性,即可对属于不同变量的数据分开着色。
2.4 散点图-分面
ggplot(mpg, aes(displ, hwy)) +
geom_point() +
facet_wrap(~class)

ggplot2分面的目的是对数据子集单独绘图,观察子集之间数据的规律。
2.5 箱式图
ggplot(mpg, aes(drv, hwy)) + geom_jitter()

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

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

三行代码对应三幅图,如果用“+“把上述代码合并,三张图即可叠加,即ggplot2以图层的模式,构建不同类型的统计图形。
ggplot(mpg, aes(drv, hwy)) + geom_jitter() + geom_boxplot() + geom_violin()

2.6 直方图和频率多边形
ggplot(mpg, aes(hwy)) + geom_histogram()
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. 4个空格代表代码引用(有框无背景填充)
ggplot(mpg, aes(hwy)) + geom_freqpoly()
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
2.7 柱状图
ggplot(mpg, aes(manufacturer)) + geom_bar()

2.8 时间序列图
# 此处message决定是否显示执行提示信息,warning 决定是否显示警告信息
ggplot(economics, aes(date, unemploy / pop)) + geom_line()

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

2.9 路径图
ggplot(economics, aes(unemploy / pop, uempmed)) +
geom_path() +
geom_point()

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

选择aes () 函数,对连续的时间进行变量着色。
2.10 ggplot2其它统计图
除了散点图、条形图等之外,ggplot2有更广泛的应用。
曲面图
ggplot(faithfuld, aes(eruptions, waiting)) +
geom_contour(aes(z = density, colour = ..level..))

ggplot(faithfuld, aes(eruptions, waiting)) +
geom_raster(aes(fill = density))

3 透明度设置
大量数据点覆盖堆积,将会掩盖数据趋势,可设置透明度加以区分。
# 此处 echo=TRUE 只显示代码,不执行,不显示结果
norm <- ggplot(df, aes(x, y)) + xlab(NULL) + ylab(NULL)
norm + geom_point (alpha = 1 / 3)
norm + geom_point (alpha = 1 / 5)
norm + geom_point (alpha = 1 / 10)
4 主题设置
ggplot2提供了大量主题设置,利用theme () 函数,快速转换。例如左上图分别添加一行代码,便可得到其它类型的主题。
theme_classic()
theme_minimal()
theme_economist()+ scale_colour_economist()
ggplot2更新很快,拥有大量函数,以实现多种统计图的绘制。
5 无代码绘制ggplot2图
尽管ggplot2代码简洁,在不熟悉的前提下,依然会出现许多Bug,为此Keon-Woong Moon编写了Learn ggplot2 Shiny App,将代码的编写转化为图形模块的点击。
http://r-graph.com/
从主页中选择最近的服务器地址,即可打开在线ggplot2绘图网页。
加载数据后,用鼠标选择对应的变量,勾选需要绘制的统计图,即可一键出图。
页面左下方会显示相应的R代码,可以作为学习代码的教程。
ggplot(data=acs,aes(x=Dx,y=age,fill=Dx))+
geom_point(position='jitter',size=0.3)+
geom_violin()+
geom_boxplot(fill='white',width=0.05,outlier.shape=1,outlier.size=16)+
stat_summary(geom='point',fun.y=mean,shape=23,size=3)+
theme(legend.position='none')
- Line 1:将变量数据映射到坐标系
- Line 2:添加散点图
- Line 3:添加小提琴图
- Line 4:添加箱式图
- Line 5:添加平均值
- Line 6:隐藏图例
Shiny App菜单栏的MultiPlot可实现上述4种图形依次保存和排列的功能,并快速输出。
6 ggplot2的扩展包
leave 4 spaces can make this style.
animlnt:制作交互图形,增加询问,筛选链接等
ggthemes:提供扩展的图形风格主题
ggmap:提供在线地图服务模块
ggiraph:绘制交互式的ggplot图形
ggstance:实现常见图形的横向版本
GGally:绘制散点图矩阵
ggalt:添加额外的坐标轴、geoms等
ggforce:添加额外geoms等
ggrepel:避免图形标签重叠
ggraph:绘制网络状、树状等特定形状的图形
ggpmisc:光生物学相关扩展
ggbio:提供基因组学数据图形
geomnet:绘制网络状图形
ggExtra:绘制图形的边界直方图
gganimate:绘制动画图
plotROC:绘制交互式ROC曲线图
ggspectra:绘制光谱图
ggnetwork:网络状图形的geoms
ggradar:绘制雷达图
ggTimeSeries:时间序列数据可视化
ggtree:树图可视化
ggtern:绘制三元图
ggseas:季节调整工具
ggenealogy:浏览和展示系谱学数据
6.1 GGally
尽管ggplot2默认条件下即可输出精美的图,但是其核心的图形语法并未限制于常规的统计图形,也未指定图形的外观,这极大地扩展了ggplot2绘图的范围和可能达到的极致美观。
sessionInfo()
## R version 3.5.1 (2018-07-02)
## Platform: x86_64-w64-mingw32/x64 (64-bit)
## Running under: Windows 10 x64 (build 17134)
##
## Matrix products: default
##
## locale:
## [1] LC_COLLATE=Chinese (Simplified)_China.936
## [2] LC_CTYPE=Chinese (Simplified)_China.936
## [3] LC_MONETARY=Chinese (Simplified)_China.936
## [4] LC_NUMERIC=C
## [5] LC_TIME=Chinese (Simplified)_China.936
##
## attached base packages:
## [1] stats graphics grDevices utils datasets methods base
##
## other attached packages:
## [1] ggplot2_3.1.0
##
## loaded via a namespace (and not attached):
## [1] Rcpp_1.0.0 bindr_0.1.1 knitr_1.20 magrittr_1.5
## [5] tidyselect_0.2.5 munsell_0.5.0 colorspace_1.3-2 R6_2.3.0
## [9] rlang_0.3.0.1 stringr_1.3.1 plyr_1.8.4 dplyr_0.7.8
## [13] tools_3.5.1 grid_3.5.1 gtable_0.2.0 withr_2.1.2
## [17] htmltools_0.3.6 assertthat_0.2.0 yaml_2.2.0 lazyeval_0.2.1
## [21] rprojroot_1.3-2 digest_0.6.18 tibble_1.4.2 crayon_1.3.4
## [25] bindrcpp_0.2.2 purrr_0.2.5 glue_1.3.0 evaluate_0.12
## [29] rmarkdown_1.10 labeling_0.3 stringi_1.2.4 compiler_3.5.1
## [33] pillar_1.3.0 scales_1.0.0 backports_1.1.2 pkgconfig_2.0.2