Search code examples
rdplyrggvis

R ggvis Combining multiple sliders in one calculated curve layer


Based on this question of mine: R ggvis interactive slider for calculating y values (e.g. for background correction), I would like to use several ggvis sliders to modify one background correction.

library("dplyr")
library("ggvis")
library("lubridate")
data <- data.frame(timestamp = Sys.time() - hours(10:1),
                   signal = rnorm(10),
                   temperature = rnorm(10),
                   secondParameter = rnorm(10))

# mySliderA works fine
mySliderA <- input_slider(0, 2, value = 0, step = 0.1, label = "T-correction", 
                         map = function(x)  data$signal - x * data$temperature)
# mySliderB wants to add a second parameter to the calculation based on mySliderA, this fails.
mySliderB <- input_slider(0, 2, value = 0, step = 0.1, label = "P2-correction", 
                          map = function(x2)  mySliderA - x2 * data$secondParameter )

data %>% 
  ggvis() %>%
  layer_paths(x = ~timestamp, y = ~signal,      stroke := "darkgreen") %>%
  layer_paths(x = ~timestamp, y = ~temperature, stroke := "red") %>%
  # layer_paths(... y = mySliderA, ...) # would work, but:
  layer_paths(x = ~timestamp, y = mySliderB,    stroke := "darkblue")
  # does not.

How can I get the second slider to work? Probably, I have to link the mySliderA-calculated values differently, but I don't know how.


Solution

  • You can use the getValue function from the observable attribute of the other slider. To get both sliders, you still need to plot the line with mySliderA, but it can of course be transparent.

    # mySliderA 
    mySliderA <- input_slider(0, 2, value = 0, step = 0.1, label = "T-correction", 
                              map = function(x)  data$signal - x * data$temperature)
    
    # mySliderB using `attr(mySliderA, "observable")$getValue()`
    mySliderB <- input_slider(0, 2, value = 0, step = 0.1, label = "P2-correction", 
                              map = function(x2)  attr(mySliderA, "observable")$getValue() -
                                x2 * data$secondParameter)
    # plotting
    data %>% 
      ggvis() %>%
      layer_paths(x = ~timestamp, y = ~signal,      stroke := "darkgreen") %>%
      layer_paths(x = ~timestamp, y = ~temperature, stroke := "red") %>%
      layer_paths(x = ~timestamp, y = mySliderA, stroke := "transparent")  %>% 
      layer_paths(x = ~timestamp, y = mySliderB, stroke := "darkblue")