ggfortify 有着简单易用的统一的界面来用一行代码来对许多受欢迎的R软件包结果进行二维可视化的一个R工具包。这让许多的统计学家以及数据科学家省去了许多繁琐和重复的过程,不用对结果进行任何处理就能以 {ggplot} 的风格画出好看的图,大大地提高了工作的效率。

虽然ggfortify已经在CRAN上,但是由于最近很多的功能都还在快速增加,还是推荐大家从Github上下载和安装

library(devtools)
install_github('sinhrks/ggfortify')
library(ggfortify)

接下来我将简单介绍一下怎么用 {ggplot2} 和 {ggfortify} 来很快的对PCA, clustering, 以及LFDA的结果进行可视化。然后将简单介绍用 {ggfortify} 来对时间序列进行迅速的可视化。

PCA (主成分分析)

{ggfortify} 使 {ggplot2} 知道怎么诠释PCA对象. 加载好 {ggfortify}包之后, 你可以对stats::prcomp 和 stats::princomp对象使用 ggplot2::autoplot

library(ggfortify)
df <- iris[c(1, 2, 3, 4)]
autoplot(prcomp(df))

转载于:http://terrytangyuan.github.io/2015/11/24/ggfortify-intro/

你还可以选择数据中的一列来给画出的点按类别自动分颜色。输入help(autoplot.prcomp) 可以了解到更多的其他选择。

autoplot(prcomp(df), data = iris, colour = 'Species')

比如说给定label = TRUE 可以给每个点加上标识(以rownames为标准),也可以调整标识的大小。

autoplot(prcomp(df), data = iris, colour = 'Species', label = TRUE, label.size = 3)

给定 shape = FALSE 可以让所有的点消失,只留下标识,这样可以让图更清晰,辨识度更大。

autoplot(prcomp(df), data = iris, colour = 'Species', shape = FALSE, label.size = 3)

给定 loadings = TRUE 可以很快的画出特征向量。

autoplot(prcomp(df), data = iris, colour = 'Species', loadings = TRUE)

同样的,你也可以显示特征向量的标识以及调整他们的大小,更多选择请参考帮助文件。

autoplot(prcomp(df), data = iris, colour = 'Species',
loadings = TRUE, loadings.colour = 'blue',
loadings.label = TRUE, loadings.label.size = 3)

因素分析

和PCA类似,ggfortify 也支持 stats::factanal 对象。可调的选择也很广泛。以下给出了简单的例子:

注意 当你使用 factanal 来计算分数的话,你必须给定 scores的值。

d.factanal <- factanal(state.x77, factors = 3, scores = 'regression')
autoplot(d.factanal, data = state.x77, colour = 'Income')

autoplot(d.factanal, label = TRUE, label.size = 3,
loadings = TRUE, loadings.label = TRUE, loadings.label.size = 3)

K-均值

autoplot(kmeans(USArrests, 3), data = USArrests)

autoplot(kmeans(USArrests, 3), data = USArrests, label = TRUE, label.size = 3)

cluster(集群)

{ggfortify} 也支持 cluster::claracluster::fannycluster::pam

library(cluster)
autoplot(clara(iris[-5], 3))

给定 frame = TRUE,可以把stats::kmeans 和 cluster::* 的每个集群圈出来。

autoplot(fanny(iris[-5], 3), frame = TRUE)

你也可以通过 frame.type 来选择圈的类型。更多选择请参照ggplot2::stat_ellipse里面的frame.typetype关键词。

autoplot(pam(iris[-5], 3), frame = TRUE, frame.type = 'norm')

lfda(Fisher局部判别分析)

{lfda}包支持一系列的Fisher局部判别分析方法,包括半监督lfda,非线性lfda。你也可以使用{ggfortify}来对他们的结果进行可视化。

library(lfda)

# Fisher局部判别分析 (LFDA)
model <- lfda(iris[-5], iris[, 5], 4, metric="plain")
autoplot(model, data = iris, frame = TRUE, frame.colour = 'Species')

# 半监督Fisher局部判别分析 (SELF)
model <- self(iris[-5], iris[, 5], beta = 0.1, r = 3, metric="plain")
autoplot(model, data = iris, frame = TRUE, frame.colour = 'Species')

更多关于集群方面的可视化请参考Github上的Vignette或者Rpubs上的例子。

时间序列的可视化

用 {ggfortify} 使时间序列的可视化变得及其简单。接下来我将给出一些简单的例子。

ts对象

library(ggfortify)
autoplot(AirPassengers)

