京公网安备 11010802034615号
经营许可证编号:京B2-20210330
一行R代码来实现繁琐的可视化
ggfortify 是一个简单易用的R软件包,它可以仅仅使用一行代码来对许多受欢迎的R软件包结果进行二维可视化,这让统计学家以及数据科学家省去了许多繁琐和重复的过程,不用对结果进行任何处理就能以ggplot的风格画出好看的图,大大地提高了工作的效率。
ggfortify 已经可以在 CRAN 上下载得到,但是由于最近很多的功能都还在快速增加,因此还是推荐大家从 Github 上下载和安装。
library(devtools) install_github('sinhrks/ggfortify') library(ggfortify)
接下来我将简单介绍一下怎么用ggplot2和ggfortify来很快地对PCA、聚类以及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))
你还可以选择数据中的一列来给画出的点按类别自动分颜色。输入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)
其他聚类
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')
更多关于聚类方面的可视化请参考 Github 上的 Vignette 或者 Rpubs 上的例子。
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局部判别分析 (KLFDA) model <- klfda(kmatrixGauss(iris[-5]), iris[, 5], 4, metric="plain") autoplot(model, data = iris, frame = TRUE, frame.colour = 'Species')
注意对iris数据来说,不同的类之间的关系很显然不是简单的线性,这种情况下非线性的klfda 影响可能太强大而影响了可视化的效果,在使用前请充分理解每个算法的意义以及效果。
# 半监督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
tseries::irts
一些例子:
library(xts) autoplot(as.xts(AirPassengers), ts.colour = 'green')
library(timeSeries) autoplot(as.timeSeries(AirPassengers), ts.colour = ('dodgerblue3'))
你也可以通过ts.geom来改变几何形状,目前支持的有line,bar和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) data(Canada) 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) 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") p <- autoplot(filtered) autoplot(trend, ts.colour = 'blue', p = p)
stats包
可支持的stats包里的对象有:
stl,decomposed.ts
acf,pacf,ccf
spec.ar,spec.pgram
cpgramautoplot(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)
数据分析咨询请扫描二维码
若不方便扫码,搜微信号:CDAshujufenxi
在用户行为分析实践中,很多从业者会陷入一个核心误区:过度关注“当前数据的分析结果”,却忽视了结果的“泛化能力”——即分析 ...
2026-03-13在数字经济时代,用户的每一次点击、浏览、停留、转化,都在传递着真实的需求信号。用户行为分析,本质上是通过收集、整理、挖掘 ...
2026-03-13在金融、零售、互联网等数据密集型行业,量化策略已成为企业挖掘商业价值、提升决策效率、控制经营风险的核心工具。而CDA(Certi ...
2026-03-13在机器学习建模体系中,随机森林作为集成学习的经典算法,凭借高精度、抗过拟合、适配多场景、可解释性强的核心优势,成为分类、 ...
2026-03-12在机器学习建模过程中,“哪些特征对预测结果影响最大?”“如何筛选核心特征、剔除冗余信息?”是从业者最常面临的核心问题。随 ...
2026-03-12在数字化转型深度渗透的今天,企业管理已从“经验驱动”全面转向“数据驱动”,数据思维成为企业高质量发展的核心竞争力,而CDA ...
2026-03-12在数字经济飞速发展的今天,数据分析已从“辅助工具”升级为“核心竞争力”,渗透到商业、科技、民生、金融等各个领域。无论是全 ...
2026-03-11上市公司财务报表是反映企业经营状况、盈利能力、偿债能力的核心数据载体,是投资者决策、研究者分析、从业者复盘的重要依据。16 ...
2026-03-11数字化浪潮下,数据已成为企业生存发展的核心资产,而数据思维,正是CDA(Certified Data Analyst)数据分析师解锁数据价值、赋 ...
2026-03-11线性回归是数据分析中最常用的预测与关联分析方法,广泛应用于销售额预测、风险评估、趋势分析等场景(如前文销售额预测中的多元 ...
2026-03-10在SQL Server安装与配置的实操中,“服务名无效”是最令初学者头疼的高频问题之一。无论是在命令行执行net start启动服务、通过S ...
2026-03-10在数据驱动业务的当下,CDA(Certified Data Analyst)数据分析师的核心价值,不仅在于解读数据,更在于搭建一套科学、可落地的 ...
2026-03-10在企业经营决策中,销售额预测是核心环节之一——无论是库存备货、营销预算制定、产能规划,还是战略布局,都需要基于精准的销售 ...
2026-03-09金融数据分析的核心价值,是通过挖掘数据规律、识别风险、捕捉机会,为投资决策、风险控制、业务优化提供精准支撑——而这一切的 ...
2026-03-09在数据驱动决策的时代,CDA(Certified Data Analyst)数据分析师的核心工作,是通过数据解读业务、支撑决策,而指标与指标体系 ...
2026-03-09在数据处理的全流程中,数据呈现与数据分析是两个紧密关联却截然不同的核心环节。无论是科研数据整理、企业业务复盘,还是日常数 ...
2026-03-06在数据分析、数据预处理场景中,dat文件是一种常见的二进制或文本格式数据文件,广泛应用于科研数据、工程数据、传感器数据等领 ...
2026-03-06在数据驱动决策的时代,CDA(Certified Data Analyst)数据分析师的核心价值,早已超越单纯的数据清洗与统计分析,而是通过数据 ...
2026-03-06在教学管理、培训数据统计、课程体系搭建等场景中,经常需要对课时数据进行排序并实现累加计算——比如,按课程章节排序,累加各 ...
2026-03-05在数据分析场景中,环比是衡量数据短期波动的核心指标——它通过对比“当前周期与上一个相邻周期”的数据,直观反映指标的月度、 ...
2026-03-05