一行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的的智能拐点时代).都基于算法及建模来 ...
随机推荐
- 【待整理】MongoDB 数据集
MongoDB复制集原理 https://yq.aliyun.com/articles/64?spm=5176.100239.blogcont14692.15.XzCCrj MongoDB管理:如何优 ...
- 实现一个小目标,动动小指,分享可得iphone7/ipad/U盘|奥威软件
为什么很多人喜欢冬天呢?是因为冬天有着“床边挂起长长棉袜,而你做着甜甜美梦”的平安夜?还是因为冬天有着“具有无法言述的浪漫情怀”的圣诞节? 是不是还沉浸在平安夜,圣诞节的双节狂欢中, 好像不管长到多大 ...
- css给div添加0.5px的边框
具体代码实现如下: <!DOCTYPE html> <html lang="en"> <head> <meta charset=" ...
- Prototype based langue LUA
Prototype-based programming https://en.wikipedia.org/wiki/Prototype-based_programming Prototype-base ...
- lua自定义迭代器
迭代器 http://www.tutorialspoint.com/lua/lua_iterators.htm 迭代器能够让你遍历某个集合或者容器中的每一个元素. 对于lua来说, 集合通常指代 ta ...
- zstack 离线升级1.1到 1.2 rc
说明 zstack版本1.1是通过离线安装的. 升级过程 1 挂载下一个版本的zstack的社区版本centos镜像 ZStack-Community-x86_64-DVD-1.2.0.iso mkd ...
- C语言第7次作业
1 #include<stdio.h> int main() { char name[50];int character[26]={0};int i=0,j;int length=0;wh ...
- UVALive 7141 BombX(离散化+线段树)(2014 Asia Shanghai Regional Contest)
题目链接:https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&category=6 ...
- Extjs 3.4 同值合并
摘自:http://www.cnblogs.com/kunpengit/archive/2012/11/13/2768239.html/** * grid gridPanel 需要合并的表格 * ro ...
- Java多线程开发系列之四:玩转多线程(线程的控制1)
在前文中我们已经学习了:线程的基本情况.如何创建多线程.线程的生命周期.利用已有知识我们已经可以写出如何利用多线程处理大量任务这样简单的程序.但是当应用场景复杂时,我们还需要从管理控制入手,更好的操纵 ...