r语言ggbio包使用方法

Python09

r语言ggbio包使用方法,第1张

第一步:获取要绘图的整洁数据(涉及到数据整洁和操作的知识)

第二步:整洁数据做映射操作,确定x,y,color,size,shape,alpha等

第三步:选择合适的几何对象(根据画图的目的、变量的类型和个数)

第四步:坐标系和刻度配置

第五步:标签信息和图例信息

第六步:选择合适的主题

ggplot2的语法包括10个部件。

数据(data)

映射(mapping)

几何对象(geom)

标度(scale)

统计变换(stats)

坐标系(coord)

位置调整(Position adjustments)

分面(facet)

主题(theme)

输出(output)

前3个是必须的,其它部件ggplot2会自动配置,也可以手动配置

ggplot2基本绘图模板:

注意:

1)添加图层的加号(+)只能放在行末尾

2)红色方框里面mapping是全局域,绿色方框里面mapping是局部域,执行先后顺序,先局部域,后全局域

ggplot2画图必要部件-数据,映射和几何对象

2.1 数据

数据(Data)用于画图的整洁数据

library(tidyverse

ggplot()先只提供数据,创建一个空图形。

# ggplot()先提供整洁数据,生成一个空图形

2映射

映射,把数据变量集与图形属性库建立关联。

最常用的映射有:

x:x轴

y:y轴

color:颜色

size:大小

shape:形状

fill:填充

alpha:透明度

以mpg数据集为例,把变量displ和hwy分别映射到x和y,变量drv映射到color,此时图形就有了坐标轴和网格线,color需要在有了几何对象后才能体现出来。

# 映射操作

ggplot(data = mpg, mapping = aes(x = displ,

y = hwy, color = drv))

2.3 几何对象

几何对象是表达数据的视觉对象

不同类型的几何对象是从不同的角度表达数据。

pgglot2提供了50多种“几何对象”,均以geom_xxxx()的方式命名,常用的有:

几何对象很简单,只需要添加图层即可。

例如,以mpg数据集为例,画散点图。

ggplot(data = mpg, mapping = aes(x = displ,

y = hwy,

color = drv)) +

geom_point()层依次叠加,在上图的基础上,再添加一个几何对象:光滑曲线。

#继续增加一个几何对象:光滑曲线

# 写法1

ggplot(data = mpg, mapping = aes(x = displ,

y = hwy,

color = drv)) +

geom_point() +

geom_smooth(se=FALSE)

# 写法2

ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +

geom_point(aes(color = drv)) +

geom_smooth(se=FALSE)

思考题:

1)写法1和写法2的差异?(全局域和局部域的使用差异)

2)写法2若是要实现写法1的功能,怎么编写代码?

03

标度

ggplot2会自动根据输入变量选择最优的坐标刻度方法,若要手动设置或调整,就需要使用标度函数

标度函数用来控制几何对象中的标度映射(x轴,y轴或者由color,fill,shape,size产生的图例)。

ggplot2提供丰富的标度函数,常用的有:

拓展功能:scales包提供很多设置刻度标签风格的函数,比如百分数、科学计数法法、美元格式等。

3.1 修改坐标轴刻度及标签

连续变量使用scale_*_continuous()函数,参数breaks设置各个刻度的位置,参数labels设置各个刻度对应的标签。

离散变量使用scale_*_discrete()函数,修改离散变量坐标轴的标签。

时间变量使用scale_x_date()函数设置日期刻度,参数date_breaks设置刻度间隔,date_labels设置标签的日期格式

以mpg数据集为例,修改连续变量坐标轴刻度及标签。

# scale_y_continuous函数

# 对比分析和观察

# 图1

ggplot(mpg, aes(displ, hwy)) +

geom_point()

# 图2

ggplot(mpg, aes(displ, hwy)) +

geom_point() +

scale_y_continuous(breaks = seq(15, 40, by = 10))

# 图3

ggplot(mpg, aes(displ, hwy)) +

geom_point() +

scale_y_continuous(breaks = seq(15, 40, by = 10),

labels = c(" 一五 "," 二五 "," 三五 "))

以mpg数据集为例,修改离散变量的标签

# scale_x_discrete函数

# 对比分析和观察

# 图1

ggplot(mpg, aes(x = drv)) +

geom_bar()

# 图2

ggplot(mpg, aes(x = drv)) +

geom_bar() +

scale_x_discrete(labels = c("4" = " 四驱 ", "f" = " 前驱 ",

"r" = " 后驱 "))

以ggplot2自带的economics数据集为例,修改日期变量。

