Search code examples
rshinyshinydashboardflexdashboard

Shiny and flex dashboard - struggling to add three widgets to a timeseries ggplot


my question carries on from my previous one seen here. I've been trying to build a dashboard on shiny, but I've decided to combine it with flex dashboard because it's easier and shiny has been giving a hard time.

I've created an interactive time series graph with a Country selection widget, but I'm having trouble adding date and user type selection as widgets.

My code so far:

---
title: "eServices users"
output: 
  flexdashboard::flex_dashboard: 
    orientation: row
    vertical_layout: fill
    country: ["Angola","Kenya", "South Africa"]
    source_code: embed 
    runtime: shiny 
---

```{r setup, include=FALSE, results= 'hide'}
knitr::opts_chunk$set(echo = FALSE)

library(flexdashboard)
library(rmarkdown)
library(shiny)
library(shinythemes)
library(ggplot2)
library(tidyverse)
library(readxl)
library(knitr) 

```

```{r echo=FALSE, results= 'hide'}
#Reading data

library(readr)
df <- read_delim("df.csv", 
    delim = ";", escape_double = FALSE, trim_ws = TRUE)
View(df)
```

```{r echo=FALSE, results= 'hide'}
#Cleaning data

df$date <- as.Date(df$date, format = "%Y-%m-%d")


```

## Column {.sidebar}

```{r}
#creating a sidebar where the user can choose which country they want to view 
selectInput("Country", 
label = strong("Country"), 
choices = c("All","Angola","Kenya", "South Africa"),
selected = "Angola")


## Column {.sidebar key =" value, one per line"}
#selecting dates - this isn't linked to the graphs yet
dateRangeInput("date", strong("Date range"), start = "2020-06-01", end = "2021-11-01", min = "2020-06-01", max = "2021-11-01")

#user type sidebar - isn't connected to the dashboard yet 
 checkboxGroupInput(inputId = "selected_user_type",
                  label = "Select user tpe",
            choices =c ("Active_Users","New_users","Returning_User"),
                      selected = "New_users")
```

## Column {data-width="1000"}

### Trend of eServices Users

```{r echo=FALSE}
shiny::renderPlot ({
df %>% 
    filter(str_detect(Country, if_else(input$Country == "All","",input$Country))) %>% 
    ggplot (aes( x=date, y=Count,color = Users)) +
  geom_line(size = 1) +
  scale_x_date(breaks = function(x) seq.Date(from = min(x), 
                                             to = max(x), 
                                             by = "3 month")) + 
  scale_y_continuous(breaks = scales::pretty_breaks(n = 10)) + 
  scale_colour_manual(values = c("Active_Users" = "#ffae49", "New_users" = "#44a5c2", "Returning_Users" = "#024b7a")) + 
  labs(x = "Time (date)", y = "Users") + 
  theme_classic()
})
```

I want the user to be able to filter for all the added widgets; country, date and user type.


Solution

  • Maybe this is what you are looking for. Basically I only added the filters for the user type and the date range:

    BTW: It would have been easier to run your code if you provided some example data. (;

    ---
    title: "eServices users"
    output: 
      flexdashboard::flex_dashboard: 
        orientation: row
        vertical_layout: fill
        country: ["Angola", "Kenya", "South Africa"]
        source_code: embed 
        runtime: shiny 
    ---
    
    ```{r setup, include=FALSE, results= 'hide'}
    knitr::opts_chunk$set(echo = FALSE)
    
    library(flexdashboard)
    library(rmarkdown)
    library(shiny)
    library(shinythemes)
    library(ggplot2)
    library(tidyverse)
    library(readxl)
    library(knitr)
    ```
    
    ```{r echo=FALSE, results= 'hide'}
    # Reading data
    # library(readr)
    # df <- read_delim("df.csv",
    #   delim = ";", escape_double = FALSE, trim_ws = TRUE
    # )
    # View(df)
    dates <- seq.Date(as.Date("2020-06-01"), as.Date("2021-11-01"), 40)
    n <- length(dates)
    df <- data.frame(
       date = rep(dates, 3),
       Country = rep(c("Angola", "Kenya", "South Africa"), each = n),
       Users = sample(c("Active_Users", "New_users", "Returning_User"), 3 * n, replace = TRUE),
       Count = sample(seq(20), 3 * n, replace = TRUE)
    )
    ```
    
    ## Column {.sidebar}
    
    ```{r}
    # creating a sidebar where the user can choose which country they want to view
    selectInput("Country",
      label = strong("Country"),
      choices = c("All", "Angola", "Kenya", "South Africa"),
      selected = "Angola"
    )
    
    ## Column {.sidebar key =" value, one per line"}
    
    dateRangeInput("date", strong("Date range"), start = "2020-06-01", end = "2021-11-01", min = "2020-06-01", max = "2021-11-01")
    
    checkboxGroupInput(
      inputId = "selected_user_type",
      label = "Select user tpe",
      choices = c("Active_Users", "New_users", "Returning_User"),
      selected = "New_users"
    )
    ```
    
    ## Column {data-width="1000"}
    
    ### Trend of eServices Users
    
    ```{r echo=FALSE}
    renderPlot({
      if (input$Country == "All") {
        countries <- unique(df$Country)[!df$Country %in% "All"]  
      } else {
        countries <- input$Country
      }
      
      df %>%
        filter(Country %in% countries, 
               Users %in% input$selected_user_type,
               date >= as.Date(input$date[1]),
               date <= as.Date(input$date[2])) %>%
        ggplot(aes(x = date, y = Count, color = Users)) +
        geom_line(size = 1) +
        scale_x_date(breaks = function(x) {
          seq.Date(
            from = min(x),
            to = max(x),
            by = "3 month"
          )
        }) +
        scale_y_continuous(breaks = scales::pretty_breaks(n = 10)) +
        scale_colour_manual(values = c("Active_Users" = "#ffae49", "New_users" = "#44a5c2", "Returning_Users" = "#024b7a")) +
        labs(x = "Time (date)", y = "Users") +
        theme_classic()
    })
    ```
    

    enter image description here