R ggvis在一个计算的曲线图层中组合多个滑块

时间:2015-05-20 07:30:35

标签: r dplyr ggvis

基于我的这个问题:R ggvis interactive slider for calculating y values (e.g. for background correction),我想使用几个ggvis滑块来修改一个背景校正。

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.

如何让第二个滑块工作?可能我必须以不同方式链接mySliderA - 计算出的值,但我不知道如何。

1 个答案:

答案 0 :(得分:1)

您可以使用其他滑块的getValue属性中的observable功能。要获得两个滑块,您仍然需要使用mySliderA绘制线条,但它当然可以是透明的。

# 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")