# scale_x_date函数

# 以ggplot2自带的economics为例

economics %>% glimpse()

# 图1

ggplot(tail(economics, 45), aes(date, uempmed / 100)) +

geom_line()

# 图2

ggplot(tail(economics, 45), aes(date, uempmed / 100)) +

geom_line() +

scale_x_date(date_breaks = "6 months", date_labels = "%Y-%b") +

scale_y_continuous(labels = scales::percent)

3.2 修改坐标轴标签、图例名及图例位置

用labs()函数参数x,y或者xlab(),ylab(),设置x轴,y轴标签。

若用参数color生成了图例,可以在labs()函数用参数color修改图例名。

用theme图层的参数legend.position设置图例的位置。

以mpg数据为例。

# 修改坐标轴标签,图例名和图例位置

mpg

# 图1

ggplot(mpg, aes(displ, hwy)) +

geom_point(aes(color = drv)) +

labs(x = " 引擎大小 (L)", y = " 高速燃油率 (mpg)",

color = " 驱动类型 ") +

theme(legend.position = "top")

# 图2

ggplot(mpg, aes(displ, hwy)) +

geom_point(aes(color = drv)) +

xlab(" 引擎大小 (L)") +

ylab(" 高速燃油率 (mpg)") +

labs(color = " 驱动类型 ") +

theme(legend.position = "top")

# 图3 不需要图例

ggplot(mpg, aes(displ, hwy)) +

geom_point(aes(color = drv)) +

xlab(" 引擎大小 (L)") +

ylab(" 高速燃油率 (mpg)") +

theme(legend.position = "none")

3.3 设置坐标轴的范围

用coord_cartesian()函数参数xlim和ylim,或者用xlim(),ylim()设置x轴和y轴的范围。

以mpg数据集为例。

# 修改坐标轴的范围

# 图1 coord_cartesian()的参数xlim和ylim

ggplot(mpg, aes(displ, hwy)) +

geom_point(aes(color = drv)) +

coord_cartesian(xlim = c(5, 7), ylim = c(10, 30))

# 图2 xlim()和ylim()函数

ggplot(mpg, aes(displ, hwy)) +

geom_point(aes(color = drv)) +

xlim(5, 7) +

ylim(10, 30)

3.4 变换坐标轴

用scale_x_log10()函数变换坐标系,可以保持原始数据的坐标刻度。

# 修改坐标轴的范围

# 图1 coord_cartesian()的参数xlim和ylim

ggplot(mpg, aes(displ, hwy)) +

geom_point(aes(color = drv)) +

coord_cartesian(xlim = c(5, 7), ylim = c(10, 30))

# 图2 xlim()和ylim()函数

ggplot(mpg, aes(displ, hwy)) +

geom_point(aes(color = drv)) +

xlim(5, 7) +

ylim(10, 30)

3.5 设置图形标题

用labs()函数设置图形标题。

参数title 设置正标题

参数subtitle 设置副标题

参数caption 设置脚注标题(默认右下角)

# 设置标题

# mpg数据集为例

p <- ggplot(mpg, aes(displ, hwy)) +

geom_point(aes(color = drv)) +

geom_smooth(se = FALSE) +

labs(title = " 燃油效率与引擎大小的关系图 ",

subtitle = " 两座车 ( 跑车 ) 因重量小而符合预期 ",

caption = " 数据来自 fueleconomy.gov")

p

标题若要居中,采用theme图层设置。

p + theme(plot.title = element_text(hjust = 0.5),

plot.subtitle = element_text(hjust = 0.5))

3.6 设置color、fill颜色

数据的某个维度信息可以通过颜色来表示。

可以直接使用颜色值,建议使用RColorBrewer(调色板)或者colorspace包。

1)连续变量

- 用scale_color_gradient()设置二色渐变色。

# 连续变量

# 图1 scale_color_gradient()函数

ggplot(mpg, aes(displ, hwy, color = hwy)) +

geom_point() +

scale_color_gradient(low = "green", high = "red")

- 用scale_color_distiller()设置调色板中的颜色

# 图2 scale_color_distiller()函数

ggplot(mpg, aes(displ, hwy, color = hwy)) +

geom_point() +

scale_color_distiller(palette = "Set1")

2)离散变量

- 用scale_color_manual()手动设置颜色,还可以修改图例及其标签信息

# 离散变量

# 图1 scale_color_manual()函数

ggplot(mpg, aes(displ, hwy, color = drv)) +

geom_point() +

