Getting Started with Plotly in ggplot2

Get started with Plotly's R graphing library with ggplot2 to make interactive, publication-quality graphs online.


Plotly Studio: Transform any dataset into an interactive data application in minutes with AI. Try Plotly Studio now.

Note: We are retiring documentation for R, MATLAB, Julia, and F#. Learn more about this change here.

Plotly for R

Plotly is an R package for creating interactive web-based graphs via plotly's JavaScript graphing library, plotly.js.

The plotly R package serializes ggplot2 figures into Plotly's universal graph JSON. plotly::ggplotly will crawl the ggplot2 figure, extract and translate all of the attributes of the ggplot2 figure into JSON (the colors, the axes, the chart type, etc), and draw the graph with plotly.js.

Furthermore, you have the option of manipulating the Plotly object with the style function.

Build Status

Installation

Plotly is now on CRAN!

install.packages("plotly")

Or install the latest development version (on GitHub) via devtools:

devtools::install_github("ropensci/plotly")

RStudio users should download the latest RStudio release for compatibility with htmlwidgets.

Initialization

By default, Plotly for R runs locally in your web browser or in the R Studio viewer.

library(plotly)

set.seed(100)
d <- diamonds[sample(nrow(diamonds), 1000), ]

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)

ggplotly(p)

Simply printing the Plotly object will render the chart locally in your web browser or in the R Studio viewer.

Plotly graphs are interactive. Click on legend entries to toggle traces, click-and-drag on the chart to zoom, double-click to autoscale, shift-and-drag to pan.

Cutomizing the Layout

Since the ggplotly() function returns a plotly object, we can manipulate that object in the same way that we would manipulate any other plotly object. A simple and useful application of this is to specify interaction modes, like plotly.js' layout.dragmode for specifying the mode of click+drag events.

library(plotly)
## Loading required package: ggplot2
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
p <- ggplot(fortify(forecast::gold), aes(x, y)) + geom_line()
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
p <- ggplotly(p)

p <- p %>% layout(dragmode = "pan")

p