在ggvis中绘制带有截距和斜率的直线。

4
刚开始使用Shiny。我问你:是否可以在ggvis图中添加由截距斜率特征的单条线?
例如,使用geom_abline在ggplot2中。
我感兴趣的代码位于server.R文件中,位于https://github.com/wch/movies,并涉及此示例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个回答

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


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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接