The 'plotly' package is a large and complex beast.
This document just focuses on the ggplotly()
function, which is a very simple way to
add a variety of interactions to a 'ggplot2' plot.
library(plotly)
ggplotly()functionThis function takes a 'ggplot2' plot object and creates an interactive version of the plot. The plot automatically has a variety of interactive features, including tooltips, the ability to pan and zoom the plot region, and the ability to select points. We can select different interaction modes by clicking on different icons that appear in the top-right of the plot when the mouse is over the plot.
The documentation for the plotly modebar describes how to interact with the plotly plot.
In addition to the icons described there, there is the rectangle selection icon (a dashed rectangle) and the lasso selection icon (a lasso). You can shift-drag to add to the selection.
ggplotly(ggplot(mtcars) + geom_point(aes(disp, mpg)))
When used interactively in an R session, the interactive plot is opened automatically in a web browser.
When used in an R Markdown document, the interactive plot is automatically embedded in the processed HTML document.
text aesthetic
The default tooltips contain default information about points
(in scatterplots) or bars (in bar plots) based on the
aesthetic mappings in the ggplot() code.
'plotly' adds a text aesthetic that can be
used to provide additional text for the tooltip.
ggplotly(ggplot(mtcars) +
geom_point(aes(disp, mpg, text = paste0("Number of gears: ", gear))))
In the plot below, hover the mouse over a point to see the tooltip.
If our plot uses an aesthetic mapping that produces a (discrete) legend, we can use the legend to select and deselect groups within the plot.
Clicking on a data symbol in the legend hides/unhides the corresponding data symbols on the plot. Double-clicking a data symbol in the legend hides/unhides all other data symbols on the plot.
ggplotly(ggplot(mtcars) +
geom_point(aes(disp, mpg, colour=as.factor(gear))))
If the number of points (or lines) in a plot becomes large, interactions with the plot can become very slow.
A possible solution is to use toWebGL().
This produces a raster (canvas-based) version of the plot rather than the default SVG version and can be significantly faster.