可以使用 ts.colour 和 ts.linetype来改变线的颜色和形状。更多的选择请参考 help(autoplot.ts)

autoplot(AirPassengers, ts.colour = 'red', ts.linetype = 'dashed')

多变量时间序列

library(vars)
data(Canada)
autoplot(Canada)

使用 facets = FALSE 可以把所有变量画在一条轴上。

autoplot(Canada, facets = FALSE)

autoplot 也可以理解其他的时间序列类别。可支持的R包有:

  • zoo::zooreg
  • xts::xts
  • timeSeries::timSeries
  • tseries::irts

一些例子:

library(xts)
autoplot(as.xts(AirPassengers), ts.colour = 'green')

library(timeSeries)
autoplot(as.timeSeries(AirPassengers), ts.colour = ('dodgerblue3'))

你也可以通过 ts.geom 来改变几何形状,目前支持的有 linebar and point.

autoplot(AirPassengers, ts.geom = 'bar', fill = 'blue')

autoplot(AirPassengers, ts.geom = 'point', shape = 3)

forecast包

library(forecast)
d.arima <- auto.arima(AirPassengers)
d.forecast <- forecast(d.arima, level = c(95), h = 50)
autoplot(d.forecast)

有很多设置可供调整:

autoplot(d.forecast, ts.colour = 'firebrick1', predict.colour = 'red',
predict.linetype = 'dashed', conf.int = FALSE)

vars包

library(vars)
d.vselect <- VARselect(Canada, lag.max = 5, type = 'const')$selection[1]
d.var <- VAR(Canada, p = d.vselect, type = 'const')

更多可设置可供调整:

autoplot(predict(d.var, n.ahead = 50), ts.colour = 'dodgerblue4',
predict.colour = 'blue', predict.linetype = 'dashed')

changepoint包

library(changepoint)
autoplot(cpt.meanvar(AirPassengers))

autoplot(cpt.meanvar(AirPassengers), cpt.colour = 'blue', cpt.linetype = 'solid')

strucchange包

library(strucchange)
autoplot(breakpoints(Nile ~ 1), ts.colour = 'blue', ts.linetype = 'dashed',
cpt.colour = 'dodgerblue3', cpt.linetype = 'solid')

dlm包

library(dlm)
form <- function(theta){
dlmModPoly(order = 1, dV = exp(theta[1]), dW = exp(theta[2]))
} model <- form(dlmMLE(Nile, parm = c(1, 1), form)$par)
filtered <- dlmFilter(Nile, model) autoplot(filtered)

autoplot(filtered, ts.linetype = 'dashed', fitted.colour = 'blue')

smoothed <- dlmSmooth(filtered)
class(smoothed)
## [1] "list"
autoplot(smoothed)

p <- autoplot(filtered)
autoplot(smoothed, ts.colour = 'blue', p = p)

KFAS包

library(KFAS)
model <- SSModel(
Nile ~ SSMtrend(degree=1, Q=matrix(NA)), H=matrix(NA)
) fit <- fitSSM(model=model, inits=c(log(var(Nile)),log(var(Nile))), method="BFGS")
smoothed <- KFS(fit$model)
autoplot(smoothed)

使用 smoothing='none' 可以画出过滤后的结果。

filtered <- KFS(fit$model, filtering="mean", smoothing='none')
autoplot(filtered)

trend <- signal(smoothed, states="trend")
class(trend)
## [1] "list"
p <- autoplot(filtered)
autoplot(trend, ts.colour = 'blue', p = p)

stats包

可支持的stats包里的对象有:

  • stldecomposed.ts
  • acfpacfccf
  • spec.arspec.pgram
  • cpgram
autoplot(stl(AirPassengers, s.window = 'periodic'), ts.colour = 'blue')

autoplot(acf(AirPassengers, plot = FALSE))

autoplot(acf(AirPassengers, plot = FALSE), conf.int.fill = '#0000FF', conf.int.value = 0.8, conf.int.type = 'ma')

autoplot(spec.ar(AirPassengers, plot = FALSE))

ggcpgram(arima.sim(list(ar = c(0.7, -0.5)), n = 50))

library(forecast)
ggtsdiag(auto.arima(AirPassengers))

gglagplot(AirPassengers, lags = 4)

