閱讀506 返回首頁    go gooseeker集搜客


一行R代碼實現數據分析可視化

本文摘自:大數據文摘
作者簡介:       唐源,目前就職於芝加哥一家創業公司,曾參與和創作過多個被廣泛使用的 R 和 Python 開源項目,是 ggfortify,lfda,metric-learn 等包的作者,也是 xgboost,caret,pandas 等包的貢獻者。(喜歡爬山和燒烤 )
       ggfortify 是一個簡單易用的R軟件包,它可以僅僅使用一行代碼來對許多受歡迎的R軟件包結果進行二維可視化,這讓統計學家以及數據科學家省去了許多繁瑣和重複的過程,不用對結果進行任何處理就能以 ggplot 的風格畫出好看的圖,大大地提高了工作的效率。
       ggfortify 已經可以在 CRAN 上下載得到,但是由於最近很多的功能都還在快速增加,因此還是推薦大家從 Github 上下載和安裝。
1  library(devtools)2  install_github('sinhrks/ggfortify')3  library(ggfortify)
       接下來我將簡單介紹一下怎麼用 ggplot2 和 ggfortify 來很快地對PCA、聚類以及LFDA的結果進行可視化,然後將簡單介紹用 ggfortify 來對時間序列進行快速可視化的方法。
1,PCA (主成分分析)       ggfortify 使 ggplot2 知道怎麼詮釋PCA對象。加載好 ggfortify 包之後, 你可以對stats::prcomp 和 stats::princomp 對象使用 ggplot2::autoplot。
1  library(ggfortify)2  df <- iris[c(1, 2, 3, 4)]3  autoplot(prcomp(df))

       你還可以選擇數據中的一列來給畫出的點按類別自動分顏色。輸入help(autoplot.prcomp) 可以了解到更多的其他選擇。
4  autoplot(prcomp(df), data = iris, colour = 'Species')

       比如說給定label = TRUE 可以給每個點加上標識(以rownames為標準),也可以調整標識的大小。
5  autoplot(prcomp(df), data = iris, colour = 'Species', label = TRUE,label.size = 3)

       給定 shape = FALSE 可以讓所有的點消失,隻留下標識,這樣可以讓圖更清晰,辨識度更大。
6  autoplot(prcomp(df), data = iris, colour = 'Species', shape = FALSE, label.size = 3)

       給定 loadings = TRUE 可以很快地畫出特征向量。
7  autoplot(prcomp(df), data = iris, colour = 'Species', loadings = TRUE)

       同樣的,你也可以顯示特征向量的標識以及調整他們的大小,更多選擇請參考幫助文件。
8  autoplot(prcomp(df), data = iris, colour = 'Species',loadings = TRUE, loadings.colour = 'blue',loadings.label = TRUE, loadings.label.size = 3)


2,因子分析       和PCA類似,ggfortify 也支持 stats::factanal 對象。可調的選擇也很廣泛。以下給出了簡單的例子:       注意 當你使用 factanal 來計算分數的話,你必須給定 scores 的值。
1  d.factanal <- factanal(state.x77, factors = 3, scores = 'regression')2  autoplot(d.factanal, data = state.x77, colour = 'Income')

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


3,K-均值聚類
1  autoplot(kmeans(USArrests, 3), data = USArrests)


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


4,其他聚類       ggfortify 也支持 cluster::clara, cluster::fanny, cluster::pam。
1  library(cluster)2  autoplot(clara(iris[-5], 3))

       給定 frame = TRUE,可以把 stats::kmeans 和 cluster::* 中的每個類圈出來。
3  autoplot(fanny(iris[-5], 3), frame = TRUE)

       你也可以通過 frame.type 來選擇圈的類型。更多選擇請參照 ggplot2::stat_ellipse 裏麵的 frame.type 的 type 關鍵詞。
4  autoplot(pam(iris[-5], 3), frame = TRUE, frame.type = 'norm')

       更多關於聚類方麵的可視化請參考 Github 上的 Vignette 或者 Rpubs 上的例子。
5,lfda(Fisher局部判別分析)       lfda 包支持一係列的 Fisher 局部判別分析方法,包括半監督 lfda,非線性 lfda。你也可以使用 ggfortify 來對他們的結果進行可視化。
1  library(lfda)2  # Fisher局部判別分析 (LFDA)3  model <- lfda(iris[-5], iris[, 5], 4, metric="plain")4  autoplot(model, data = iris, frame = TRUE, frame.colour = 'Species')

