library(plotly) 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)
Plotly graphs are interactive. Click-drag to zoom, shift-click to pan, double-click to autoscale.
Know and love
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))
Mix data manipulation and visualization verbs
Plotly objects are data frames with a class of plotly and an environment that tracks the mapping from data to visual properties.
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"
This allows us to mix data manipulation and visualization verbs in a pure(ly) functional, predictable and pipeable manner. Here, we take advantage of dplyr's
filter() verb to label the highest peak in the time series:
p %>% add_trace(y = fitted(loess(uempmed ~ as.numeric(date))), x = 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))
3D WebGL and more
Although data frames can be thought of as the central object in this package, plotly visualizations don't actually require a data frame. This makes chart types that accept a
z argument especially easy to use if you have a numeric matrix:
plot_ly(z = volcano, type = "surface")
Run locally or publish to the web
By default, plotly for R runs locally in your web browser or R Studio's viewer. You can publish your graphs to the web by creating a plotly account.
Plotly hosting is free for public charts. If you have sensitive data, upgrade to a paid plan.
library(plotly) p <- plot_ly(midwest, x = percollege, color = state, type = "box") # plotly_POST publishes the figure to your plotly account on the web plotly_POST(p, filename = "r-docs/midwest-boxplots", sharing='public')