Lab session on Plotly for R

This notebook introduces to the plotly library for R. The library is also available for Pythonand is free and open-source. The main goals of this lab session are for you to:

  1. create basic charts, including a pie chart.
  2. create time series and spatial charts
  3. add custom controls and animations so that you can interact with plots

Before doing this, we need to install and load the package.

#install.packages("plotly", repos = "http://cran.us.r-project.org")
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
library("dplyr")
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union

Creating basic plots

Plotly includes an extensive set of charts that cover most common use cases. By having a fixed set of charts, plotly has the disadvantage (compared to ggplot) of having less control over how data are charted. Conversely, this limitation means that the the library creators have simplified the syntax used to create graphs. In other words, you will probably find it much easier to create standard graphs in plotly, compared to ggplot. Creating anything fancy, like the Napoleon war chart, is not possible in plotly.

Here, we will go through a few examples of how to plot a simple bar chart, pie chart, and distribution plots (line of best fit over histogram). We will also show the corresponding ggplot2 code, so that you can compare the two. The full list of charts is available at plotly.com

import and view data

We will use the mtcars dataset, which is built into R

data(iris)
head(iris, 6)

create bar chart

Note that, unlike ggplot, the data has to be explicitly processed - i.e. if we didn’t pre-process the Species column, then the x axis would have 150 columns, each corresponding to a row of data.

x_vals = unique(iris$Species)
y_vals = table(iris$Species)
fig <- plot_ly(x = x_vals, y = y_vals, color = ~x_vals, type = "bar")
fig

create pie chart

Compare the code for generating a pie chart in plotly compared to the ggplot2 equivalent.

fig <- plot_ly(labels = x_vals, values = y_vals, type = "pie")
fig
# here is an alternative way to achieve the same goal
#Pie_Data<-count(iris,Species)
#fig <- plot_ly(data=Pie_Data,values=~n,labels=~factor(Species), type = "pie")
#fig

Q1 create scatter plot

By making use of plotly’s documentation, create a simple chart that shows the relationship between sepal length and sepal width.

#Insert code for Q1 here

Q2 - create multiple subplots

Create a 4x4 grid of plots showing scatterplots for every combination of the Iris data set variables using the splom plot

#Insert code for Q2 here

Q3 - recreate splom plot manually

Create a 4x4 grid of plots showing scatterplots for every combination of the Iris data set variables

# here is some starter code, but the actual output should be 4x4 - complete Q3 code below

fig1 <- plot_ly(data=iris, x = ~Sepal.Length, y = ~Sepal.Length, type = 'scatter')
fig2 <- plot_ly(data=iris, x = ~Sepal.Length, y = ~Sepal.Width, type = 'scatter')
fig3 <- plot_ly(data=iris, x = ~Sepal.Width, y = ~Sepal.Length, type = 'scatter')
fig4 <- plot_ly(data=iris, x = ~Sepal.Width, y = ~Sepal.Width, type = 'scatter')

fig <- subplot(fig1, fig2, fig3, fig4, nrows = 2) %>%
  layout(plot_bgcolor='#e5ecf6', 
         xaxis = list( 
           zerolinecolor = '#ffff', 
           zerolinewidth = 2, 
           gridcolor = 'ffff'), 
         yaxis = list( 
           zerolinecolor = '#ffff', 
           zerolinewidth = 2, 
           gridcolor = 'ffff'))
## No scatter mode specifed:
##   Setting the mode to markers
##   Read more about this attribute -> https://plotly.com/r/reference/#scatter-mode
## No scatter mode specifed:
##   Setting the mode to markers
##   Read more about this attribute -> https://plotly.com/r/reference/#scatter-mode
## No scatter mode specifed:
##   Setting the mode to markers
##   Read more about this attribute -> https://plotly.com/r/reference/#scatter-mode
## No scatter mode specifed:
##   Setting the mode to markers
##   Read more about this attribute -> https://plotly.com/r/reference/#scatter-mode
fig

Time Series and Spatial visualisations

Plotly also supports standard time series and spatial visualisations. In this next part of the lab, you will create a line chart for time series data. If you have more time, explore some of the other visualisations available with plotly. An example of a spatial (map) plot is also provided