scale_color_manual(" 驱动方式 ",

values = c("red", "blue", "green"),

breaks = c("4", "f", "r"))

ggplot(mpg, aes(displ, hwy, color = drv)) +

geom_point() +

scale_color_manual(" 驱动方式 ",

values = c("red", "blue", "green"),

labels = c(" 四驱 ", " 前驱 ", " 后驱 "))

-用scale_fill_brewer()调用调色板中的颜色

# 图2 scale_fill_brewer()函数

ggplot(mpg, aes(x = class, fill = class)) +

geom_bar() +

scale_fill_brewer(palette = "Dark2")

.7 添加文字标注

ggrepel包提供了geom_label_repel()函数或者geom_text_repel()函数,为图形添加文字标注。

操作步骤:

第一步:先准备好标记点的数据

第二步:增加文字标注图层,包括标记点的数据和标注的文字给label参数

# 设置文字标注信息

library(ggrepel)

# 选取每种车型 hwy 值最大的样本

best_in_class <- mpg %>%

group_by(class) %>%

slice_max(hwy, n = 1)

best_in_class %>% select(class, model, hwy)

ggplot(mpg, aes(displ, hwy)) +

geom_point(aes(color = class)) +

geom_label_repel(data = best_in_class,

aes(label = model))

04

计变换、坐标系和位置调整

.1 统计变换

统计变换是构建新的统计量而画图。

例如,条形图或直方图,是对数据分组的频数做画图;平滑曲线是对数据拟合模型的预测值画图。

gplot2可以把统计变换直接融入画图中,不必先在对数据做统计变换后再画图。

gplot2提供30多种统计,均以stats_xxx()的方式命名。

1)可在几何对象中直接使用的统计变换,直接使用几何对象就可以了。

能在几何对象创建的,而需要单独使用。

mpg数据集为例。

stat_summary()做统计绘图并汇总。

# 图1 stat_summary()做统计绘图并汇总

p <- ggplot(mpg, aes(x = class, y = hwy)) +

geom_violin(trim = FALSE, alpha = 0.5, color = "green")

p

p + stat_summary(fun = mean,

fun.min = function (x) {mean(x) - sd(x)},

fun.max = function (x) {mean(x) + sd(x)},

geom = "pointrange",

color = "red")

tat_smooth()添加光滑曲线,与geom_smooth()相同。

参数method设置平滑曲线的拟合方法,如lm线性回归、glm广义线性回归、loess多项式回归、gam广义加法模型(mgcv包)、rlm稳健回归(MASS包)等。

参数formula指定平滑曲线方程,如y ~ x, y ~ poly(x, 2), y ~ log(x)等。

参数se设置是否绘制置信区间。

# 图2 stat_smooth()添加平滑曲线

ggplot(mpg, aes(displ, hwy)) +

geom_point() +

stat_smooth(method = "lm",

formula = y ~ splines::bs(x, 3),

se = FALSE)

ggplot(mpg, aes(displ, hwy)) +

geom_point() +

geom_smooth(method = "lm",

formula = y ~ splines::bs(x, 3),

se = FALSE)

4.2 坐标系

ggplot2默认是直角坐标系。

- coord_cartesian()

常用的其它坐标系:

以mpg数据集为例,坐标轴翻转。

# 图1 坐标轴翻转coord_flip()

p <- ggplot(mpg, aes(class, hwy)) +

geom_boxplot()

p

p + coord_flip()

直角坐标下条形图转换为极坐标下玫瑰图。

# 图2 直角坐标条形图-->极坐标玫瑰图

p <- ggplot(mpg, aes(class, fill = drv)) +

geom_bar()

p

p + coord_polar()

4.3 位置调整

条形图的位置调整

# 图1:条形图条形位置调整

ggplot(mpg, aes(class, fill = drv)) +

geom_bar()

ggplot(mpg, aes(class, fill = drv)) +

geom_bar(position = "dodge")

ggplot(mpg, aes(class, fill = drv)) +

geom_bar(position = position_dodge(preserve = "single"))

散点图的散点位置调整

# 图1:散点图的散点位置调整

ggplot(mpg, aes(displ, hwy)) +

geom_point()

ggplot(mpg, aes(displ, hwy)) +

geom_point(position = "jitter")

用patchwork包排布多个图形

library(patchwork)

p1 <- ggplot(mpg, aes(displ, hwy)) +

geom_point()

p2 <- ggplot(mpg, aes(drv, displ)) +

geom_boxplot()

p3 <- ggplot(mpg, aes(drv)) +

geom_bar()

