3

I am trying to create a function which allows column names to be passed in by the user and I find that the resulting plot is simply one dot in the middle of screen. What needs to change for it to work as intended? My minimalist example is:

library(ggplot2)
weather <- data.frame(Month = month.name[1:5], `Low Temperature` = 20:16,
                      `High Temperature` = seq(30, 22, -2), check.names = FALSE)

xVariable <- "Month"
yVariable <- "High Temperature"
yVariable <- enquo(yVariable)
ggplot(weather, aes(x = xVariable, y = !!yVariable)) + geom_point()
0

3 Answers 3

4

Note that enquo() is only for function arguments.

If you have column names as strings, use the .data pronoun:

fn <- function(data, x, y) {
  data %>%
    ggplot(aes(x = .data[[x]], y = .data[[y]])) +
    geom_point() 
}

x <- "disp"
y <- "drat"

fn(mtcars, x, y)
Sign up to request clarification or add additional context in comments.

Comments

3

Because it's quoted text, instead of enquo, use rlang::sym

xVariable <- "Month"
yVariable <- "High Temperature"
fun <- function(dat, xvar, yvar) {
  xvar <- rlang::sym(xvar)
  yvar <- rlang::sym(yvar)
  p1 <-dat %>%
    ggplot(aes(x = !!xvar, y = !!yvar)) +
    geom_point()
  return(p1)
  
}


fun(weather, xVariable, yVariable)

enter image description here

1 Comment

I think using .data would be better. It's less technical (no !! injection) and less brittle (only scoped in the data, no risk of collisions with env-variables if the column unexpectedly doesn't exist). I have added a variant of that answer that uses .data.
2

You could use aes_string instead of aes.

library(ggplot2)
weather <- data.frame(Month = month.name[1:5], `Low Temperature` = 20:16,
                      `High Temperature` = seq(30, 22, -2), check.names = FALSE)

xVariable <- "Month"
yVariable <- "`High Temperature`"

ggplot(weather, aes_string(x = xVariable, y = yVariable)) + geom_point()

enter image description here

1 Comment

I originally had aes_string but it is deprecated since ggplot2 version 3.0.0 according to its NEWS file.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.