7.6 Interactive Plot with plotly()

Until now, all the plots we created are all static. In this section, we will introduce a powerful tool named plotly() that can make interactive plots. If you haven’t done so, you need to first install the R package plotly.

install.packages("plotly")

Let’s start with a static scatterplot and make it interactive.

library(r02pro)
library(ggplot2)
library(plotly)
#> 
#> 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
my_plot <- ggplot(data = gm2004) + 
    geom_point(mapping = aes(x = sugar, 
                             y = cholesterol))
ggplotly(my_plot)                           

Upon a first look, this may look identical to a regular scatterplot. However, you can try to move your cursor to the points which will show the corresponding coordinates. Some other features offered are available via a bar of buttons on the top right of the plot. Some useful features include

  • Download plot as png.
  • Zoom: Zoom a region of the plot.
  • Pan: Move the plot around.

In addition to the vanilla scatterplots, you can use plotly with more complicated plots that involves aesthetics.

my_plot_continent <- ggplot(data = gm2004) + 
    geom_point(mapping = aes(x = sugar, 
                             y = cholesterol,
                             color = continent))
ggplotly(my_plot_continent)   

Now, you can easily see the continent in addition to the sugarand cholesterol values for each data point.

Let’s try to use plotly with some other types of plots.

my_box_plot <- ggplot(data = na.omit(sahp), 
            aes(x = house_style, 
                y = sale_price)) +
  scale_x_discrete(limits=c("1Story", "2Story")) + geom_boxplot(mapping = aes(color = oa_qual > 5))
ggplotly(my_box_plot) 

For boxplots, we can easily see the values of summary statistics. You are welcome to try out plotly on other types of plots.

In this section, we introduced the plotly package for creating interactive plots. The ggplotly() function provides a convenient way to convert any static ggplot2 plot into an interactive one, enabling features like hovering to see data values, zooming, and downloading as PNG.

7.6.1 Exercises

  1. Using the sahp dataset from the r02pro package, create an interactive scatterplot of liv_area (x-axis) vs. sale_price (y-axis) using ggplotly().

  2. Enhance the plot from Exercise 1 by mapping house_style to the color aesthetic. Hover over points to verify that the house style information is displayed.

  3. Create an interactive violin plot of cholesterol grouped by continent using the gm2004 dataset. Restrict to three continents of your choice.


Buy Me A Coffee