2

I am building a loop to print a series of plots to separate files in R. Everything works except that when I try to pass a variable to aes in ggplot, the geom_histogram thinks the value is now discrete.

So this works:

epdSimpleName <- c("API", "TI", "CE")

for (epdName in epdSimpleName) {
  plot <- ggplot(simpledf, aes(x=API))
  plot <- plot + geom_histogram(binwidth=5)

  print(plot)
}

but this does not:

epdSimpleName <- c("API", "TI", "CE")

for (epdName in epdSimpleName) {
  plot <- ggplot(simpledf, aes(x=epdName))
  plot <- plot + geom_histogram(binwidth=5)

  print(plot)
}

because R thinks that API, TI, etc is then discrete I guess?

Error: StatBin requires a continuous x variable: the x variable is discrete. Perhaps you want stat="count"?

Thanks for any help/guidance!

1 Answer 1

1

In this case the error message is confusing and it doesn't give a good hint about what is wrong.

The example that works specifies the aesthetic as aes(x = API). It is important that API is unquoted. The example that doesn't work in effect specifies the aesthetic as aes(x = "API") (not explicitly but that's what happens when you cycle through the loop).

So what it is necessary is to take "API" and "unquote" it. You can achieve that with !!rlang::sym("API")

library("tidyverse")

data(diamonds)

plot <- ggplot(diamonds, aes(x = x))
plot <- plot + geom_histogram()
print(plot)
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

vars <- c("x")

for (var in vars) {
  plot <- ggplot(diamonds, aes(x = !!rlang::sym(var)))
  plot <- plot + geom_histogram()
  print(plot)
}
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

Created on 2019-04-03 by the reprex package (v0.2.1)

Sign up to request clarification or add additional context in comments.

3 Comments

Worked perfect, thank you! One follow-up question. How could I have figured that out on my own? I knew that the quotes were the problem but could not find the !!rlang::sym(var) solution. Thanks again! You rock!
This is a very big topic. One place to start learning about tidy evaluation and quosures is the vignette "Programming with dplyr": cran.r-project.org/web/packages/dplyr/vignettes/…. (Even understanding what these terms mean takes some learning.) I also find this blog summary of common transformations useful: edwinth.github.io/blog/dplyr-recipes (You can find this particular transformation under the heading "character to name".)
Thanks! I'll take a look!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.