Plotly lets users easily create interactive charts and dashboards to share online with their audience. Plotly for R is based on the open source library plotly.js. The plotly.js charts are shipped with zoom, pan, hover, and click interactions. You can click-and-drag to zoom into a region, double-click to autoscale, click on legend items to toggle traces.
You can refer to below URL for getting started with Plotly:
You can use plotly with or without ggplot. In this example, we will use plotly with ggplot.
It may ask you to confirm if you want to install from the sources. In my case, I gave n as a choice:
Do you want to install from sources the package which needs compilation?
Attach plotly library by invoking library function:
Some of the libraries in ggplot may not be in sync with the plotly libraries. In such cases you may get following error:
We recommend that you use the dev version of ggplot2 with `ggplotly()`
Install it with: `devtools::install_github('hadley/ggplot2')`
Installing dev version of ggplot2
By default, the devtools may not be in your environment. So, first install devtools package as shown below:
Now run the following command to get the development version of ggplot2:
Your first interactive plot
Run following code in the console:
> pl <- ggplot(data=mtcars, aes(x=mpg, y=wt)) + geom_point() > ggplotly(pl)
Look at the the viewer tab to see the plotly plots:
One of the thing which differentiates this very clearly is that it has a toolbar, with following controls:
Above toolbar allows great amount of interactions with the plot.
- In above example, you passed the ggplot object to the ggplotly to make the ggplot interactive
Example Usage of Plotly
Now that you have done all the hard work, let’s make use of this and see few examples.
Using Annotation and Filters
The following code applies filters where it identifies cars with 5-gears and mileage more than 20 and annotates such cars as a good mileage:
plot_ly(mtcars, x = ~wt, y = ~mpg, type='scatter') %>% filter(mpg > 20 & gear == 5) %>% add_annotations(text = "Good mileage")
Using different geometries and themes
You can use the various layers available in ggplot to make it feature rich as well as interactive. In this example, we have used geom_distogram and geom_density and overlaid them together.
p <- ggplot(mtcars, aes(mpg)) + geom_histogram(aes(y = ..density..), alpha = 0.7, fill = "#333333", bins = 10) + geom_density(fill = "#ff4d4d", alpha = 0.5) + theme(panel.background = element_rect(fill = '#aabbff')) + ggtitle("Density with Histogram overlay") p <- ggplotly(p) print(p)