R Shiny 仪表板 - 如何使用 Select 框以交互方式 select x 和 y 轴绘制散点图?

R Shiny dashboard - how to interactively select x and y axis for a scatter plot using Select box?

我想构建一个交互式散点图,其中可以根据数据框中的列使用 select 框 select 编辑 x 和 y 轴。

这是使用 mtcars 的示例 - 我使用 colnames(mtcars) 获取两个 select-box 的值。但我收到以下错误: “.subset2(x, "impl")$defineOutput 中的错误:散点图的意外 gg 输出散点图的意外 ggplot 输出

我做错了什么? colnames(mtcars) 有问题吗?

library(shiny)
library(shinydashboard)
library(ggplot2)


ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(
    fluidRow(
      box(selectInput("scat_x", label = h2("select x-axis"), 
                      choices = colnames(mtcars)),
          selectInput("scat_y", label = h2("select y-axis"), 
                      choices = colnames(mtcars))),
      box(plotOutput("scatter", height = 250))
    )
    
  )
)

server <- function(input, output) {
  output$scatter<- ggplot(mtcars, aes(x=input$scat_x, y=input$scat_y)) + 
    geom_point()
}
  

shinyApp(ui, server)
  1. 要输出 ggplot,您需要将 ggplot 对象包装在 renderPlot({})
  2. 您需要使用 aes_string,因为您将列名作为字符串传递到 ggplot。
library(shiny)
library(shinydashboard)
library(ggplot2)


ui <- dashboardPage(
    dashboardHeader(),
    dashboardSidebar(),
    dashboardBody(
        fluidRow(
            box(selectInput("scat_x", label = h2("select x-axis"), 
                            choices = colnames(mtcars)),
                selectInput("scat_y", label = h2("select y-axis"), 
                            choices = colnames(mtcars))),
            box(plotOutput("scatter", height = 250))
        )
        
    )
)

server <- function(input, output) {
    output$scatter<- renderPlot({
        ggplot(mtcars, aes_string(x=input$scat_x, y=input$scat_y)) + geom_point()
    })
}


shinyApp(ui, server)