The following is a very simple demonstration on using the Plotly package in R in order to create interactive plots. This assignment is part of the Data Products course under John Hopkins University’s Data Science Specialization. The prompt is simply as follows:
Create a web page presentation using R Markdown that features a plot created with Plotly. Host your webpage on either GitHub Pages, RPubs, or NeoCities. Your webpage must contain the date that you created the document, and it must contain a plot created with Plotly.
For this example, we will be exploring the “Orange” dataset from the datasets library.
library(tidyverse)
library(magrittr)
library(plotly)
Lets load the dataset to our own object named data:
data <- datasets::Orange
To get an idea of how our data looks, lets take a peek at the first few rows:
head(data)
## Tree age circumference
## 1 1 118 30
## 2 1 484 58
## 3 1 664 87
## 4 1 1004 115
## 5 1 1231 120
## 6 1 1372 142
As you can see, the dataset is pretty straight forward, with only 35 rows and 3 variables. There are 5 total trees, each with 7 observations that record the tree age and trunk circumference.
We will now create and assign our plot to an object named
plot. We will be plotting the age of the tree on the
x-axis, and the trunk circumference on the y-axis. Additionally, we are
facet wrapping around the “Tree” variable.
plot <- data %>% ggplot(aes(x = age, y = circumference)) +
geom_line(color = "orange", linewidth = 1) +
labs(x = "Tree Age (days since 1968/12/31)",
y = "Trunk Circumference (mm)",
title = "Growth of Five Orange Trees") +
facet_wrap(~factor(Tree, levels = c("1", "2", "3", "4", "5")),
scales = "free_x") +
theme_light()
Now, all that’s left is to pass our ggplot plot to the
ggplotly() function from the plotly library in order to
create our interactive plot:
ggplotly(plot)