I generate a dataframe about a disease with the following variables:
- Date (date of disease)
- Cases (number of cases, by default, the number of cases is 1)
- Week (week of disease case)
- Month (month of disease case)
- Year (year of disease case).
My ui is here:
library(shiny)
library(dplyr)
library(lubridate)
library(ggplot2)
library(scales)
Disease<-data.frame(Date=seq(as.Date("2015/1/1"), as.Date("2017/1/1"), "days"),Cases=rep(1))
Disease$Week<-as.Date(cut(Disease$Date,breaks="week",start.on.monday = TRUE))
Disease$Month<-as.Date(cut(Disease$Date,breaks="month"))
Disease$Year<-as.Date(cut(Disease$Date,breaks="year"))
ui <- fluidPage(
dateRangeInput("daterange", "Choice the date",
start = min(Disease$Date),
end = max(Disease$Date),
min = min(Disease$Date),
max = max(Disease$Date),
separator = " - ", format = "dd/mm/yy",
startview = 'Month', language = 'fr', weekstart = 1),
selectInput(inputId = 'Time_unit',
label='Time_unit',
choices=c('Week','Month','Year'),
selected='Month'),
plotOutput("Disease"))
I wish to create a barplot that reacts according to the time unit (i.e. week, month, year) and that agregates data by time unit
You will find below the code of the server (but it doesn't work) :
server <- function(input, output) {
dateRangeInput<-reactive({
dataset= subset(Disease, Date >= input$daterange[1] & Date <=
input$daterange[2])
return(dataset)
})
selectInput= reactive({
summarize(group_by(dateRangeInput(),
period = switch(input$Time_unit,
"Week"=Disease$Week,
"Month" = Disease$Month,
"Year" = Disease$Year)))
})
output$Disease <-renderPlot({
ggplot(data=selectInput(), aes_string(x="period",x="Cases"))
+ stat_summary(fun.y = sum, geom = "bar")
+ labs(title="Disease", y ="Number of cases")
+theme_classic()
+theme(plot.title = element_text(hjust = 0.5))
})
}
shinyApp (ui = ui, server = server)
You will find below barplots thatI would like to obtain if I choose Week or Month or Year:
by Month: https://i.stack.imgur.com/wyWoL.png
by Week: https://i.stack.imgur.com/jAWJq.png
Sorry for "by Year", I can't to post more than 2 links
You can check this code out, it is working how You want:
Plot is reactive to the
Time_unit
input, You just need to do small adjustment with the axis text and thats it.P.S. Your second link to the image
is not working --> getting an empty space.