afg
March 14, 2023, 7:46pm
1
I'm trying to write a function for ggplot to define aes arguments. But I get errors running it since the internal column headings are not objects in themselves like the data frame is. For example:
df <- data.frame(conc = c(2, 3, 3.7), abs = c(0.2, 0.31, 0.33))
ggplot(df, aes(x = conc, y = abs)) + geom_point()
plot <- function(a, b, c) {
ggplot(a, aes(x = b, y = c)) + geom_point()
}
plot(df, conc, abs)
Is there any way to define aes this way using a function?
FJCC
March 14, 2023, 8:16pm
2
Here are two solutions.
library(ggplot2)
df <- data.frame(conc = c(2, 3, 3.7), abs = c(0.2, 0.31, 0.33))
ggplot(df, aes(x = conc, y = abs)) + geom_point()
#Solution #1
plotFunc <- function(a, b, c) {
ggplot(a, aes_string(x = b, y = c)) + geom_point()
}
plotFunc(df, "conc", "abs")
#Solution #2
library(rlang)
plotFunc2 <- function(a, b, c) {
ggplot(a, aes(x = {{b}}, y = {{c}})) + geom_point()
}
plotFunc2(df, conc, abs)
Created on 2023-03-14 with reprex v2.0.2
afg
March 15, 2023, 5:36pm
3
Ah first time I have encountered aes_string and those issues. Very helpful thank you!
If you happen to know a resource you can point me to understand {{}} I would appreciate it. Googling operators is always a problem
I think textbook wise this is the best approach Introduction | Advanced R (hadley.nz)
Theres also rlang (r-lib.org) if you look at the top links under "Tidy Evaluation" and "Metaprogramming"
1 Like
system
Closed
March 22, 2023, 5:52pm
5
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed. If you have a query related to it or one of the replies, start a new topic and refer back with a link.