一行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::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
来改变几何形状,目前支持的有 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.ts
acf
,pacf
,ccf
spec.ar
,spec.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代码来实现繁琐的可视化的更多相关文章
- 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的的智能拐点时代).都基于算法及建模来 ...
随机推荐
- java设计模式之工厂方法探究
简单工厂 + 工厂方法 + 抽象工厂 看了十几篇博客,每篇基本上都能有个自己的解释,我汇总这些内容,重新梳理整理了一番,以形成自己的理解. 简单工厂模式其实不算23种设计模式之 ...
- idea使用心得(4)-踩过的坑
1.非法的表达式开始 / 需要';' / 未结束的字符串文字 表现形式: 原因/解决: 这个一定是文件编码问题:依次检查setting中的file Encodings 中的IDE ...
- RestTemplate配置
什么是RestTemplate? RestTemplate是Spring提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效 ...
- Object转数组
int length = Array.getLength(value);String[] newarray = new String[length];for (int i = 0; i < le ...
- uva 147 Dollars
http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&p ...
- 据库都有哪些锁 然后 Kill session
当某个数据库用户在数据库中插入.更新.删除一个表的数据,或者增加一个表的主键时或者表的索引时,常常会出现ora-00054:resource busy and acquire with nowait ...
- c#序列化json字符串及处理
上面提到的第四篇文章最后有个解析数组的例子,出现了 .First.First.First.First.Children(); 我表示很晕,网上找的的例子大多数是关于JObject的,但是我很少看到JA ...
- Uml学习-类图简介
类图(Class Diagram)简介 类图是面向对象分析(OOA,Object-Oriented Analysis)和面向对象设计(OOP,Object-Oriented Deisgn)思想的重要 ...
- 利用 Serial Over Lan(SOL)搭建 XEN 的调试信息输出环境
如有转载,请注明出处与本文连接,谢谢! 修改XEN的源码实现额外的功能,需要有一个调试环境来得到XEN的调试信息(有关源码编译并安装 XEN 请阅读我以前的博文:在CentOS下源码安装 Xen并搭建 ...
- [原创]Visual Studio 使用 Just My Code引起无法断点
今天遇到的问题,同样的代码,在一台机器上用Release配置可以命中断点,在另一台上用Release断点就都失效了.后来发现是因为断点失效的机器上设置了Just My Code.在Debug-Opti ...