Shiny in Flexdashboard with conditional plot

I have hotel reservation dataset which consists of "book_date", "check_in", "check_out" and "revenue". I would like to draw 2 charts - "revenue by booking date" vs "revenue by check-in date"; which I could highlight/zoom in particular booking period (says Jan 2018) to understand revenue for corresponding check-in period (says Feb - Apr 2018).

I try to achieve this by incorporating Shiny "brush" in R Flexdashboard. The idea is that, when nothing is "brush" on "revenue by booking date", "revenue by check-in date" will show a default chart (i.e. revenue for all check-in date). If user zoom in a period in "revenue by booking date", "revenue by check-in date" will react accordingly. However, the default display for "revenue by check-in date" is not working as expected.

Below are my codes:

library(flexdashboard) 
library(shiny)
library(tidyverse)
library(lubridate)
library(timetk)
library(scales)
library(plotly)

  1. revenue by booking date

shiny::plotOutput(outputId = "revenue_book", brush = brushOpts(id = "brush", direction = "x"))

plot time series

output$revenue_book <- shiny::renderPlot(
df %>% filter(book_year == 2018) %>%
group_by(book_date) %>%
summarise(revenue = sum(price)) %>%
ungroup() %>%
ggplot(aes(book_date, revenue)) + geom_line() + geom_point(color = "red") + theme_bw()
)

  1. revenue by check-in date

shiny::renderPlot({

if (is.null(input$brush$xmin)) {
p <- df %>% filter(book_date == 2018) %>%
group_by(check_in) %>% summarise(revenue = sum(price)) %>% ungroup()
p %>% ggplot(aes(check_in, revenue)) + geom_line() + geom_point(color = "blue") + theme_bw()
}
else {
q <- df %>% filter(between(book_date, input$brush$xmin, input$brush$xmax)) %>%
group_by(check_in) %>% summarise(revenue = sum(price)) %>% ungroup()

q %>% ggplot(aes(check_in, revenue)) + geom_line() + geom_point(color = "blue") + theme_bw()

}
})

Default chart is not displayed...

Please advise me what could be the issue.

I think you need to use lubridate::year(book_date) == 2018 to filter the year - currently you are filtering out all the points

Hi @slodge, thanks for your advice. I'm new to R and made such silly mistake. I spend few nights looking around for work around.

I've been using R for 3 years... I make worse silly mistakes every day... and often spend nights looking for fixes :slight_smile:

The nights aren't wasted though - while trying fixes, I learn lots :slight_smile:

Good luck - and thanks for investing the time in writing a good question - the fact you included a good description, the code and the images helped me see the problem :+1:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.