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

问题描述 投票:0回答:1

我的数据框中有两列,一列是“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)
r shiny
1个回答
1
投票
  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)
© www.soinside.com 2019 - 2024. All rights reserved.