首页 > 解决方案 > 如何使用 plotly 创建条形图?

问题描述

我正在尝试使用用户输入生成条形图。我尝试~在输入之前使用,但它不起作用。我看到的是带有轴标签的空白画布。

在此处输入图像描述

代码

library(shiny)
library(plotly)

ui <- fluidPage(
  titlePanel(tags$h4("Bar Chart")),
  sidebarLayout(
  sidebarPanel(selectInput("input1", label = NULL, choices = names(mtcars)),
               selectInput("input2", label = NULL, choices = names(mtcars))),
  mainPanel(plotlyOutput("bar"))
)
)

server <- function(input, output, session) {
  
  
  output$bar <- renderPlotly(
    mtcars %>% 
      plot_ly(
        x = ~input$input1,
        y = ~input$input2,
        
        type = "bar"
      )
  )
  
}

shinyApp(ui, server)

标签: rshinyplotly

解决方案


您可以使用get()将输入变量转换为 plotly 可以使用的东西。在你的情况下试试这个:

 output$bar <- renderPlotly(
     mtcars %>% 
         plot_ly(
             x = ~get(input$input1),
             y = ~get(input$input2),
             
             type = "bar"
         )

推荐阅读