0

I have a tibble with more than 2 variables. I want to create a function that creates a ggplot scatterplot with the x- and y-axis being a variable from the tibble. The function parameters will take a tibble, and two string parameters corresponding to variable names e.g. plot_data(tbl_name, "var1", "var2").

Currently, I have:

plot_data <- function(data_tbl, x_axis, y_axis) {
  ggplot(
    data = data_tbl,
    mapping = aes(x = .data$x_axis, y = .data$y_axis)
  ) +
    geom_point() +
    geom_smooth()
}

When I run the function, I get the following error:

Error in geom_point(): ! Problem while computing aesthetics. ℹ Error occurred in the 1st layer. Caused by error in .data$x_axis: ! Column x_axis not found in .data.

I don't know what to do to fix this, could anyone please help?

SPAMINACAN
  • 11
  • 1

1 Answers1

0

There is a function for calling aes with string variables called aes_string(). It works like this:

plot_data <- function(data_tbl, x_axis, y_axis) {
  ggplot(
    data = data_tbl,
    mapping = aes_string(x = x_axis, y = y_axis)
  ) +
    geom_point() +
    geom_smooth()
}

plot_data(iris, "Sepal.Length", "Sepal.Width")
M.Viking
  • 5,067
  • 4
  • 17
  • 33
  • 3
    Just a note: `aes_string()` was deprecated in ggplot2 3.0.0. ℹ Please use tidy evaluation ideoms with `aes()` – benson23 Mar 06 '23 at 03:50