Shiny: passing input$var to aes() in ggplot2

前端 未结 1 1212
栀梦
栀梦 2020-11-30 09:41

I am trying to write a Shiny app graphing the density of a variable VAL, by categories of age (AGE) or sex (SEX). The user selects \"SEX\" or \"AGE\" in the dropdown menu, a

相关标签:
1条回答
  • 2020-11-30 10:05

    I'm not sure this is still an open question, but an alternative to the aes_string would be to convert the string to a symbol:

    library(ggplot2)
    
    # usually you can put all the shared aesthetics in the first line
    ggplot(mtcars, aes(mpg, hp, colour = cyl)) +
      geom_point()
    

    # when the input is a string, you can use aes_string(), but you'd
    # have to enter the string var separately, or change all vars..
    
    input <- "cyl"
    
    ggplot(mtcars, aes(mpg, hp)) +
      geom_point(aes_string(colour = input))
    
    # or
    # ggplot(mtcars, aes_string("mpg", "hp", colour = input)) +
    #  geom_point()
    

    # you can put the converted string var in the normal aes()
    ggplot(mtcars, aes(mpg, hp, colour = !!as.symbol(input))) +
      geom_point()
    
    # note: as.name() and as.symbol() are aliases
    

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

    0 讨论(0)
提交回复
热议问题