Getting Started with Plotly for R

Getting Started with Plotly for R

  • Plotly is a free and open-source graphing library for R.

  • Plotly’s R graphing library makes interactive, publication-quality graphs.

Getting Started with Plotly for R

  • Plotly is a free and open-source graphing library for R.

  • Plotly’s R graphing library makes interactive, publication-quality graphs.

  • You can view the source, report issues or contribute on GitHub.

Getting Started with Plotly for R

  • Plotly is a free and open-source graphing library for R.

  • Plotly’s R graphing library makes interactive, publication-quality graphs.

  • You can view the source, report issues or contribute on GitHub.

  • plotly is an R package for creating interactive web-based graphs via the open source JavaScript graphing library plotly.js.

Getting Started with Plotly for R

  • Plotly is a free and open-source graphing library for R.

  • Plotly’s R graphing library makes interactive, publication-quality graphs.

  • You can view the source, report issues or contribute on GitHub.

  • plotly is an R package for creating interactive web-based graphs via the open source JavaScript graphing library plotly.js.

  • As of version 2.0 (November 17, 2015), graphs created with the plotly R package are rendered locally through the htmlwidgets framework.

Installation

Download from CRAN

install.packages("plotly")

Installation

Download from CRAN

install.packages("plotly")

Download from GitHub

  • Alternatively, you can install the latest development version of plotly from GitHub via the devtools R package:
devtools::install_github("ropensci/plotly")

Installation

Download from CRAN

install.packages("plotly")

Download from GitHub

  • Alternatively, you can install the latest development version of plotly from GitHub via the devtools R package:
devtools::install_github("ropensci/plotly")

Note For RStudio Users

  • RStudio users should ensure that they are using the latest RStudio release in order to ensure compatibility with the htmlwidgets R package.

Rendering Charts

By default, the plotly R package runs locally in your web browser or in the RStudio viewer.

library(plotly)
plot_ly(midwest, x = ~percollege, color = ~state, type = "box", height=350, width=800)

Rendering Charts

Simply printing the plot object will render the chart locally in your web browser or in the RStudio viewer.

Rendering Charts

Graphs created with the plotly R package are interactive!

Rendering Charts

Click on legend entries to hide/show traces, click-and-drag on the chart to zoom, double-click to autoscale, shift-and-drag to pan.

Basic Charts

Basic Scatter Plot

plot_ly(data = iris, x = ~Sepal.Length, y = ~Petal.Length)

Qualitative Colorscales

plot_ly(data = iris, x = ~Sepal.Length, y = ~Petal.Length, color = ~Species)

Adding Color and Size Mapping

plot_ly(diamonds[sample(nrow(diamonds), 1000), ], x = ~carat, y = ~price, color = ~carat, size = ~carat)

Data Labels on Hover

plot_ly(
  diamonds[sample(nrow(diamonds), 1000), ], x = ~carat, y = ~price,
  # Hover text:
  text = ~paste("Price: ", price, '$<br>Cut:', cut),
  color = ~carat, size = ~carat
)

Data Labels on Hover

See https://plot.ly/r/reference/#scatter for more information and chart attribute options!

3D Scatter Plot

mtcars$am[which(mtcars$am == 0)] <- 'Automatic'
mtcars$am[which(mtcars$am == 1)] <- 'Manual'
mtcars$am <- as.factor(mtcars$am)

fig <- plot_ly(mtcars, x = ~wt, y = ~hp, z = ~qsec, color = ~am, colors = c('#BF382A', '#0C4B8E'))
fig <- fig %>% add_markers()
fig <- fig %>% layout(scene = list(xaxis = list(title = 'Weight'),
                     yaxis = list(title = 'Gross horsepower'),
                     zaxis = list(title = '1/4 mile time')))

fig

3D Scatter Plot

See https://plot.ly/r/reference/#scatter3d for more information and chart attribute options!

Basic Line Plot