p1 | (p2 / p3)

p1 | p2 | p3

p1 / p2 / p3

p1 / (p2 | p3)

05

分面

利用分类变量把图形分成若干“子图”(面),实际上就是对数据分组后再画图,属于数据分析里面细分和下钻的思想。

5.1 用facet_wrap()函数

封装分面,先生成一维的面板系列,再封装到二维中。

语法形式:~ 分类变量 或者 ~ 分类变量1 + 分类变量2

参数scales设置是否共用坐标刻度,fixed 默认 共用, free 不共用,还可以额通过free_x,free_y单独设置。

以下为该包的帮助文件内容

Dynamic nomogram to visualise statistical models

Description

DynNom is a generic function to display the results of statistical model objects as a dynamic nomogram in an 'RStudio' panel or web browser. DynNom supports a large number of model objects from a variety of packages.

Usage

DynNom(model, data = NULL, clevel = 0.95, m.summary = c("raw", "formatted"),

covariate = c("slider", "numeric"), ptype = c("st", "1-st"),

DNtitle = NULL, DNxlab = NULL, DNylab = NULL, DNlimits = NULL,

KMtitle = NULL, KMxlab = NULL, KMylab = NULL)

DynNom.core(model, data, clevel, m.summary, covariate, DNtitle, DNxlab, DNylab, DNlimits)

DynNom.surv(model, data, clevel, m.summary, covariate,

ptype, DNtitle, DNxlab, DNylab, KMtitle, KMxlab, KMylab)

Arguments

model

an lm, glm, coxph, ols, Glm, lrm, cph, mgcv::gam or gam::gam model objects.

data

a dataframe of the accompanying dataset for the model (if required).

clevel

a confidence level for constructing the confidence interval. If not specified, a 95% level will be used.

m.summary

an option to choose the type of the model output represented in the 'Summary Model' tab. "raw" (the default) returns an unformatted summary of the model"formatted" returns a formatted table of the model summary using stargazer package.

covariate

an option to choose the type of input control widgets used for numeric values. "slider" (the default) picks out sliderInput"numeric" picks out numericInput.

ptype

an option for coxph or cph model objects to choose the type of plot which displays in "Survival plot" tab. "st" (the default) returns plot of estimated survivor probability (S(t)). "1-st" returns plot of estimated failure probability (1-S(t)).

DNtitle

a character vector used as the app's title. If not specified, "Dynamic Nomogram" will be used.

DNxlab

a character vector used as the title for the x-axis in "Graphical Summary" tab. If not specified, "Probability" will be used for logistic model and Cox proportional model objectsor "Response variable" for other model objects.

DNylab

a character vector used as the title for the y-axis in "Graphical Summary" tab (default is NULL).

DNlimits

a vector of 2 numeric values used to set x-axis limits in "Graphical Summary" tab. Note: This also removes the 'Set x-axis ranges' widget in the sidebar panel.

KMtitle

a character vector used as KM plot's title in "Survival plot" tab. If not specified, "Estimated Survival Probability" for ptype = "st" and "Estimated Probability" for ptype = "1-st" will be used.

KMxlab

a character vector used as the title for the x-axis in "Survival plot" tab. If not specified, "Follow Up Time" will be used.

KMylab

a character vector used as the title for the y-axis in "Survival plot" tab. If not specified, "S(t)" for ptype = "st" and "F(t)" for ptype = "1-st" will be used.

Value

A dynamic nomogram in a shiny application providing individual predictions which can be used as a model visualisation or decision-making tools.

The individual predictions with a relative confidence interval are calculated using the predict function, displaying either graphically as an interactive plot in the Graphical Summary tab or a table in the Numerical Summary tab. A table of model output is also available in the Model Summary tab. In the case of the Cox proportional hazards model, an estimated survivor/failure function will be additionally displayed in a new tab.

Please cite as:

Jalali, A., Roshan, D., Alvarez-Iglesias, A., Newell, J. (2019). Visualising statistical models using dynamic nomograms. R package version 5.0.

Author(s)

Amirhossein Jalali, Davood Roshan, Alberto Alvarez-Iglesias, John Newell

Maintainer: Amirhossein Jalali [email protected]

References

Banks, J. 2006. Nomograms. Encyclopedia of Statistical Sciences. 8.

Easy web applications in R. http://shiny.rstudio.com

Frank E Harrell Jr (2017). rms: Regression Modeling Strategies. R package version 4.5-0. https://CRAN.R-project.org/package=rms

See Also

DNbuilder, getpred.DN

