从selectizeInput中选择多个选项并为r

时间:2018-06-07 03:15:59

标签: r plot shiny plotly

我正在研究r中的简单折线图。现在我可以在UI部分中使用两个selectizeInputs来选择一个季节和一个团队,每个selectizeInput都有一个在select语句中用于服务器部分的ID,无论如何我想调整代码以便我可以选择多个季节和多个团队,当发生这种情况时,我想在图表上为每个团队和季节绘制多条线。我的问题是我应该在UI部分中更改什么以及我应该在服务器部分中更改什么? 非常感谢你的帮助!

这是UI部分

libraries("plotly","ggplot2","plotrix")

ui <- fluidPage(
fluidRow(
column ( width = 3,

         h4(span(tagList(icon("filter")), "Select season")),
         selectizeInput('season', "", choices = shots$SeasonNr, selected = TRUE, multiple = TRUE),
         br(),


         h4(span(tagList(icon("filter")), "Select team")),
         selectizeInput('team', "", choices = shots$TeamName, selected = TRUE, multiple = TRUE),
         br()
)),


 plotlyOutput("pos1")

)

这是我的服务器部分

server <- function(input,output, session){
  observeEvent(c(input$team), {

team1 <- input$team
Season1 <- input$season

tp <- sqldf(sprintf("select TeamName,  Training_ID, SeasonNr, Position, ShotAverage from shots where TeamName is '%s'", team1,"AND SeasonNr is '%s'", Season1))
dfNew<- aggregate(ShotAverage ~ tp$TeamName  +tp$Position, data=tp, FUN=mean)
#creates empty dataframe
dfF <- data.frame()
#bind
dfF <- rbind(dfF, dfNew)
colnames(dfF) <- c("Team Name", "Position", "Average")
 # render the plot
 output$pos1 <-renderPlotly({ 
   plot_ly(x = ~dfF$Position, y = ~dfF$Average, type = 'scatter', mode = 'bar')%>%
     layout(title = 'Seasonal team statistics', xaxis = list(title = "Position"),yaxis = list(title = "Average")) 
 })
 })}
shinyApp(ui, server)

1 个答案:

答案 0 :(得分:0)

直到您使用您的数据支持我们,我使用ggplot2

中的另一个数据集做了类似的示例
library("plotly","ggplot2","plotrix")

ui <- fluidPage(
  fluidRow(
    column ( width = 3,

             h4(span(tagList(icon("filter")), "Select season")),
             selectizeInput('season', "", choices = txhousing$year %>% unique(),selected = TRUE,  multiple = TRUE),
             br(),


             h4(span(tagList(icon("filter")), "Select city")),
             selectizeInput('city', "", choices = txhousing$city %>% unique(), selected = TRUE, multiple = TRUE),
             br()
    )),


  plotlyOutput("pos1")

)
server <- function(input,output, session){
  dta <- reactive({

    req(input$city,input$season)

    txhousing %>% 
      select(city,year,month,median) %>% 
      filter(city %in% input$city, year %in% input$season) %>% 
      group_by(city,month) %>% 
      summarise(median = mean(median))
  })
  output$pos1 <-renderPlotly({ 
    plot_ly(data = dta(),x = ~month, y = ~median,type = "area",color = ~city) %>%
      layout(title = 'Seasonal team statistics', xaxis = list(title = "Month"),yaxis = list(title = "Average")) 
  })
}
shinyApp(ui, server)

请注意,我已将您的代码分成一个被动和一个渲染语句。这是一个更好的闪亮设计,然后将所有内容放在观察者的声明中

希望这会有所帮助!!