简体   繁体   中英

ggvis: Transforming numeric values in the dataset using a slider

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()

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() 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM