aes_string()内部的小数位值 [英] Scale value inside of aes_string()

查看:70
本文介绍了aes_string()内部的小数位值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过在ggplot中乘以一个数字(例如10)来缩放y-var.问题在于这是在Shiny应用程序中,变量必须作为字符串传递,即input$variable.

I want to scale my y-var by multiplying it by a number, say 10, in ggplot. The problem is this is in a Shiny app and the variable must be passed as a character string, i.e. input$variable.

如何像在aes()中那样将aes_string()中的变量之一相乘?这是一个失败时的示例:

How can I multiply one of the variables in aes_string() the same way I would in aes()? Here is an example of when it fails:

 library(ggplot2)
 ggplot(data = subset(mtcars, cyl == 4), aes_string(x = "wt", y = "mpg")) + 
      geom_line(size = 1.5, color = "#00868B") + 
      geom_line(data = subset(mtcars, cyl == 8), aes_string(x = "wt", y = "mpg" * 10))

"mpg"中的错误* 10:二进制运算符的非数字参数

Error in "mpg" * 10 : non-numeric argument to binary operator

推荐答案

您可以使用tidyeval方法-0-0/"rel =" nofollow noreferrer> ggplot2 v3.0.0

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)

reprex程序包(v0.2.0)创建于2018-06-06.

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

这篇关于aes_string()内部的小数位值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