5  # 非線性核Fisher局部判別分析 (KLFDA)6  model <- klfda(kmatrixGauss(iris[-5]), iris[, 5], 4, metric="plain")7  autoplot(model, data = iris, frame = TRUE, frame.colour = 'Species')

       注意 對 iris 數據來說,不同的類之間的關係很顯然不是簡單的線性,這種情況下非線性的klfda 影響可能太強大而影響了可視化的效果,在使用前請充分理解每個算法的意義以及效果。
8   # 半監督Fisher局部判別分析 (SELF)9   model <- self(iris[-5], iris[, 5], beta = 0.1, r = 3, metric="plain")10 autoplot(model, data = iris, frame = TRUE, frame.colour = 'Species')


6,時間序列的可視化用 ggfortify 可以使時間序列的可視化變得極其簡單。接下來我將給出一些簡單的例子。
6.1,ts對象
1  library(ggfortify)2  autoplot(AirPassengers)

       可以使用 ts.colour 和 ts.linetype 來改變線的顏色和形狀。更多的選擇請參考 help(autoplot.ts)。
3  autoplot(AirPassengers, ts.colour = 'red', ts.linetype = 'dashed')



6.2,多變量時間序列
4  library(vars)5  data(Canada)6  autoplot(Canada)

       使用 facets = FALSE 可以把所有變量畫在一條軸上。
7  autoplot(Canada, facets = FALSE)

6.3,其他時間序列       autoplot 也可以理解其他的時間序列類別。可支持的R包有:
  • zoo::zooreg
  • xts::xts 
  • timeSeries::timSeries
  • tseries::irts

       一些例子:
8  library(xts)9  autoplot(as.xts(AirPassengers), ts.colour = 'green')

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

       你也可以通過 ts.geom 來改變幾何形狀,目前支持的有 line, bar 和 point。
12  autoplot(AirPassengers, ts.geom = 'bar', fill = 'blue')

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

6.4,forecast包
14  library(forecast)15  d.arima <- auto.arima(AirPassengers)16  d.forecast <- forecast(d.arima, level = c(95), h = 50)17  autoplot(d.forecast)

       有很多設置可供調整:
18  autoplot(d.forecast, ts.colour = 'firebrick1', predict.colour = 'red',predict.linetype = 'dashed', conf.int = FALSE)


6.5,vars包
19  library(vars)20  data(Canada)21  d.vselect <- VARselect(Canada, lag.max = 5, type = 'const')$selection[1]22  d.var <- VAR(Canada, p = d.vselect, type = 'const')23  autoplot(predict(d.var, n.ahead = 50), ts.colour = 'dodgerblue4', predict.colour = 'blue', predict.linetype = 'dashed')

6.6,changepoint包
24  library(changepoint)25  autoplot(cpt.meanvar(AirPassengers))

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



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

6.8,dlm包
29  library(dlm)30  form <- function(theta){31      dlmModPoly(order = 1, dV = exp(theta[1]), dW = exp(theta[2]))32  }3334  model <- form(dlmMLE(Nile, parm = c(1, 1), form)$par)35  filtered <- dlmFilter(Nile, model)3637  autoplot(filtered)

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

39  smoothed <- dlmSmooth(filtered)40  autoplot(smoothed)

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


6.9,KFAS包
43  library(KFAS)44  model <- SSModel(45      Nile ~ SSMtrend(degree=1, Q=matrix(NA)), H=matrix(NA)46  )47 48  fit <- fitSSM(model=model, inits=c(log(var(Nile)),log(var(Nile))), method="BFGS")49  smoothed <- KFS(fit$model)50  autoplot(smoothed)

       使用 smoothing='none' 可以畫出過濾後的結果。
51  filtered <- KFS(fit$model, filtering="mean", smoothing='none')52  autoplot(filtered)

53  trend <- signal(smoothed, states="trend")54  p <- autoplot(filtered)55  autoplot(trend, ts.colour = 'blue', p = p)


6.10,stats包
       可支持的stats包裏的對象有:
  • stl, decomposed.ts
  • acf, pacf, ccf
  • spec.ar, spec.pgram
  • cpgram

56  autoplot(stl(AirPassengers, s.window = 'periodic'), ts.colour = 'blue')

57  autoplot(acf(AirPassengers, plot = FALSE))


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



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

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

62  gglagplot(AirPassengers, lags = 4)


       更多關於時間序列的例子,請參考 Rpubs 上的介紹。
摘自:大數據文摘

最後更新:2017-01-09 14:08:06

  上一篇:go Yelp是如何使用深度學習對商業照片進行分類的
  下一篇:go 微信朋友圈技術之道:三個人的後台團隊與每日十億的發布量 ...