Search code examples
rggplot2statisticsggvis

Is it possible with ggvis to interactively change the variables for the x and y axes?


Does anyone know if it is possible to change the variables for the x and y axis interactively with ggvis? I can change the size of the data points, their position and opacity, but I can't work out if its possible to allow the user to select a variable from a dropdown that will become the data for the x/y axis.


Solution

  • The ggvis package was designed to be used in conjunction with dplyr, e.g. to summarise data. The dplyr package also re-exports the magrittr pipe operator (%>%, see README.md), which makes working with ggvis' implementation of The Grammar of Graphics particularly intuitive (see also this article by the author of these packages, Hadley Wickham).

    Below I'll illustrate how to use the input_select() function to change the x of a model and leave the y constant.

    First we need to load the two required libraries:

    library(dplyr)
    library(ggvis)
    

    Now we can plot a data.frame (I'm using the build-in pre-loaded iris):

    iris %>% 
      ggvis(x = input_select(c('Petal.Width', 'Sepal.Length'), map = as.name)) %>% 
      layer_points(y = ~Petal.Length, fill = ~Species)
    

    The output is:

    input_select = Petal.Width

    using the input_select this can be changed to:

    input_select = Sepal.Length

    If you prefer not to use dplyr / magrittr it would look like this:

    p <- ggvis(iris, x = input_select(c('Petal.Width', 'Sepal.Length'), map = as.name))
    layer_points(p, y = ~Petal.Length, fill=~Species)