This document is an introduction tutorial for the plotly R package. Many of the examples from this tutorial are borrowed from the plotly.com R tutorial.

What is Plotly.R?

Plotly’s R graphing library makes interactive, publication-quality graphs. It can be used to make a variety of graphics includeing: line plots, scatter plots, area charts, bar charts, error bars, box plots, histograms, heatmaps, subplots, multiple-axes, and 3D (WebGL based) charts. Plotly.R is free and open source and you can view the source, report issues or contribute on GitHub.

Download and install package

Use the install.package() function to install the plotly R package from CRAN.

install.packages("plotly")
library(plotly)
library(ggplot2)

Creating Plots

Plotly is a great tool for users to create beautiful, interactive plots. These can be plotted using the plotly package as well as using ggplot2.

data(midwest)
fig <- plot_ly(midwest, x = ~percollege, color = ~state, type = "box") #Plot percent college educated by state
fig

By printing the plot you will render the chart locally in your web browser or in the Rstudio viewer. This package allows you to share customize plots before and while using them, which I will touch on later.

Basic plots

To create a basic plot you can either directly plot in plotly or use ggplot2.

#import the iris data for example
data(iris)
fig <- plot_ly(data = iris, x = ~Sepal.Length, y = ~Petal.Length)
fig

You can see that with the plot you can scroll over the data point and see the value appear in the box next to the point. You can customize what information you want to appear in these pop-up boxes and how it will appear.

With ggplot2

This same plot can also be created in ggplot2 and saved as an object. Then the plot can be made interactive using the ggplotly function. (Note that not all features will work when using ggplotly so you sometimes have to do some trial and error)

fig2<- ggplot(data=iris, aes(x=Sepal.Length, y=Petal.Length))+
  geom_point()

ggplotly(fig2)

By being able to use ggplot2 you can customize the plots the same way that you can with ggplot.

#look at column names 
colnames(iris)
## [1] "Sepal.Length" "Sepal.Width"  "Petal.Length" "Petal.Width"  "Species"
#colour points by species

fig2<- ggplot(data=iris, aes(x=Sepal.Length, y=Petal.Length, colour=Species))+
  geom_point()

ggplotly(fig2)

Now you can also see that the Species appears in the text box as you hover over each point.

Just Like in ggplot you can customize the axis, title, color, etc…

fig2 <- ggplot(data=iris, aes(x = Sepal.Length, y = Petal.Length))+
  geom_point(aes(color=Species, shape=Species)) +
  xlab("Sepal Length") +  ylab("Petal Length") +
  ggtitle("Sepal Length- Petal Length")


ggplotly(fig2)

Features of Plot

Lets take a look at some of the features that you can use when looking at the plot created with plotly.

As mentioned before, you can hover over the different points to get more information about them, specifically the x and y values as well as any information about their colouring and/or grouping.

Another great feature is the ability to toggle on/off different groups. This is especially useful when you have a lot of overlapping points from different groups.

Now looking at the bar of features at the top, you can navigate the plot even more:

  • Save plot as PNG
  • Zoom into a particular area of the plot
  • Pan around plot
  • Select a particular group of points either with box or lasso
  • Zoom in/out
  • Autoscale (can use if axis are set)
  • Reset to original axis

You can also get more information from the plot using the other three buttons

  • Toggle Spike Lines
  • Closes feature hover (default)
  • Compare Hover (This allows you to see information about more than one point at once, you can customize when creating the plot if this is done by the x, y, or closest value)

Other Examples

Here I will just show other examples of plots that can use the plotly package.

Basic Bar Chart

dat1 <- data.frame(
    sex = factor(c("Female","Female","Male","Male")),
    time = factor(c("Lunch","Dinner","Lunch","Dinner"), levels=c("Lunch","Dinner")),
    total_bill = c(13.53, 16.81, 16.24, 17.42)
)

# Bar graph, time on x-axis, color fill grouped by sex -- use position_dodge()
p <- ggplot(data=dat1, aes(x=time, y=total_bill, fill=sex)) +
    geom_bar(stat="identity", position=position_dodge())

fig4 <- ggplotly(p)

fig4

Basic SF

Note that in this example they used the ggplot function nested within the ggplotly function.

library(sf)

nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)

fig3 <- ggplotly(
  ggplot(nc) +
  geom_sf(aes(fill = AREA))
) 

fig3

Maps

df <- read.csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_february_us_airport_traffic.csv')

# geo styling
g <- list(
  scope = 'usa',
  projection = list(type = 'albers usa'),
  showland = TRUE,
  landcolor = toRGB("gray95"),
  subunitcolor = toRGB("gray85"),
  countrycolor = toRGB("gray85"),
  countrywidth = 0.5,
  subunitwidth = 0.5
)

fig <- plot_geo(df, lat = ~lat, lon = ~long)
fig <- fig %>% add_markers(
    text = ~paste(airport, city, state, paste("Arrivals:", cnt), sep = "<br />"),
    color = ~cnt, symbol = I("square"), size = I(8), hoverinfo = "text"
  )
fig <- fig %>% colorbar(title = "Incoming flights<br />February 2011")
fig <- fig %>% layout(
    title = 'Most trafficked US airports<br />(Hover for airport)', geo = g
  )

fig

Raster

geom_raster creates a coloured heatmap, with two variables acting as the x- and y-coordinates and a third variable mapping onto a colour

library(reshape2)
library(plotly)

df <- melt(volcano)

p <- ggplot(df, aes(Var1, Var2)) +
  geom_raster(aes(fill=value)) +
  scale_fill_distiller(palette = "Spectral", direction = -1) +
  labs(x="West to East",
       y="North to South",
       title = "Elevation map of Maunga Whau",
       fill = "Elevation") +
  theme(text = element_text(family = 'Fira Sans'),
        plot.title = element_text(hjust = 0.5))

ggplotly(p)

3D Scatter Plots

Lastly you can use plotly to create 3D Scatter plots

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

Conclusion

plotly package in R allows you to create highly customizable, interactive plots, maps, etc. Because of its ability to intergrate with ggplot2 the possibilities are endless. I highly recommend that you explore https://plotly.com/r/ for more information on the types of graphics you can create and the package as a whole.