Add mode and type arguements to make line graphs. They’re of course useful for showing change over time:

data("airmiles")
plot_ly(x = time(airmiles), y = airmiles, mode='lines',type='scatter', height=350)

Multi Line Graph

You can show multiple lines by specifying the column in the data frame that separates the lines:

library(tidyr)
library(dplyr)
data("EuStockMarkets")

stocks <- as_tibble(EuStockMarkets) %>%
  gather(index, price) %>%
  mutate(time = rep(time(EuStockMarkets), 4))

plot_ly(x = stocks$time, y = stocks$price, color = stocks$index, type = 'scatter', mode = 'lines')

Multi Line Graph

Density Plot

dens <- with(diamonds, tapply(price, INDEX = cut, density))
df <- data.frame(
  x = unlist(lapply(dens, "[[", "x")),
  y = unlist(lapply(dens, "[[", "y")),
  cut = rep(names(dens), each = length(dens[[1]]$x))
)

fig <- plot_ly(df, x = ~x, y = ~y, color = ~cut) 
fig <- fig %>% add_lines()

fig

Density Plot

See https://plot.ly/r/reference/#scatter for more information and chart attribute options!

Basic Histogram

Histograms are great for showing how counts of data are distributed. Use the type = "histogram" argument.

plot_ly(x = ~rnorm(50), type = "histogram",height=350, width = 600)

Overlaid Histograms

Use alpha to set the opacity to make overlayed histograms easier to see:

fig <- plot_ly(alpha = 0.6)
fig <- fig %>% add_histogram(x = ~rnorm(500))
fig <- fig %>% add_histogram(x = ~rnorm(500) + 1)
fig <- fig %>% layout(barmode = "overlay")

fig

Overlaid Histograms

See https://plot.ly/r/reference/#histogram for more information and chart attribute options!

Boxplot

plot_ly(ggplot2::diamonds, y = ~price, color = ~cut, type = "box")

See https://plot.ly/r/reference/#box for more information and chart attribute options!

Basic 3D Surface Plot

plot_ly(z = ~volcano) %>% add_surface()

Choropleth Maps

df <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/2011_us_ag_exports.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')
)

fig <- plot_geo(df, locationmode = 'USA-states')
fig <- fig %>% add_trace(
    z = ~total.exports, text = ~hover, locations = ~code,
    color = ~total.exports, colors = 'Purples'
  )
fig <- fig %>% colorbar(title = "Millions USD")
fig <- fig %>% layout(
    title = '2011 US Agriculture Exports by State<br>(Hover for breakdown)',
    geo = g
  )

fig

Choropleth Maps

Plotly ggplot2 Library

With ggplotly() by Plotly, you can convert your ggplot2 figures into interactive ones powered by plotly.js, ready for embedding into Dash applications.

library(plotly)

dat <- data.frame(
    time = factor(c("Lunch","Dinner"), levels=c("Lunch","Dinner")),
    total_bill = c(14.89, 17.23)
)

p <- ggplot(data=dat, aes(x=time, y=total_bill)) +
    geom_bar(stat="identity")

fig <- ggplotly(p)

fig

Plotly ggplot2 Library

Publishing your plot online

You can publish your charts to the web with Plotly’s web service.

1. Create a free Plotly account:

  • A Plotly account is required to publish charts online. It’s free to get started, and you control the privacy of your charts.

Publishing your plot online

2. Save your authentication credentials

Sys.setenv("plotly_username"="your_plotly_username")
Sys.setenv("plotly_api_key"="your_api_key")
  • Save these commands in your .Rprofile file to be run every time you start R.

Publishing your plot online

3. Publish your graphs to Plotly with api_create

library(plotly)
p <- plot_ly(midwest, x = ~percollege, color = ~state, type = "box")
api_create(p, filename = "r-docs-midwest-boxplots")
  • filename sets the name of the file inside your online plotly account.

Resources