从 Shiny 中的数据框动态更改绘图轴值

Change plot axis values dynamically from dataframe in Shiny

我在项目中使用 Rstudio 和 Shiny。

我定义了一个变量res,它包含多行多列的数据框,然后我画了一个图,它的 x y 和颜色是来自 res 数据框的数据。 我的问题是,当我 运行 它时,如果我写我想要 x 轴输入变量值 (input$SelInp),我没有得到数据帧值,相反,我只得到列名。

如果我更改代码以直接从数据帧中获取值 (res$some_column_name),我会得到正确的值。

ui.R

selectInput("SelInp",
                         label = "Choose one:",
                         choices = colnames(res)
                         )

server.R

  output$plt = renderPlot({
                  qplot(data = res,
                     x = input$SelInp, #this only returns a column name 
                     y = res$loan_amnt, # this returns correct values from column loan_amt
                     ylab = "some y axis",
                     xlab = "some x axis",
                     main="Our Chart")
                     }
                     )

所以,我想获取 input$SelInp 中的值 提前致谢

我认为原因是 selectInput 将列名称作为字符返回。 qplot 需要一个变量。我没有检查 qplot 是否可以选择使用字符来指定比例,但是 ggplot 中的 aes_string 会这样做:

ui.R

library(shiny)
library(ggplot2)

shinyUI(fluidPage(
  titlePanel("Old Faithful Geyser Data"),
  sidebarLayout(sidebarPanel(
    selectInput(
      "selectedCol",
      "Select colum for X axis",
      choices = colnames(mtcars),
      selected = colnames(mtcars)[1]
    )
  ),
  mainPanel(plotOutput("distPlot")))
))

server.R

library(shiny)
library(ggplot2)

shinyServer(function(input, output) {
  output$distPlot <- renderPlot({
    x_axis <- input$selectedCol
    gg <-
      ggplot(mtcars, aes_string(x = x_axis, y = "hp", color = "cyl"))
    gg <- gg + geom_point()
    gg
  })
})

如果有帮助请告诉我。