Anish
Anish

Reputation: 1950

Vary plots based on date range selected in R-shiny

I am trying to vary the barplot based on the date range selected in Shiny. Below is the code that I used to get a static plot using ggplot2. How can I make it interactive to vary the ranges and get plot accordingly?

server.R

library(RMySQL)

con <- dbConnect(MySQL(), user="xxx", host="xxx", password="xxx", dbname="xxx")
query <- function(...) dbGetQuery(con, ...)

days <-   query("SELECT date(date) as Date,  count(*) as Count FROM article 
    where date BETWEEN NOW() - INTERVAL 30 DAY AND NOW() group by date(date)")

shinyServer(function(input, output) {
   #Each day plot
  output$days.plot <- renderPlot({    
    days.plot<-ggplot(data=days, aes(x=Date, y=Count)) + geom_bar(stat="identity")    
    days.plot<-days.plot + theme(axis.text.x = element_text(angle = 45, hjust = 1))
    days.plot<-days.plot+ggtitle("example.com\nStories Published Per Day \n[For     Last 30 Days]")
    print(days.plot)
  })
}

ui.R

library(shiny)
library(ggplot2)

shinyUI(fluidPage(
  titlePanel("My APP"),
  sidebarLayout(
    sidebarPanel(
      sliderInput("Days-Range",
              label="Range of Days:",
              min=0,max=30, value = c(0,30))
      ),
    mainPanel(

      plotOutput("days.plot"),
     )
  )

))

Data Table

Date    Count
2014-10-21  179
2014-10-22  140
2014-10-23  225
2014-10-24  248
2014-10-25  137
2014-10-26  116

Upvotes: 1

Views: 2331

Answers (1)

jdharrison
jdharrison

Reputation: 30425

library(shiny)
library(ggplot2)
read.table(text = 'Date    Count
2014-10-21  179
2014-10-22  140
2014-10-23  225
2014-10-24  248
2014-10-25  137
2014-10-26  116', header = TRUE, stringsAsFactor = FALSE) -> days
days$Date <- as.Date(days$Date)

Herer we make days a reactive object. Then within our ggplot call we condition on the sliderInput:

runApp(
  list(
    ui = fluidPage(
      titlePanel("My APP"),
      sidebarLayout(
        sidebarPanel(
          sliderInput("Days-Range",
                      label="Range of Days:",
                      min=0,max=30, value = c(0,30))
        ),
        mainPanel(
          plotOutput("days.plot")
        )
      )
    )
    , server = function(input, output) {
      myReactives <- reactiveValues(days = days)
      output$days.plot <- renderPlot({    
        appDates <- seq(Sys.Date() - input$`Days-Range`[2], Sys.Date() - input$`Days-Range`[1], by = "days")
        appData <- myReactives$days[myReactives$days$Date %in% appDates, ]
        days.plot<-ggplot(data=appData, aes(x=Date, y=Count)) + geom_bar(stat="identity")    
        days.plot<-days.plot + theme(axis.text.x = element_text(angle = 45, hjust = 1))
        days.plot<-days.plot+ggtitle("example.com\nStories Published Per Day \n[For     Last 30 Days]")
        print(days.plot)
      })
    }
  )
)

Upvotes: 2

Related Questions