For these exercises, we will import some data sets directly from the UCI repository. Effectively, this downloads data via a hyperlink.

Q4: create a line chart with dates on the x-axis

Import and view data first:

# import database
chickenpox <- read.csv("hungary_chickenpox.csv", header=TRUE)
# view a few rows to check that the data looks as we expect
head(chickenpox)

Create a line chart that plots the number of chicken pox cases in BUDAPEST and BARANYA over time. As before, review the plotly documentation. Note that there the plotly documentation contains additional information about how to deal with ‘date’ datatypes

# Add Q4 code here

Generating a chloropleth heatmap

The code below uses world gross domestic product data for each country in the world, and plots it as a heat map. Plotly allows for the use of any arbitrary map via GEOJson files, but also has two maps pre-installed, a world map with countries, and a US map with states. The code below is directly from the plotly tutorial. Before running the code, you should ensure that you understand what each line of the code is doing. In the final (optional) question of this lab, you will be asked to extend this to create an interactive map that shows how GDP changes over time.

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

# light grey boundaries
l <- list(color = toRGB("grey"), width = 0.5)

# specify map projection/options
g <- list(
  showframe = FALSE,
  showcoastlines = FALSE,
  projection = list(type = 'Mercator')
)

fig <- plot_geo(df)
fig <- fig %>% add_trace(
    z = ~GDP..BILLIONS., color = ~GDP..BILLIONS., colors = 'Blues',
    text = ~COUNTRY, locations = ~CODE, marker = list(line = l)
  )
fig <- fig %>% colorbar(title = 'GDP Billions US$', tickprefix = '$')
fig <- fig %>% layout(
    title = '2014 Global GDP<br>Source:<a href="https://www.cia.gov/library/publications/the-world-factbook/fields/2195.html">CIA World Factbook</a>',
    geo = g
  )

fig

Interaction

By selecting one of your previous charts, you will see that you can easily pan and zoom. It’s also possible to hover over datapoints to and bring up a tooltip that displays information about the data point. (note that this doesn’t work in my version of rstudio - so, you may need to preview the notebook, and then ‘open in browser’) This is built in to plotly, but it can also integrate with ggplot. We show one example of this below:

# here is the ggplot code
g <- ggplot(mpg, aes(class))  
p <-  g + geom_bar()

#this function converts from ggplot to plotly
ggplotly(p)

Q5 - generate your own interactive chart from a ggplot chart

Starting with one of the ggplot charts that you generated in Monday or Tuesday’s lab, convert it to a plotly interactive chart

#Q5 - insert your code here

Interaction - buttons and sliders

The final feature of plotly that we will look at in this lab is the use of buttons and sliders to change a graph. An example of each, for the chickenpox data, is shown below.

The first example uses a button to switch between the two line graphs you generated in Q4. This uses the ‘update’ method. From the plotly documentation, you will see that ‘restyle’, ‘relayout’ and ‘animate’ are other methods that control what a button will do.

# Add Q4 code here
# updatemenus component
updatemenus <- list(
  list(
    active = -1,
    type= 'buttons',
    buttons = list(
      list(
        label = "Budapest",
        method = "update",
        args = list(list(visible = c(FALSE, TRUE)),
                    list(title = "Budapest"))),
      list(
        label = "Baranya",
        method = "update",
        args = list(list(visible = c(TRUE, FALSE)),
                    list(title = "Baranya"))),
      list(
        label = "Both",
        method = "update",
        args = list(list(visible = c(TRUE, TRUE)),
                    list(title = "Both")))
    )
  )
)

# Creates line graphs. The additional layout component creates the buttons, with functionality according to 'updatemenus'
fig <- plot_ly(chickenpox, type = 'scatter', mode = 'lines')%>%
  add_lines(x = ~Date, y = ~BUDAPEST, name = 'Budapest')%>%
  add_lines(x = ~Date, y = ~BARANYA, name = 'Baranya')
fig <- fig %>% layout(updatemenus = updatemenus)
options(warn = -1)
fig

Q5 - edit buttons

To test your understanding of the code above, add another time series that can be selected individually using a button.

# insert question 5 code here - we suggest you start by copying the code snippet above