基于R-shiny中选择的日期范围的变化图

时间:2014-11-20 05:21:51

标签: r ggplot2 shiny

我正在尝试根据Shiny中选择的日期范围改变条形图。下面是我用ggplot2获取静态图的代码。 如何使其互动以改变范围并相应地获得绘图?

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"),
     )
  )

))

数据表

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

1 个答案:

答案 0 :(得分:2)

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)

我们将days作为反应对象。然后在我们的ggplot调用中,我们调整了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)
      })
    }
  )
)