Tdebeus
Tdebeus

Reputation: 1599

Columns `x`, `y` must be 1d atomic vectors or lists

I'm building a ggplot wrapper function to use for multiple plots. Now I get this error which I don't understand.

This is my function:

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")
}

This is a subset of my dataframe.

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"))

...but when I plot my ggplot2 object I run into this 1d atomic vector or list error.

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

Tnx in advance!

Upvotes: 0

Views: 1543

Answers (2)

PKumar
PKumar

Reputation: 11128

You may choose to use rlang::enexpr or base::substitute to solve this problem like below and then use 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")
}

I hope this works for you, please notify in case of otherwise.

Upvotes: 1

Alex Yahiaoui Martinez
Alex Yahiaoui Martinez

Reputation: 994

try this code ! It works for me

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

enter image description here

Upvotes: 1

Related Questions