【问题标题】:Columns `x`, `y` must be 1d atomic vectors or lists列 `x`、`y` 必须是一维原子向量或列表
【发布时间】:2018-10-01 14:00:30
【问题描述】:

我正在构建一个 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 提前!

【问题讨论】:

标签: r ggplot2


【解决方案1】:

试试这个代码!它对我有用

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

【讨论】:

  • 这在这种情况下确实有效,但这是不好的做法。它基本上忽略了df 参数,并且可能会因更复杂的图而中断(例如,如果使用了stat 函数或构面)。
【解决方案2】:

您可以选择使用rlang::enexprbase::substitute 来解决这个问题,如下所示,然后使用aes_q from 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")
}

我希望这对你有用,如果不是,请通知。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-05
    • 2017-11-08
    • 1970-01-01
    • 2017-05-03
    • 2020-05-10
    • 1970-01-01
    相关资源
    最近更新 更多