首页 > 解决方案 > 通过 selectInput 带引号的绘图选项

问题描述

我正在尝试通过 selectInput 生成一个 ggplot 选择“位置”变量,其中包含一个引号。

我已经尝试使用 paste0 或“和”的不同组合,运气很好。

在 ui.R 方面:

selectInput("posicion","Visualizar Barras",
     list ("Agrupadas"= 'position_dodge2(preserve = "single")',
       "Sumadas"="stack")))

在 server.R 端:

output$g_virus_x_semana.1 <- renderPlot({
      ggplot(subset(v,  v$año==input$año.1 & Virus %in% input$virus), aes(semana, fill=Virus))+
        geom_bar(position = input$posicion, stat = "count")+
        scale_x_discrete(drop=FALSE)+
        scale_fill_virus()+theme_dark()+labs(y = "N° de virus identificados", x= "Semana")

如果我选择“Agrupadas”,我会得到:Error in : Can't find `position` called "position_dodge2(preserve = "single")"

如果将position_dodge2(preserve = "single")直接放在 de ggplot 代码部分中,效果就像魅力一样。

标签: rggplot2shiny

解决方案


一种选择是创建一个基于 的反应函数input$posicion来更改您添加到绘图的图层。

selectInput()可能看起来像

selectInput(inputId = "posicion", label = "Visualizar barras",
                                    choices = list("Agrupadas",
                                                   "Sumadas") )

然后,server您可以根据所做的选择添加有关要添加到绘图中的图层的信息。请注意,整个图层都存储在列表中以添加到绘图中。

server = function(input, output) {

    bartype = reactive({
        if(input$posicion == "Agrupadas") {                     
            list( geom_bar(position = position_dodge(preserve = "single"), stat = "count") )
            }
        else {
            list( geom_bar(position = "stack", stat = "count") )
        }
    })

    # Create scatterplot object the plotOutput function is expecting
    output$lineplot = renderPlot({
        ggplot(mtcars, aes(factor(gear), fill = factor(cyl) ) ) +
            bartype()
    })

}

推荐阅读