R的plotly包是一個基於瀏覽器的交互式圖表庫,它創建在開源的JavaScript圖表庫plotly.js之上。它經過HTML widgets框架徹底在本地上運行。把結果上傳到plotly帳戶,能夠查看交互圖及相應的數據,並進行修改。javascript
library(plotly) library(ggplot2) set.seed(100) d <- diamonds[sample(nrow(diamonds), 1000), ] plot_ly(d, x = carat, y = price, text = paste("Clarity: ", clarity),mode = "markers", color = carat, size = carat)
注:ggplot2
包須要安裝最新的2.0.0版本,若是RStudio版本過低請直接在R上演示。html
plotly圖是可交互的。單擊拖動能夠放大,按下shift鍵單擊能夠移動,雙擊可自動縮放。java
p <- ggplot(data = d, aes(x = carat, y = price)) + geom_point(aes(text = paste("Clarity:", clarity)), size = 4) + geom_smooth(aes(colour = cut, fill = cut)) + facet_wrap(~ cut) (gg <- ggplotly(p))
plotly對象是一個plotly類的數據框,而且追蹤數據到可視化屬性的映射web
str(p <- plot_ly(economics, x = date, y = uempmed)) ## Classes 'plotly' and 'data.frame': 478 obs. of 6 variables: ## $ date : Date, format: "1967-06-30" "1967-07-31" ... ## $ pce : num 508 511 517 513 518 ... ## $ pop : int 198712 198911 199113 199311 199498 199657 199808 199920 200056 200208 ... ## $ psavert : num 9.8 9.8 9 9.8 9.7 9.4 9 9.5 8.9 9.6 ... ## $ uempmed : num 4.5 4.7 4.6 4.9 4.7 4.8 5.1 4.5 4.1 4.6 ... ## $ unemploy: int 2944 2945 2958 3143 3066 3018 2878 3001 2877 2709 ... ## - attr(*, "plotly_hash")= chr "7ff330ec8c566561765c62cbafed3e0f#2"
它容許咱們對數據進行混合操做,並可視化像pure(ly)、predictable、pipeable這樣一些所獲得的結果。這裏,咱們利用dplyr包中的filter
函數來標記出時間序列數據中的最高峯標籤:瀏覽器
p %>% add_trace(y = fitted(loess(uempmed ~ as.numeric(date)))) %>% layout(title = "Median duration of unemployment (in weeks)", showlegend = FALSE) %>% dplyr::filter(uempmed == max(uempmed)) %>% layout(annotations = list(x = date, y = uempmed, text = "Peak", showarrow = T))
雖然數據框被認爲是這個包的核心對象,但plotly作可視化也不必定都須要數據框。下面的圖形就是經過一個數值矩陣參數z
獲得的3D圖:網絡
plot_ly(z = volcano, type = "surface")
默認狀況下,plotly獲得的結果運行在你本地的瀏覽器或者是RStudio瀏覽器。經過plotly帳戶能夠發佈到網絡上。對於公開的圖表,plotly的託管是免費的。若是你有敏感數據,能夠升級到paid plan 框架
library(plotly) p <- plot_ly(midwest, x = percollege, color = state, type = "box") p # plotly_POST publishes the figure to your plotly account on the web plotly_POST(p, filename = "r-docs/midwest-boxplots", world_readable=TRUE)
注:用ployly_POST
函數發佈到網絡時,請先肯定建立了一個plotly帳戶。函數
本文由雪晴數據網負責翻譯整理,原文請參考Plotly R Library 2.0。轉載請註明原文連接http://www.xueqing.cc/cms/article/93 spa