一行R代码来实现繁琐的可视化的更多相关文章

  1. R 代码积累

    R 代码积累不定期更新 1.阶乘.递归.reduce.sprintf #NO.1 # 阶乘函数 fact <- function(n){ if(n==0) return(1) #基例在这 els ...

  2. R代码展示各种统计学分布 | 生物信息学举例

    二项分布 | Binomial distribution 泊松分布 | Poisson Distribution 正态分布 | Normal Distribution | Gaussian distr ...

  3. (转)利用Auto ARIMA构建高性能时间序列模型(附Python和R代码)

    转自:  原文标题:Build High Performance Time Series Models using Auto ARIMA in Python and R 作者:AISHWARYA SI ...

  4. 高效完成R代码

    为什么R有时候运行慢? 参考https://www.cnblogs.com/qiaoyihang/p/7779144.html 一.为什么R程序有时候会很慢? 1.计算性能的三个限制条件 cpu ra ...

  5. 惊呆了!不改一行 Java 代码竟然就能轻松解决敏感信息加解密|原创

    前言 出于安全考虑,现需要将数据库的中敏感信息加密存储到数据库中,但是正常业务交互还是需要使用明文数据,所以查询返回我们还需要经过相应的解密才能返回给调用方. ps:日常开发中,我们要有一定的安全意识 ...

  6. 用数据说话,R语言有哪七种可视化应用?

    今天,随着数据量的不断增加,数据可视化成为将数字变成可用的信息的一个重要方式.R语言提供了一系列的已有函数和可调用的库,通过建立可视化的方式进行数据的呈现.在使用技术的方式实现可视化之前,我们可以先和 ...

  7. 神经网络模型及R代码实现

    神经网络基本原理 一.神经元模型 图中x1~xn是从其他神经元传来的输入信号,wij表示表示从神经元j到神经元i的连接权值,θ表示一个阈值 ( threshold ),或称为偏置( bias ).则神 ...

  8. 一行python代码实现树结构

    树结构是一种抽象数据类型,在计算机科学领域有着非常广泛的应用.一颗树可以简单的表示为根, 左子树, 右子树. 而左子树和右子树又可以有自己的子树.这似乎是一种比较复杂的数据结构,那么真的能像我们在标题 ...

  9. 建模分析之机器学习算法(附python&R代码)

    0序 随着移动互联和大数据的拓展越发觉得算法以及模型在设计和开发中的重要性.不管是现在接触比较多的安全产品还是大互联网公司经常提到的人工智能产品(甚至人类2045的的智能拐点时代).都基于算法及建模来 ...

随机推荐

  1. AFNetworking 2.0指北

    AFNetworking 2.0 来了 SEP 30TH, 2013 前几天 Mattt 发布了 AFNetworking 2.0,我的一个最大感慨就是,他怎么那么高产? 关于 Mattt Mattt ...

  2. vmware rdm

    RDM即裸磁盘映射,基本思想就是将host的磁盘直接映射给虚拟机使用   需要讨论的是: 1.rdm磁盘是否允许设置为共享,即可以映射给多个虚拟机使用(vmware不可用)   在 vSphere W ...

  3. mysql主键uuid、uuid_short和int自增对比

    数据库主键性能对比: 名称 存储长度 生成方式 1. uuid 32+4 uuid()函数 2. uuid20 20 UUID_SHORT()函数 3. bigint自增 20 auto_increm ...

  4. 使用intellij的svn时提示出错: Can't use Subversion command line client: svn.Errors found while svn working copies detection.

    使用Intellij的svn时提示出错:Can't use Subversion command line client: svn. Errors found while svn working co ...

  5. Netty NIO 框架性能压测-短链接-对比Tomcat

    压测方案 准备多个文件大小分别为 1k 10k 100k 300k 使用ab分别按 [50,2000](按50逐渐叠加)压测服务,每次请求10W次 硬件信息:CPU:Intel(R) Xeon(R) ...

  6. javascript数据结构和算法

    一.栈 javascript实现栈的数据结构(借助javascript数组原生的方法即可) //使用javascript来实现栈的数据结构 var Stack={ //不需要外界传参进行初始化,完全可 ...

  7. Python之路----------shutil模块

    高级的文件.文件夹.压缩包 处理模块 复制文件: import shutil f1 = open('test') f2 = open('test2','w') shutil.copyfileobj(f ...

  8. 配置Openfire的eclipse项目

    官方文档在这里 Install JDK Download JDK and install them. The least version should be 1.5. I use 1.6. Sorry ...

  9. Leetcode: Design Phone Directory

    Design a Phone Directory which supports the following operations: get: Provide a number which is not ...

  10. deep learning...深入学习深度学习 --工具篇

    Caffe( http://caffe.berkeleyvision.org/ )是一个清晰而高效的深度学习框架,其作者是博士毕业于UC Berkeley的贾扬清( http://daggerfs.c ...