Five Interactive R Visualizations With D3, ggplot2, & RStudio

[This article was first published on Modern Data » R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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, '<br>', "Beef", beef, "Dairy", dairy, "<br>",
                           "Fruits", total.fruits, "Veggies", total.veggies,
                           "<br>", "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<br>(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.

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 about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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)