How to make interactive plots in R


  R Interview Questions

Base R as well as ggplot does not have interactive plots. You can use third party libraries like plotly to produce interactive plots. Say, you have a data frame like this and you want to do an (x,y) interactive plot

1. Using PLOTLY

> data
    x   y
1   1   1
2   2   4
3   3   9
4   4  16
5   5  25
6   6  36
7   7  49
8   8  64
9   9  81
10 10 100

Step 1 – Start by making a plot in ggplot

> ggplot = ggplot(data,aes(x,y)) + geom_point()

Step 2 – pass this object to the GGPLOTLY() function

> ggplotly = ggplotly(ggplot)

That’s it.

2. Using GGVIS

ggvis is another interactive graphing package from the makers of R studio. For example, the same plot can be made in GGVIS as below (for the same set of data).

> ggplot = ggvis(data, x = ~x, y = ~y )
> layer_points(ggplot)
> layer_points(ggplot) %>% add_tooltip(function(data) data$x)

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.