【问题标题】:How to create a barchart with plotly? [duplicate]如何使用 plotly 创建条形图? [复制]
【发布时间】:2021-05-18 12:49:25
【问题描述】:

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

代码

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)

【问题讨论】:

    标签: r shiny plotly


    【解决方案1】:

    this post 之后,第二种选择是像这样使用as.formula

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-03-09
        • 2020-10-20
        • 2021-10-25
        • 2021-11-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-05
        相关资源
        最近更新 更多