代码之家  ›  专栏  ›  技术社区  ›  stackinator Brenton Wiernik

R dplyr-如何取消引用一个输入,使其得到评估,而不是引用-特别是ggplot coord\u cart()

  •  0
  • stackinator Brenton Wiernik  · 技术社区  · 7 年前
    library(tidyverse)
    df <- tibble(
      date = as.Date(41000:41050, origin = "1899-12-30"), 
      value = c(rnorm(25, 5), rnorm(26, 10))
      )
    

    我首先在上面创建我的数据。然后我尝试创建一个函数,除其他外,它可以改变ggplot的坐标比例。

    scatter_plot_cart <- function(data, x, y) {
      x <- enquo(x)
      y <- enquo(y)
      ggplot(data, aes(!!x, !!y)) + 
        geom_point() + 
        coord_cartesian(xlim = c(min(data$(!!x)) + 100, max(data$(!!x)) - 100))
    }
    
    scatter_plot_cart(df, date, value)
    

    c(最小值(数据$(“>}错误:“}”中出现意外的“}”

    我从错误中猜到我没有引用 x 在我的生活中 coord_cartesian()

    ggplot(df, aes(date, value)) + 
      geom_point() + 
      coord_cartesian(xlim = c(min(df$date) + 100, max(df$date) - 100))
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Maurits Evers    7 年前

    我会预先计算轴的极限

    scatter_plot_cart <- function(data, x, y) {
        x <- enquo(x)
        y <- enquo(y)
        xlim <- c(
            data %>% pull(!!x) %>% min() + 100,
            data %>% pull(!!x) %>% max() - 100)
        ggplot(data, aes(!!x, !!y)) +
            geom_point() +
            coord_cartesian(xlim = xlim)
    }
    
    scatter_plot_cart(df, date, value)
    

    enter image description here

    推荐文章