代码之家  ›  专栏  ›  技术社区  ›  Tdebeus

列“x”、“y”必须是1d原子向量或列表

  •  0
  • Tdebeus  · 技术社区  · 8 年前

    我正在构建一个ggplot包装函数,用于多个绘图。现在我得到这个错误,我不明白。

    这是我的职责:

    library(tidyverse)
    
    plot_hist_trend <- function(df, title, subtitle = "", x_axis, y_axis, point_color) {
      df %>%
       ggplot(aes(x_axis, y_axis)) +
        geom_smooth(color = "black") +
        geom_point(color = point_color) +
        theme(legend.position = "right") +
        labs(title = title,
             subtitle = subtitle,
             x = "",
             y = "",
             caption = "Data: NOAA")
    }
    

    这是我的数据帧的一个子集。

    df <- structure(list(year = c(2018L, 2017L, 2016L, 2015L, 2014L), n = c(52L, 
    53L, 47L, 47L, 55L)), .Names = c("year", "n"), row.names = c(NA, 
    -5L), class = c("tbl_df", "tbl", "data.frame"))
    

    …但是当我绘制ggplot2对象时,我遇到了这个 1d atomic vector or list

    plot_hist_trend(df, title = "Title",
                      x_axis = year, y_axis = n,
                      point_color = "#D0021B")
    

    提前通知Tnx!

    2 回复  |  直到 8 年前
        1
  •  1
  •   Alex Yahiaoui Martinez    8 年前

    plot_hist_trend(df, title = "Title",
                x_axis =df$year, y_axis = df$n,
                point_color = "#D0021B")
    

    enter image description here

        2
  •  1
  •   PKumar    8 年前

    您可以选择使用 rlang::enexpr 或 base::substitute 如下图所示解决此问题,然后使用 aes_q 从 ggplot

    plot_hist_trend <- function(df, title, subtitle = "", x_axis, y_axis, point_color) {
        x_axis <- rlang::enexpr(x_axis)
        y_axis <- rlang::enexpr(y_axis)
        df %>%
            ggplot(aes_q(x_axis, y_axis)) +
            geom_smooth(color = "black") +
            geom_point(color = point_color) +
            theme(legend.position = "right") +
            labs(title = title,
                 subtitle = subtitle,
                 x = "",
                 y = "",
                 caption = "Data: NOAA")
    }
    

    我希望这对你有用,否则请通知。