首页 > 解决方案 > 我的第一个 R Shiny,我如何将 selectinput 与 renderplot(ggplot) 结合起来?

问题描述

我想将 selectinput 与渲染图(ggplot)结合起来。我想制作我选择的年份和月份的条形图。如果我选择 select year(yil) 2009 并选择 month(ay) 2 ,情节就像必须显示我的选择。这就像过滤器,也许我不知道如何解决这个问题。我的数据网格中的年份和月份值,我分享了我的数据图片

我的 ui.R ;

library(shiny)
library(ggplot2)


shinyUI(fluidPage(

    titlePanel(title=h4("Norvec Arac Satıs Verisi 2007-2016",align="center")),

    sidebarLayout(
        sidebarPanel(
            selectInput("yil","1.Yıl Seçiniz",
                        choices = list("2007"=1,"2008"=2,"2009"=3,"2010"=4,"2011"=5,"2012"=6,"2013"=7,"2014"=8,"2015"=9,"2016"=10)),
            sliderInput("ay","2. Ay Seçiniz",min = 1,max = 12,value = 1,step = 1,
                        animate = animationOptions(interval=800,loop = FALSE, playButton = "OYNAT", pauseButton = "DUR"))

            ),

        mainPanel(
            tabsetPanel(type="tab",
                        tabPanel("Grafik",plotOutput("bar"))

            )
        )


    )
))

我的服务器.R;

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


shinyServer(function(input,output){

  output$bar <- renderPlot({
    ggplot(data=carsales,aes(x = Brand, y = Quantity, group = Brand, color = Brand, fill=Brand)) +
      geom_bar(stat = "identity")


  })



})

闪亮的:

闪亮的

我的数据:

我的数据

我的数据:

    > head(carsales)
  Year Month      Brand Quantity
1 2007     1     Toyota     2884
2 2007     1 Volkswagen     2521
3 2007     1    Peugeot     1029
4 2007     1       Ford      870
5 2007     1      Volvo      693
6 2007     1      Skoda      665

标签: rggplot2plotshinybar-chart

解决方案


您可以制作反应式数据集

carsales_subset <- reactive({
                           carsales %>% filter(Year==input$yil, Month==input$ay)
                           })

然后通过 ggplot 函数传递它

output$bar <- renderPlot({
    ggplot(data=carsales_subset(),aes(x = Brand, y = Quantity, group = Brand, color = Brand, fill=Brand)) +
      geom_bar(stat = "identity")


  })

推荐阅读