用ggvis中的截距和斜率绘制一条线

时间:2014-07-05 08:50:25

标签: r shiny ggvis

刚开始使用Shiny。我问你:是否有可能将拦截斜率的单行添加到 ggvis 情节?

例如ggplot2使用geom_abline。

我有兴趣辩论的代码位于https://github.com/wch/movies的server.R文件中,并引用此示例http://shiny.rstudio.com/gallery/movie-explorer.html

这是绘制线条的方法

x_min <- 0
x_max <- 10

m <- 1
b <- 5

x <- c(x_min, x_max)
y <- m*x + b

df <- data.frame(x = x, y = y)

df %>% ggvis(x = ~x, y = ~y) %>% layer_lines()

但我有兴趣在现有的ggvis情节中绘制它,即上面的链接。

我应该在这里添加一些代码:

movies %>%
      ggvis(x = xvar, y = yvar) %>%
      layer_points(size := 50, size.hover := 200,
        fillOpacity := 0.2, fillOpacity.hover := 0.5,
        stroke = ~has_oscar, key := ~ID) %>%
      add_tooltip(movie_tooltip, "hover") %>%
      add_axis("x", title = xvar_name) %>%
      add_axis("y", title = yvar_name) %>%
      add_legend("stroke", title = "Won Oscar", values = c("Yes", "No")) %>%
      scale_nominal("stroke", domain = c("Yes", "No"),
        range = c("orange", "#aaa")) %>%
      set_options(width = 500, height = 500)
  })

2 个答案:

答案 0 :(得分:4)

我找到了解决方案,我感谢亲爱的朋友:

data_line <- data.frame(
  x_rng = c(0, 100), 
  y_rng = c(80, 200)
)     

movies %>%
  ggvis(x = xvar, y = yvar) %>%
  layer_points(size := 50, size.hover := 200,
    fillOpacity := 0.2, fillOpacity.hover := 0.5,
    stroke = ~has_oscar, key := ~ID) %>%
  ### A couple of ways to display lines
  layer_model_predictions(model = "lm", stroke := "red") %>%
  layer_paths(x = ~x_rng, y = ~y_rng, stroke := "blue", data = data_line) %>%
  ###
  add_tooltip(movie_tooltip, "hover") %>%
  add_axis("x", title = xvar_name) %>%
  add_axis("y", title = yvar_name) %>%
  add_legend("stroke", title = "Won Oscar", values = c("Yes", "No")) %>%
  scale_nominal("stroke", domain = c("Yes", "No"),
    range = c("orange", "#aaa")) %>%
  set_options(width = 500, height = 500)

坐标参考通常的例子http://shiny.rstudio.com/gallery/movie-explorer.html

答案 1 :(得分:2)

我对内省vis获取域名的解决方案感兴趣。

这是我想出的(也没有做到):

abline_data <- function (domain, intercept, slope) {
  data.frame(x = domain, y = domain * slope + intercept)
}

untick <- function (x) {
  # Hack to remove backticks from names
  stopifnot(all(sapply(x, is.name)))
  str_replace_all(as.character(x), "`", "")
}

layer_abline <- function (.vis, domain, intercept = 0, slope = 1) {
  df <- abline_data(domain, intercept, slope)
  names(df) <- with(.vis$cur_props, untick(c(x.update$value, y.update$value)))
  layer_paths(.vis, data = df)
}

cars %>% ggvis(x = ~speed, y = ~dist) %>% 
  layer_points() %>% 
  layer_abline(domain = c(0, 26))