Getting started: Plotly with ggplot2

Installation

First, install and load the devtools package. From within the R console, enter:

install.packages("devtools")
library("devtools")

Next, install plotly. From within the R console, enter:

install_github("ropensci/plotly")

Plotly's R package is updated frequently! To upgrade, just re-install:

devtools::install_github("ropensci/plotly")

Initialization

In the R console, import the Plotly R library.

library(plotly)

This will print:


Loading required package: RCurl
Loading required package: bitops
Loading required package: RJSONIO
Loading required package: ggplot2

Authentication

Set your Plotly user credentials.

set_credentials_file("DemoAccount", "lr1c37zw81")

You'll need to replace "DemoAccount" and "lr1c37zw81" with your Plotly username and API key.

Find my API key.

You only have to set this up if it's your first time using a Plotly API.


Special Instructions for Plotly On-Premise users
Your API key for account on the public cloud will be different than the API key in Plotly On-Premise. Visit https://plotly.your-company.com/settings/api/ to find your Plotly On-Premise API key. Remember to replace "your-company.com" with the URL of your Plotly On-Premise server.

If your company has a Plotly On-Premise server, change the API endpoint so that it points to your company's Plotly server instead of Plotly's cloud.

In your R console, enter:


set_config_file("https://plotly.your-company.com", "plotly.your-company.com")

Make sure to replace "your-company.com" with the URL of your Plotly On-Premise server. Questions? support@plot.ly

Start plotting!

Make a plot with ggplot2, as usual:

ggiris <- qplot(Petal.Width, Sepal.Length, data = iris, color = Species)
ggiris

Now make this plot interactive and online. To do this, first instantiate a Plotly object:

py <- plotly()

And call the ggplotly() method to convert your ggplot2 plot into a Plotly plot:

r <- py$ggplotly(ggiris)

Your online, interactive, collaborative plot lives at this URL:

r$response$url

Credentials

The initialization step places a special .plotly/.credentials file in your home directory. Your ~/.plotly/.credentials file should look something like this:


{
    "username": "DemoAccount",
    "stream_ids": ["ylosqsyet5", "h2ct8btk1s", "oxz4fm883b"],
    "api_key": "lr1c37zw81"
}
            

You can change the contents of this file manually or as described in the Initialization section.