Five Interactive R Visualizations With D3, ggplot2, & RStudio

August 24, 2015

(This article was first published on Modern Data » R, and kindly contributed to R-bloggers)

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.

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.


price vs carat
Key features are: you can share plots with a private or public URL (e.g., Interactive graphs can be embedded in knitr docs, dashboards, websites, and Shiny Apps. Updating charts is easy. Users can collaborate from any device or browser in a web app or with Plotly’s APIs for Python and MATLAB.



Interactive ggplot2 Plotting

Plotly’s ggplot2 converter turns ggplot2 plots into interactive, web-based plots. You can control the tooltip. For example, note the text.

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))



None, None, None, None, None, Fair, Good, Very Good, Premium, Ideal, Fair, Good, Very Good, Premium, Ideal


Plotly is free for online sharing. Licenses are available for on-premise deployments and Plotly Offline. Plotly Offline works inside RStudio:


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))


Median duration of unemployment (in weeks)


3D WebGL

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")



Interactive Maps

Plotly also supports interactive maps.

df <- read.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)


(Hover for breakdown)" width="450" />

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.

To leave a comment for the author, please follow the link and comment on their blog: Modern Data » R. offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)