1. 列出包所在库的路径

.libPaths()

[1] "C:/Program Files/R/R-3.0.2/library"

2. 安装包,括号里面包的名称要加英文引号,在列出的CRAN镜像站点列表中选择一个进行下载,我一般选的是China(Hefei)

install.packages()

例如,install.packages("ggplot2")

3. 包的载入library()或require(),安装完包后,需要加载才能使用其中的函数,此时括号中不使用引号。两者的不同之处在于library()载入之后不返回任何信息,而require()载入后则会返回TRUE,因此require()适合用于程序的书写。

例如

library(ggplto2)

>require(foreign)

Loading required package: foreign

>is.logical(require(foreign))

[1] TRUE

4. 包的更新

update.packages()

5. 包的帮助信息 格式如下,可以查看包中的函数以及说明

help(package="ggplot2")

6. 查看本地的包

6.1 查看默认加载的包,忽略基本的包

getOption("defaultPackages")

>getOption("defaultPackages")

[1] "datasets" "utils" "grDevices" "graphics" "stats" "methods"

[7] "ggplot2"

6.2 查看当前已经加载过的包

(.packages())

[1] "ggplot2" "stats" "graphics" "grDevices" "utils" "datasets" "methods" "base"

6.3 要显示所有可用的包

(.packages(all.available=TRUE))

>(.packages(all.available=TRUE))

[1] "abind" "agricolae" "aplpack" "base" "bitops"

[6] "boot" "car" "caTools" "class" "cluster"

[11] "codetools" "colorRamps" "colorspace" "compiler" "datasets"

[16] "Defaults" "devtools" "dichromat" "digest" "doBy"

[21] "e1071" "effects" "ellipse" "evaluate" "foreign"

[26] "formatR" "Formula" "gdata" "ggplot2" "ggthemes"

[31] "gmodels" "gplots" "graphics" "grDevices" "grid"

[36] "gtable" "gtools" "highr" "Hmisc" "httr"

[41] "KernSmooth" "knitr" "labeling" "lattice" "latticeExtra"

[46] "leaps" "lme4" "lmtest" "LSD" "manipulate"

[51] "markdown" "MASS" "Matrix" "matrixcalc" "memoise"

[56] "methods" "mgcv" "minqa" "multcomp" "munsell"

[61] "mvtnorm" "nlme" "nnet" "nortest" "parallel"

[66] "pixmap" "plyr" "proto" "psych" "quantmod"

[71] "Rcmdr" "RColorBrewer" "Rcpp" "RcppEigen" "RCurl"

[76] "relimp" "reshape2" "rgl" "rJava" "RODBC"

[81] "rpart" "rstudio" "samplesize" "sandwich" "scales"

[86] "schoolmath" "sciplot" "sem" "spatial" "splines"

[91] "stats" "stats4" "stringr" "survival" "tcltk"

[96] "tcltk2" "TH.data" "tools" "TTR" "utils"

[101] "VennDiagram" "whisker" "XLConnect" "xts" "zoo"

7. 卸载包detach(),这是library()的反向操作,此操作主要是为了避免某些包中的函数名称相同,造成冲突,注意与library()的参数不同,detach()参数为detach(package:包的名称),library(包的名称)。

例如

>library(ggplot2) #加载包

>(.packages()) #列出当前已经加载的包

[1] "ggplot2" "stats" "graphics" "grDevices" "utils" "datasets"

[7] "methods" "base"

>detach(package:ggplot2) # 卸载ggplot2包

>(.packages()) #列出当前已经加载的包

[1] "stats" "graphics" "grDevices" "utils" "datasets" "methods"

[7] "base"

8. 自定义启动时候的加载包

如果需要长期使用某个包的话,每次开启都需要输入library(),比较麻烦,因此可以让R启动时自动加载某些包。在R的安装目录/etc/Rprofile.site加入下载语句:

例如让R启动时自动加载ggplot2包

local({old <- getOption("defaultPackages")

options(defaultPackages = c(old, "ggplot2"))})

9. 在文章中引用R软件包,例如引用ggplot2包:

citation(package="ggplot2")

To cite ggplot2 in publications, please use:

H. Wickham. ggplot2: elegant graphics for data analysis. Springer New

York, 2009.

A BibTeX entry for LaTeX users is

@Book{,

author = {Hadley Wickham},

title = {ggplot2: elegant graphics for data analysis},

publisher = {Springer New York},

year = {2009},

isbn = {978-0-387-98140-6},

url = {http://had.co.nz/ggplot2/book},

}