Scale value inside of aes_string()

天大地大妈咪最大 提交于 2019-11-28 13:04:03

You can use tidyeval approach introduced in ggplot2 v3.0.0

# install.packages("ggplot2", dependencies = TRUE)
library(ggplot2)

var1 <- "wt"
var2 <- "mpg"
multiplier <- 10

ggplot(data = subset(mtcars, cyl == 4), 
       aes(x = !! rlang::sym(var1), y = !! rlang::sym(var2))) + 
  geom_line(size = 1.5, color = "#00868B") + 
  geom_line(data = subset(mtcars, cyl == 8), 
            aes(x = !! rlang::sym(var1), y = !! rlang::sym(var2) * multiplier))

Or put everything in a function

plot_select_vars <- function(var1, var2, multiplier) {

  var1 <- rlang::sym(var1)
  var2 <- rlang::sym(var2)

  ggplot(data = subset(mtcars, cyl == 4), 
         aes(x = !! var1, y = !! var2)) + 
    geom_line(size = 1.5, color = "#00868B") + 
    geom_line(data = subset(mtcars, cyl == 8), 
              aes(x = !! var1, y = !! var2 * multiplier))

}

plot_select_vars(var1, var2, multiplier)

Created on 2018-06-06 by the reprex package (v0.2.0).

I prefer to use get instead of aes_string to call variables inside ggplot2 and it works with value modification, for example:

library(ggplot2)
X <- "wt"
Y <- "mpg"
ggplot(subset(mtcars, cyl == 4), aes(get(X), get(Y))) + 
    geom_line() + 
    geom_line(data = subset(mtcars, cyl == 8), aes(y = get(Y) * 10)) +
    labs(x = X,
         y = Y)

PS: you don't need to call wt in second aes as it's the same "variable" as in first aes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!