闪亮的应用程序情节相关问题 - 反应性

Shiny app plot related question -reactive

我的数据框中有两列,一列是“all_pass”,其中包含数值,另一列是“st_name”,其中包含字符串值状态名称

绘图的要求是,当用户输入状态时,它将显示包含 all_pass 个数字

的特定状态的绘图

以下是我尝试绘制的代码,用户将在其中输入州名,并根据州名的输入,图表将按照 all_pass 绘制根据该特定州的相关及格分数。请帮助以下代码,将有很大帮助。

代码如下:

library(ggplot2)

library(plotly)
library(dplyr)

library(shiny)



ui <- basicPage(
  h1("Total bills passed by state delegation , 110th Congress"),
  selectizeInput(inputId = "bins",label = "Choose State",
    choices = list("AK","AL","AR","AS","AZ","CA","CO","CT","DC","DE","FL","GA","GU","HI","IA","ID","IL","IN","KS","KY","LA","MA","MD","ME","MI","MN","MO","MS","MT","NC","NE","ND","NH","NJ","NM","NV","NY","OH","OK","OR","PA","PR","RI","SC","SD","TN","TX","UT","VA")  ,multiple = TRUE ,plotOutput("plot"))
  
  )
  

server <- function(input, output) {

  data <- reactive({
    require(input$bins)
    df <- df7 %>% filter(st_name %in% input$bins)
  })
    output$plot <- renderPlot({
      ggplot(df(), aes(y= all_pass,x=st_name ))+geom_bar(stat = "sum")
         })
}


shinyApp(ui = ui, server = server)
  1. 在 UI 定义中,您将 plotOutput("plot") 作为 selectizeInput() 的参数而不是 basicPage()。重新格式化您的代码 (Ctrl+Shift+A) 会使它更明显。
  2. 您可以简化服务器代码,因为 renderPlot() 已经创建了对 input$bins 的响应依赖。
  3. 您可以使用对象 datasets::state.abb 获取美国各州缩写的向量。这会在每个 R 会话中自动加载。

请查看下面的一些工作代码。我正在为 df 使用一些模拟数据,因为你没有在你的问题中提供任何数据。

library(ggplot2)
library(plotly)
library(dplyr)
library(shiny)

ui <- basicPage(
  h1("Total bills passed by state delegation, 110th Congress"),
  selectizeInput(inputId = "bins",
                 label = "Choose State",
                 choices = state.abb,
                 multiple = TRUE),
  plotOutput("plot")
  
)

server <- function(input, output) {
  
  df <- 
    tibble(all_pass = sample(1:500, 350),
           st_name = rep(state.abb, 7))

  output$plot <- renderPlot({
    req(input$bins)
    df |> 
      filter(st_name %in% input$bins) |> 
      ggplot(aes(y = all_pass,x=st_name )) + 
      geom_bar(stat = "sum")
  })
}


shinyApp(ui = ui, server = server)