Plotly has a new R API and ggplot2 library for making beautiful graphs. The API lets you produce interactive D3.js graphs with R. This post has five examples. Head to our docs to get a key and you can start making, embedding, and sharing plots. The code below produces our first plot.
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)
Hover to see data, click and drag to zoom, or double-click to autoscale.
Interactive ggplot2 Plotting
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)))) %>% 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))
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")
Plotly also supports interactive maps.
library(plotly) df <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/2011_us_ag_exports.csv") df$hover <- with(df, paste(state, '
', "Beef", beef, "Dairy", dairy, "
", "Fruits", total.fruits, "Veggies", total.veggies, "
", "Wheat", wheat, "Corn", corn)) # give state boundaries a white border l <- list(color = toRGB("white"), width = 2) # specify some map projection/options g <- list( scope = 'usa', projection = list(type = 'albers usa'), showlakes = TRUE, lakecolor = toRGB('white') ) plot_ly(df, z = total.exports, text = hover, locations = code, type = 'choropleth', locationmode = 'USA-states', color = total.exports, colors = 'Purples', marker = list(line = l), colorbar = list(title = "Millions USD"), filename="r-docs/usa-choropleth") %>% layout(title = '2011 US Agriculture Exports by State
(Hover for breakdown)', geo = g)
If you have sensitive data, need to collaborate with your team, and need interactive dashboards, contact us about Plotly on-premise. Plotly’s R API was developed by Carson Sievert and Chris Parmer. If you liked what you read, please consider sharing. Find us at [email protected] and @plotlygraphs.