【问题标题】:Passing a selectInput() value (a choice between column names) as an axis to ggplot() in Shiny将 selectInput() 值(列名之间的选择)作为轴传递给 Shiny 中的 ggplot()
【发布时间】:2020-12-03 00:04:10
【问题描述】:

ggplot 只显示一条垂直线,当我尝试更改 x 轴选择时,该值不会改变。当我尝试更改 x 轴时,x 轴上唯一的内容是“列”一词,而不是根据所选内容的 df$column 值。

df_variable <- df

df_colnames <- colnames(df)

xaxis_input <- selectInput(
  inputId = "xaxis",
  label = "Feature of Interest",
  choices = df_colnames,
  selected = df_colnames['default']
)

ui <- fluidPage(
  titlePanel("DF"),
  xaxis_input,
  plotOutput(
    outputId = "df_plot",
  )
)

server <- function(input, output) {
  output$df_plot <- renderPlot({
    plot <- ggplot(data = df) +
      geom_point(aes(x = input$xaxis, y = some_other_col))
    
    return(plot)
  })
}

【问题讨论】:

    标签: r ggplot2 shiny


    【解决方案1】:

    input$xaxis 是一个字符串,所以不能直接在aes() 中使用。

    尝试改用aes_string()。

    注意some_other_col 也应该是一个字符串。

    server <- function(input, output) {
    
      output$df_plot <- renderPlot({
        plot <- ggplot(data = df) +
          geom_point(aes_string(x = input$xaxis, y = "some_other_col"))
    
        return(plot)
    
      })
    

    一个完整的工作示例:

    library(shiny)
    library(ggplot2)
    
    df <- iris
    df_colnames <- colnames(df)
    
    xaxis_input <- selectInput(
        inputId = "xaxis",
        label = "Feature of Interest",
        choices = df_colnames
    )
    
    ui <- fluidPage(
            titlePanel("DF"),
            xaxis_input,
            plotOutput(
            outputId = "df_plot",
        )
    )
    
    server <- function(input, output) {
    
        output$df_plot <- renderPlot({
            plot <- ggplot(data = df) +
                geom_point(aes_string(x = input$xaxis, y = "Sepal.Width"))
        
            return(plot)
        })
    }
    
    # Run the application 
    shinyApp(ui = ui, server = server)
    

    【讨论】:

    • 谢谢!很高兴知道。
    猜你喜欢
    • 2017-04-22
    • 2015-05-12
    • 1970-01-01
    • 2014-12-03
    • 2019-01-19
    • 1970-01-01
    • 2021-03-24
    • 2016-07-31
    相关资源
    最近更新 更多