I need to generate a plot inside a function, relying on aes_string()
, and I need labels as rownames.
The below plot works fine, but not inside a function.
library(ggplot2)
data(mtcars)
plotfun <- function(cars) {
g <- ggplot(data = cars, aes_string(x = "mpg", y = "disp", label = "rownames(cars)"))
g <- g + geom_point()
g <- g + geom_text()
g
}
plotfun(cars = mtcars)
When run as a function, that gets me:
Error: Aesthetics must either be length one, or the same length as the dataProblems:mpg, disp
I can't wrap my head around it.
I am aware that there are plenty of similar questions about aes_string()
inside a function –– I just wasn't able to adapt their solutions to my problem.
Ps.: obviously, the above MWE is pretty stupid; in my real use-case, I run the plot through for loops, hence the need for aes_string()
.