Site icon R-bloggers

Make your R plots interactive

[This article was first published on Apply R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
As a part of my daily job, I draw scatterplots, lots of them. And because there are thousands of genes expressed in any mouse or human tissue, my typical plot looks something like this (code). (Actually, it is a comparison of variance that can be attributed to “sex” factor in mRNA vs. protein expression.)

The question is – what is a gene in the top right corner? And what is the one next to him? And this one? And that?

What we need is a clickable scatterplot. Something I can point with a mouse and get a corresponding gene name. Then click and my browser would open a window with the gene’s details (for example in Ensemble). And thanks to ggvis package, it is now possible. Try the following code:


In the case above there must be R running somewhere behind, translating points to gene symbols and Ensemble links. How to share this figure to somebody who does not have R on his or her machine? One possibility is to run it on shinyapps.io or your private shiny server (see below, Enseble links stop working). If it stucks try to reload the page!




The second way to add interactive annotation is iplot function in the new Karl Broman’s interactive testjs package. It produces Javascipt widget that can be easily saved and share as html page (code).




And with a little help of shiny, we can do even more: Mike Love has a nice example (mtcars_demo in his Github repository), see the widget below. Clicking on a dot in a left panel makes the corresponding dot in the right panel highlighted (the trick is to use clickId option in  shiny::plotOutput).




Mike’s approach is similar to identify function in basic graphics. The output is a position on an image and you need to find the nearest point yourself.

I tried something similar with ggvis that makes SVG objects so you can set up “on_click” or “on_hoover” events directly (see mtcars_demo here). Click either on left or right panel and the corresponding dot in the opposite panel will be highlighted.




For more complex visualisations, D3.js is a must. However, if you just need to add a bit of interactivity to your R plots, thanks to ggvis, shiny, htmlwidgets, … it is now possible.

To leave a comment for the author, please follow the link and comment on their blog: Apply R.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.