R/Shiny/ggplot2: checkboxGroup to plot specific da

2019-09-05 00:15发布

问题:

Building from my last post I want to use selectInput to allow users to plot as many regions as they wanna plot.

My data looks like this:

Year    Ratio   Region
1983 Q1 2.9 Northern
1983 Q2 3   Northern
1983 Q3 3.1 Northern
1983 Q4 3   Northern
...
2015 Q2 5.1 UK
2015 Q3 5.1 UK
2015 Q4 5.2 UK
2016 Q1 5.2 UK

server.R snippet

houseratio <- read.csv("houseratio.csv", stringsAsFactors = FALSE)  

output$housePlot <- renderPlot({
ggplot(data=houseratio[,input$region_choose], aes(x=Year, y=Ratio, group=Region, colour=Region)) +
  geom_line() +
  geom_point()
})

ui.r snippet

checkboxGroupInput("region_choose", label = "Choose a region",
          choices = c("The North"="Northern", "Yorkshire & Humber" = "Yorks & H",
                      "North West"="NW","East Midlands"="East Mids", 
                      "West Midlands"="West Mids", "East Anglia"="East Anglia",
                      "Outer South East"="Outer SE", "Outer Met"="Outer Met", 
                      "London"="London", "South West"="SW", "Wales"="Wales",
                      "Northern Ireland"="NI", "UK"="UK")
          ),

  plotOutput("housePlot")
)

This post and this post kinda helped but as my data is in long format it didn't seem to work (also because they're selectInput but weh).

Any help would be appreciated, if I've missed anything crucial- sorry, what is it?

回答1:

1) I think your have problem in filter try

data=houseratio[houseratio$region%in%input$region_choose,]

2) better devide problem into 2 : data manipulation and plot see example

library(shiny)
library(ggplot2)
ui=shinyUI(fluidPage(checkboxGroupInput("region_choose", label = "Choose a region",
                              choices = c("setosa","versicolor","virginica")
),

plotOutput("housePlot")
))

server=function(input,output){
  #data manipulation
  data_1=reactive({
    return(iris[iris$Species%in%input$region_choose,])
  })
  #plot
  output$housePlot <- renderPlot({
    ggplot(data=data_1(), aes(x=Sepal.Length, y=Petal.Width, group=Species, colour=Species)) +
      geom_line() +
      geom_point()
  })
}

shinyApp(ui,server)


标签: r ggplot2 shiny