【发布时间】: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 提前!
【问题讨论】:
-
将不带引号的列名传递给函数需要特殊的工作。例如,参见Programming with ggplot,尤其是“间接引用变量”部分。另请参阅Programming with dplyr Vignette。
-
那里可能有更好的规范副本,但这里有一个可能的副本:Pass column names to a function。 Pass character column names to ggplot within a function 有点过时了,因为它只提到了
aes_string方法。 -
非常感谢! @Gregor!