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