一行R代码来实现繁琐的可视化
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::clara, cluster::fanny, cluster::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.type的type关键词。
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')
时间序列的可视化
用 {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::zooregxts::xtstimeSeries::timSeriestseries::irts
一些例子:
library(xts)
autoplot(as.xts(AirPassengers), ts.colour = 'green')
library(timeSeries)
autoplot(as.timeSeries(AirPassengers), ts.colour = ('dodgerblue3'))
你也可以通过 ts.geom 来改变几何形状,目前支持的有 line, bar 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包里的对象有:
stl,decomposed.tsacf,pacf,ccfspec.ar,spec.pgramcpgram
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代码来实现繁琐的可视化的更多相关文章
- R 代码积累
R 代码积累不定期更新 1.阶乘.递归.reduce.sprintf #NO.1 # 阶乘函数 fact <- function(n){ if(n==0) return(1) #基例在这 els ...
- R代码展示各种统计学分布 | 生物信息学举例
二项分布 | Binomial distribution 泊松分布 | Poisson Distribution 正态分布 | Normal Distribution | Gaussian distr ...
- (转)利用Auto ARIMA构建高性能时间序列模型(附Python和R代码)
转自: 原文标题:Build High Performance Time Series Models using Auto ARIMA in Python and R 作者:AISHWARYA SI ...
- 高效完成R代码
为什么R有时候运行慢? 参考https://www.cnblogs.com/qiaoyihang/p/7779144.html 一.为什么R程序有时候会很慢? 1.计算性能的三个限制条件 cpu ra ...
- 惊呆了!不改一行 Java 代码竟然就能轻松解决敏感信息加解密|原创
前言 出于安全考虑,现需要将数据库的中敏感信息加密存储到数据库中,但是正常业务交互还是需要使用明文数据,所以查询返回我们还需要经过相应的解密才能返回给调用方. ps:日常开发中,我们要有一定的安全意识 ...
- 用数据说话,R语言有哪七种可视化应用?
今天,随着数据量的不断增加,数据可视化成为将数字变成可用的信息的一个重要方式.R语言提供了一系列的已有函数和可调用的库,通过建立可视化的方式进行数据的呈现.在使用技术的方式实现可视化之前,我们可以先和 ...
- 神经网络模型及R代码实现
神经网络基本原理 一.神经元模型 图中x1~xn是从其他神经元传来的输入信号,wij表示表示从神经元j到神经元i的连接权值,θ表示一个阈值 ( threshold ),或称为偏置( bias ).则神 ...
- 一行python代码实现树结构
树结构是一种抽象数据类型,在计算机科学领域有着非常广泛的应用.一颗树可以简单的表示为根, 左子树, 右子树. 而左子树和右子树又可以有自己的子树.这似乎是一种比较复杂的数据结构,那么真的能像我们在标题 ...
- 建模分析之机器学习算法(附python&R代码)
0序 随着移动互联和大数据的拓展越发觉得算法以及模型在设计和开发中的重要性.不管是现在接触比较多的安全产品还是大互联网公司经常提到的人工智能产品(甚至人类2045的的智能拐点时代).都基于算法及建模来 ...
随机推荐
- php+mysql+Apache环境搭建
最近有一个小程序需要用php来跑,记录一下php的环境配置过程. 1.首先在下载集成工具wamp,WAMP是指在Windows服务器上使用Apache.MySQL和PHP的集成安装环境,可以快速安装配 ...
- iOS webView与H5的交互(返回页面的处理)
摘自:http://blog.csdn.net/qq_29284809/article/details/50548413 调用 H5页面的同名返回方法(必须保证名字一致)!!!
- 使用MaskFilter
使用MaskFilter MaskFilter类可以为Paint分配边缘效果. 对MaskFilter的扩展可以对一个Paint边缘的alpha通道应用转换.Android包含了下面几种MaskFil ...
- python脚本生成exe可执行文件
1.先安装第三方插件: py2exe. Get py2exe from http://www.py2exe.org/ 在download里下载与自己python对应的版本 2.写一个测试python文 ...
- Ubuntu Kylin 14.04下配置JDK1.8
1.源码包准备: 首先到官网下载jdk,http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.h ...
- postgresql修炼之道学习笔记(2)
随后的章节 介绍了基础的sql,这个我略过了,我喜欢在开发的时候,慢慢的研究,毕竟有oracle的基础. 现在,学习psql工具 使用create database创建数据库的时候,出现如下问题: ...
- SpringMVC整合Hibernate实现增删改查之按条件查询
首先我贴出我项目的结构,只完成了条件查询的相关代码,增删改没有写. 1.新建一个动态Web工程,导入相应jar包,编写web.xml配置文件 <context-param> <par ...
- Easy Tag Write(2)
package skyseraph.android.util.nfc; import com.google.common.collect.BiMap; import com.google.common ...
- jQuery File Upload done函数没有返回
最近在使用jQuery File Upload 上传图片时发现一个问题,发现done函数没有callback,经过一番折腾,找到问题原因,是由于dataType: ‘json’造成的,改为autoUp ...
- docker 介绍
docker 介绍 安装 sudo apt-get install docker.io sudo docker info 查看是否安装成功 hello world sodu docker run he ...