0

I am trying to use input_slider(1,10) to transform the values in my dataset by multiplying them by a selected value. For example, if the the selected value is 2, I would like the values to become 120*2, 140*2, 100*2.

Here is my example:

mydata <- data.frame(year=c(1,2,3), value=c(120,140,100))
mydata %>%
  ggvis(~year, ~value) %>%
  layer_bars()
hrbrmstr
  • 77,368
  • 11
  • 139
  • 205
Dambo
  • 3,318
  • 5
  • 30
  • 79

1 Answers1

1

One approach is to use the input_slider for y, using the map argument to multiply the slider results with your value variable.

mydata %>%
    ggvis(~year, y = input_slider(1, 10, value = 1, label = "Multiplier", 
                                    map = function(x) x*.$value)) %>% 
    layer_points()

However, this doesn't actually work with layer_bars at the moment.

You can get around this by working with layer_rects, but then you have to put in the bar width, which all works out better if year is a factor.

 mydata %>%
    ggvis(~factor(year), y = input_slider(1, 10, value = 1, label = "Multiplier", 
                                 map = function(x) x*.$value)) %>% 
    layer_rects(y2 = 0, width = band())

I did find one other alternative after finding this answer. In your case, you could use mutate to essentially recalculate your y variable and then use that in layer_bars. Note the use of eval. You can see some more examples of this approach on the help page for dplyr-ggvis (?"dplyr-ggvis").

library(dplyr)

mydata %>% 
    ggvis(~year, ~value) %>%
    mutate(value = eval(input_slider(1, 10, value = 1, label = "Multiplier"))*value) %>%
    layer_bars() 
Community
  • 1
  • 1
aosmith
  • 34,856
  • 9
  • 84
  • 118