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.
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.
Use the install.package() function to install the plotly R package from CRAN.
install.packages("plotly")
library(plotly)
library(ggplot2)
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.
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.
ggplot2This 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)
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:
You can also get more information from the plot using the other three buttons
Here I will just show other examples of plots that can use the plotly package.
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
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
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
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)
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
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.