我正在构建一个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!
答案 0 :(得分:1)
尝试此代码!它对我有用
plot_hist_trend(df, title = "Title",
x_axis =df$year, y_axis = df$n,
point_color = "#D0021B")
答案 1 :(得分:1)
您可以选择使用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")
}
我希望这对您有用,否则请通知。