R shinydashboard + highcharter: arguments are not named in hc_add_series - r

I'm trying to create a dashboard where a state can be selected and the graph is updated by that selection, but I get this error:
'Warning: Error in : 'df', 'hcaes(x = date, y = injured)' arguments
are not named in hc_add_series [No stack trace available]'
library(tidyverse)
library(shiny)
library(shinydashboard)
library(highcharter)
ui <- dashboardPage(dashboardHeader(title = 'Test Dashboard'),
dashboardSidebar(),
dashboardBody(fluidPage(selectInput('select',
label = 'States',
choices = unique(opts),
selected = 'Alabama'),
box(title = "Stock",
status = "primary",
solidHeader = TRUE,
collapsible = TRUE,
highchartOutput('plot')))))
server <- function(input,
output) {
output$plot <- renderHighchart({
df <- reactive({
df <- massShooting2018.order %>%
filter(state %in% input$select) %>%
group_by(date) %>%
summarise(
dead = sum(dead),
injured = (sum(injured)),
total = sum(total)
)
})
highchart(type = "stock") %>%
hc_chart("line",
name = "base",
hcaes(x = date)
) %>%
hc_add_series(df,
name = "Total",
type = "line",
hcaes(
x = date,
y = total
)
) %>%
hc_add_series(df,
name = "Dead",
type = "line",
hcaes(
x = date,
y = dead
)
) %>%
hc_add_series(df,
name = "Injured",
type = "line",
hcaes(
x = date,
y = injured
)
) %>%
hc_tooltip(
crosshairs = TRUE,
shared = TRUE,
borderWidth = 2,
table = TRUE
)
})
}
shinyApp(ui, server)
DataSource
using the previous dataset:
massShooting2018 <- read.csv('shootings_2018.csv')
massShooting2018.clean <- massShooting2018 %>%
clean_names() %>%
mutate(date = dmy(date))
massShooting2018.order <- massShooting2018.clean %>%
group_by(date, state) %>%
summarise(dead = sum(dead),
injured = sum(injured),
total = sum(total),
description, .groups = 'drop')
opts <- massShooting2018.order %>%
sample_frac(1) %>%
select(state) %>%
arrange(state)
Thank you very much for reading and I hope I can solve this problem.

The call of df after reactive function should be df():
library(tidyverse)
library(shiny)
library(shinydashboard)
library(highcharter)
library(janitor)
library(lubridate)
massShooting2018 <- read.csv('shootings_2018.csv')
massShooting2018.clean <- massShooting2018 %>%
clean_names() %>%
mutate(date = dmy(date))
massShooting2018.order <- massShooting2018.clean %>%
group_by(date, state) %>%
summarise(dead = sum(dead),
injured = sum(injured),
total = sum(total),
description, .groups = 'drop')
opts <- massShooting2018.order %>%
sample_frac(1) %>%
select(state) %>%
arrange(state)
ui <- dashboardPage(dashboardHeader(title = 'Test Dashboard'),
dashboardSidebar(),
dashboardBody(fluidPage(selectInput('select',
label = 'States',
choices = unique(opts),
selected = 'Alabama'),
box(title = "Stock",
status = "primary",
solidHeader = TRUE,
collapsible = TRUE,
highchartOutput('plot')))))
server <- function(input,
output)
{
output$plot <- renderHighchart({
df <- reactive({df <- massShooting2018.order %>%
filter(state %in% input$select) %>%
group_by(date) %>%
summarise(dead = sum(dead),
injured = (sum(injured)),
total = sum(total))})
highchart(type = 'stock') %>%
hc_chart('line',
name = 'base',
hcaes(x = date)) %>%
hc_add_series(df(),
name = 'Total',
type = 'line',
hcaes(x = date,
y = total)) %>%
hc_add_series(df(),
name = 'Dead',
type = 'line',
hcaes(x = date,
y = dead)) %>%
hc_add_series(df(),
name = 'Injured',
type = 'line',
hcaes(x = date,
y = injured)) %>%
hc_tooltip(crosshairs = TRUE,
shared = TRUE,
borderWidth = 2,
table = TRUE)})
}
shinyApp(ui, server)

Related

R + Highcharter + ShinyDashboard: How to add mouseOver event?

I am trying to make it so that when the client puts the mouse cursor over a value in the line graph, a text is created indicating the information of a column.
This is my code:
DataSource
library(tidyverse)
library(janitor)
library(lubridate)
library(highcharter)
library(shiny)
library(shinydashboard)
massShooting2018 <- read.csv('shootings_2018.csv')
massShooting2019 <- read.csv('shootings_2019.csv')
massShooting2020 <- read.csv('shootings_2020.csv')
massShooting2021 <- read.csv('shootings_2021.csv')
massShooting2022 <- read.csv('shootings_2022.csv')
# Merge datasets
massShootings <- rbind(massShooting2018,
massShooting2019,
massShooting2020,
massShooting2021,
massShooting2022)
# Clean
massShootings.clean <- massShootings %>%
clean_names() %>%
mutate(date = dmy(date))
massShootings.order <- massShootings.clean %>%
group_by(date, state) %>%
summarise(dead = sum(dead),
injured = sum(injured),
total = sum(total),
description, .groups = 'drop')
years <- massShootings.order %>%
sample_frac(1) %>%
select(date) %>%
mutate(date = year(date)) %>%
arrange(date)
hc_my_theme <- hc_theme_merge(hc_theme_flatdark(),
hc_theme(chart = list(backgroundColor = '#242f39'),
subtitle = list(style = list(color = '#a7a5a5'))))
header <- dashboardHeader(title = 'Mass Shootings')
sideBar <- dashboardSidebar(sidebarMenu(menuItem('Description', tabName = 'info', icon = icon('info')),
menuItem('Charts', tabName = 'charts', icon = icon('chart-line')),
menuItem('Contact', tabName = 'contact', icon = icon('address-card'))))
body <- dashboardBody(fluidPage(valueBoxOutput('totals'),
valueBoxOutput('dead'),
valueBoxOutput('injured')),
fluidPage(column(width = 4,
offset = 4,
selectInput('year',
label = 'Year',
choices = unique(years),
selected = 2018,
width = "100%"))),
box(title = "USA-States Map",
status = "primary",
solidHeader = TRUE,
collapsible = TRUE,
highchartOutput('mapPlot')),
box(title = 'Mass shootings in every state over time',
status = "primary",
solidHeader = TRUE,
collapsible = TRUE,
highchartOutput('linePlot')))
ui <- dashboardPage(header,
sideBar,
body)
server <- function(input,
output,
session)
{
df <- reactive({df <- massShootings.order %>%
filter(year(date) == input$year) %>%
group_by(state) %>%
summarise(dead = sum(dead),
injured = sum(injured),
total = sum(total),
description, .groups = 'drop')})
# Map Chart
output$mapPlot <- renderHighchart({
fn <- "function(){
console.log(this.name);
Shiny.onInputChange('mapPlotinput', this.name)
}"
hcmap(map = 'countries/us/custom/us-all-mainland.js',
data = df(),
joinBy = c('name', 'state'),
value = 'total',
borderWidth = 0.05,
nullColor = "#d3d3d3") %>%
hc_title(text = 'Mass Shooting') %>%
hc_colorAxis(stops = color_stops(colors = viridisLite::viridis(10,
begin = 0.1)),
type = "logarithmic") %>%
hc_tooltip(formatter= JS("function () { return this.point.name.bold() +
' <br />' +
' <br /> <b>Dead:</b> ' + this.point.dead +
' <br /> <b>Injured:</b> ' + this.point.injured ;}")) %>%
hc_add_theme(hc_my_theme) %>%
hc_mapNavigation(enabled = TRUE) %>%
hc_credits(enabled = FALSE) %>%
hc_exporting(enabled = TRUE) %>%
hc_plotOptions(series = list(cursor = "pointer",
point = list(events = list(click = JS(fn)))))})
# Stock chart
output$linePlot <- renderHighchart({
nme <- ifelse(is.null(input$mapPlotinput),
"United States of America",
input$mapPlotinput)
dfClick <- massShootings.order %>%
filter(state %in% nme) %>%
filter(year(date) == input$year) %>%
group_by(date) %>%
summarise(dead = sum(dead),
injured = sum(injured),
total = sum(total),
.groups = 'drop')
highchart(type = "stock") %>%
hc_chart("line",
name = "base",
hcaes(x = date)) %>%
hc_add_series(dfClick,
name = "Total",
type = "line",
hcaes(
x = date,
y = total)) %>%
hc_add_series(dfClick,
name = "Dead",
type = "line",
hcaes(
x = date,
y = dead)) %>%
hc_add_series(dfClick,
name = "Injured",
type = "line",
hcaes(
x = date,
y = injured)) %>%
hc_add_theme(hc_theme_538()) %>%
hc_tooltip(
crosshairs = TRUE,
shared = TRUE,
borderWidth = 2,
table = TRUE)})
# valueBox - Total
output$totals <- renderValueBox({dfTotals <- massShootings.order%>%
filter(year(date) == input$year) %>%
group_by(date) %>%
summarise(total = sum(dead, injured))
valueBox(sum(dfTotals$total), 'Total', icon = icon('calculator') ,color = 'light-blue')})
# valueBox - Deads
output$dead <- renderValueBox({dfDeads <- massShootings.order %>%
filter(year(date) == input$year) %>%
group_by(date) %>%
summarise(dead = sum(dead))
valueBox(sum(dfDeads$dead), 'Deads', icon = icon('skull') ,color = 'red')})
# valueBox - Injureds
output$injured <- renderValueBox({dfInjureds <- massShootings.order %>%
filter(year(date) == input$year) %>%
group_by(date) %>%
summarise(injured = sum(injured))
valueBox(sum(dfInjureds$injured), 'Injureds', icon = icon('user-injured') ,color = 'yellow')})
}
shinyApp(ui, server)
So far you can interact with the map which, when clicking on each state, creates a line graph next to it showing the values per day throughout the selected year.
What I am trying to achieve is that when the client places the cursor on the values of the graph line, text is created where the description of what happened on that date is shown, but the truth is that I do not know how to achieve it.
Thank you very much for reading my question and I would appreciate any kind of help to solve this problem

plotly shiny reactive values "error function not found"

I'm working on a Shiny app in which I want to drill down into a plot with multiple levels. I am having difficulty getting the reactiveValues function to work so I can update the plot. If I set selections <- reactiveVal() I get no errors, but nothing happens when I click on the plot. On the other hand, if I use selections <- reactiveValues() I get the error "Error in selections: could not find function "selection""
Based on reading other posts, it seems like my problem is likely having to do with how exactly I set the update to the variable but I can't quite figure out how to fix it / where the issue is in my code.
Here is a reproducible example:
library(bs4Dash)
library(plotly)
library(tidyverse)
fake_data_wide <- tibble(level_1 = rep(c("A", "B", "C"), each = 50),
level_2 = rep(c(c("1", "2"), c("3", "4"), c("5", "6")), each = 25),
level_3 = c(rep("a", 40), rep("b", 10), rep("c", 30), rep("d", 20),
rep("e", 20), rep("f", 30)),
sent = rnorm(150),
number = rpois(150, lambda = 1))
fake_data_long <- fake_data_wide %>%
pivot_longer(level_1:level_3, names_to = "level_of_specificity",
values_to = "group_name")
one_level_down <- fake_data_wide %>%
select(group_name = level_1,
one_down = level_2) %>%
bind_rows(fake_data_wide %>%
select(group_name = level_2,
one_down = level_3)) %>% distinct()
ui <- dashboardPage(
header = dashboardHeader(title = "test"),
sidebar = dashboardSidebar(),
body = dashboardBody(fluidRow(box(plotlyOutput("drill_down_plot"),
id = "test_box"),
uiOutput("back")))
)
server <- function(input, output){
selections <- reactiveValues()
observeEvent(event_data("plotly_selected", source = "drill_down_plot"), {
new <- event_data("plotly_selected")$customdata[[1]]
old <- selections()
selections(c(old, new))
})
output$drill_down_plot <- renderPlotly({
if(length(selections() == 0)){
fake_data_long %>%
filter(level_of_specificity == "level_1") %>%
group_by(group_name) %>%
summarise(g_sent_mean = mean(sent),
g_total_mean = mean(number)) %>% ungroup() %>%
plot_ly(x = ~g_sent_mean, y = ~g_total_mean,
size = ~g_total_mean, customdata = ~group_name)
} else {
one_level_down %>%
filter(group_name %in% selections_test) %>%
mutate(group_name = one_down) %>% select(-one_down) %>%
inner_join(fake_data_long) %>%
group_by(group_name) %>%
summarise(g_sent_mean = mean(sent),
g_total_mean = mean(number)) %>% ungroup() %>%
plot_ly(x = ~g_sent_mean, y = ~g_total_mean,
size = ~g_total_mean, customdata = ~group_name)
}
})
output$back <- renderUI({
if (length(selections()))
actionButton("clear", "Back", icon("chevron-left"))
})
}
shinyApp(ui = ui, server = server)
The following should help you.
library(bs4Dash)
library(plotly)
library(tidyverse)
fake_data_wide <- tibble(level_1 = rep(c("A", "B", "C"), each = 50),
level_2 = rep(c(c("1", "2"), c("3", "4"), c("5", "6")), each = 25),
level_3 = c(rep("a", 40), rep("b", 10), rep("c", 30), rep("d", 20),
rep("e", 20), rep("f", 30)),
sent = rnorm(150),
number = rpois(150, lambda = 1))
fake_data_long <- fake_data_wide %>%
pivot_longer(level_1:level_3, names_to = "level_of_specificity",
values_to = "group_name")
one_level_down <- fake_data_wide %>%
dplyr::select(group_name = level_1, one_down = level_2) %>%
bind_rows(fake_data_wide %>%
dplyr::select(group_name = level_2, one_down = level_3)) %>% distinct()
ui <- dashboardPage(
header = dashboardHeader(title = "test"),
sidebar = dashboardSidebar(),
body = dashboardBody(fluidRow(box(plotlyOutput("drill_down_plot"),
id = "test_box"),
uiOutput("back")))
)
server <- function(input, output){
my <- reactiveValues(selections=NULL)
observeEvent(event_data("plotly_selected", source = "drill_down_plot", priority = "event"), {
my$selections <- event_data("plotly_selected", priority = "event")$customdata[[1]]
old <- my$selections
#print(my$selections) # c(old, new)
}, ignoreNULL = FALSE)
output$drill_down_plot <- renderPlotly({
select_data <- event_data("plotly_selected", priority = "event")
my$selections <- select_data$customdata
print(select_data)
if (is.null(select_data)) {
print("hello1")
df1 <- fake_data_long %>%
dplyr::filter(level_of_specificity == "level_1") %>%
group_by(group_name) %>%
dplyr::summarise(g_sent_mean = mean(sent),
g_total_mean = mean(number)) %>% ungroup() # %>%
# plot_ly(x = ~g_sent_mean, y = ~g_total_mean,
# size = ~g_total_mean, customdata = ~group_name)
} else {
print("hello2")
df1 <- one_level_down %>%
dplyr::filter(group_name %in% select_data$customdata) %>%
mutate(group_name = one_down) %>% dplyr::select(-one_down) %>%
inner_join(fake_data_long) %>%
group_by(group_name) %>%
dplyr::summarise(g_sent_mean = mean(sent),
g_total_mean = mean(number)) %>% ungroup() #%>%
# plot_ly(x = ~g_sent_mean, y = ~g_total_mean,
# size = ~g_total_mean, customdata = ~group_name)
}
plot_ly(df1, x = ~g_sent_mean, y = ~g_total_mean,
size = ~g_total_mean, customdata = ~group_name) %>% layout(dragmode = "lasso")
})
output$back <- renderUI({
if (!is.null(my$selections)) actionButton("clear", "Back", icon("chevron-left"))
})
}
shinyApp(ui = ui, server = server)

Using both hc_motion and hc_drilldown in R Highcharter Map

I am trying to use both hc_motion and hc_drilldown within a highcharter map.
I can manage to get the hc_motion working with the full map, and also a drilldown from a larger area to its smaller ones (UK Region to Local Authority in this instance).
However, after drilling-down and zooming back out again, the hc_motion is now frozen.
Why is this and is there anyway around it? Or are hc_motion and hc_drilldown not compatible?
While in this instance the drilldown is static, if it possible hc_motion within each drilldown would be ideal, although will no even bother trying if even a static can't be incorporated without affecting the hc_motion.
Anyway, example code is below, thanks!
region_lad_lookup = read_csv("https://opendata.arcgis.com/api/v3/datasets/6a41affae7e345a7b2b86602408ea8a2_0/downloads/data?format=csv&spatialRefId=4326") %>%
clean_names() %>%
select(
region_code = rgn21cd,
region_name = rgn21nm,
la_name = lad21nm,
la_code = lad21cd,
value = fid
) %>%
inner_join(
read_sf("https://opendata.arcgis.com/api/v3/datasets/21f7fb2d524b44c8ab9dd0f971c96bba_0/downloads/data?format=geojson&spatialRefId=4326") %>%
clean_names() %>%
filter(grepl("^E", lad21cd)) %>%
select(la_code = lad21cd),
by = "la_code"
)
region_map = read_sf("https://opendata.arcgis.com/api/v3/datasets/bafeb380d7e34f04a3cdf1628752d5c3_0/downloads/data?format=geojson&spatialRefId=4326") %>%
clean_names() %>%
select(
area_code = rgn18cd,
area_name = rgn18nm
) %>%
st_as_sf(crs = 27700) %>%
sf_geojson() %>%
fromJSON(simplifyVector = F)
year_vec = c(2015, 2016, 2017, 2018, 2019)
region_data = region_lad_lookup %>%
select(
area_code = region_code,
area_name = region_name
) %>%
distinct() %>%
crossing(year_vec) %>%
mutate(
value = runif(nrow(.)),
drilldown = tolower(area_name)
)
region_vec = region_data %>%
select(area_name) %>%
distinct() %>%
pull()
get_la_map = function(data, region_val){
data = data %>%
filter(region_name == region_val) %>%
select(
area_code = la_code,
area_name = la_name,
geometry
) %>%
st_as_sf(crs = 27700) %>%
sf_geojson() %>%
fromJSON(simplifyVector = F)
return(data)
}
get_la_data = function(data, region_val){
data = data %>%
filter(region_name == region_val) %>%
select(
area_name = la_name,
area_code = la_code,
value
)
return(data)
}
get_region_map_list = function(region_val){
output = list(
id = tolower(region_val),
data = list_parse(get_la_data(region_lad_lookup, region_val)),
mapData = get_la_map(region_lad_lookup, region_val),
name = region_val,
value = "value",
joinBy = "area_name"
)
return(output)
}
region_ds = region_data %>%
group_by(area_name) %>%
do(
item= list(
area_name = first(.$area_name),
sequence = .$value,
value = first(.$value),
drilldown = first(.$drilldown)
)
) %>%
.$item
highchart(type = "map") %>%
hc_add_series(
data = region_ds,
mapData = region_map,
value = "value",
joinBy = "area_name",
borderWidth = 0
) %>%
hc_colorAxis(
minColor = "lightblue",
maxColor = "red"
) %>%
hc_motion(
enabled = TRUE,
axisLabel = "year",
series = 0,
updateIterval = 200,
magnet = list(
round = "floor",
step = 0.1
)
) %>%
hc_drilldown(
allowPointDrilldown = TRUE,
series = lapply(region_vec, get_region_map_list)
)

Shiny app does not work once deployed - rnaturalearthhires?

I have built a shiny dashboard with Covid19 data for Switzerland.
The dashboard works well when I run it from RStudio, but after being deployed I get this:
**An error has occurred
The application failed to start: exited unexpectedly with code 1
Attaching package: ‘dplyr’
The following objects are masked from ‘package:stats’:
filter, lag
The following objects are masked from ‘package:base’:
intersect, setdiff, setequal, union
Loading required package: ggplot2
Attaching package: ‘plotly’
The following object is masked from ‘package:ggplot2’:
last_plot
The following object is masked from ‘package:stats’:
filter
The following object is masked from ‘package:graphics’:
layout
Registered S3 method overwritten by 'quantmod':
method from
as.zoo.data.frame zoo
── Attaching packages ─────────────────────────────────────── tidyverse 1.3.0 ──
✔ tibble 3.0.3 ✔ stringr 1.4.0
✔ tidyr 1.1.2 ✔ forcats 0.5.0
✔ purrr 0.3.4
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ plotly::filter() masks dplyr::filter(), stats::filter()
✖ dplyr::lag() masks stats::lag()
Attaching package: ‘lubridate’
The following objects are masked from ‘package:base’:
date, intersect, setdiff, union
Linking to GEOS 3.5.1, GDAL 2.2.2, PROJ 4.9.2
Attaching package: ‘maps’
The following object is masked from ‘package:purrr’:
map
Google's Terms of Service: https://cloud.google.com/maps-platform/terms/.
Please cite ggmap if you use it! See citation("ggmap") for details.
Attaching package: ‘ggmap’
The following object is masked from ‘package:plotly’:
wind
Attaching package: ‘shinydashboard’
The following object is masked from ‘package:graphics’:
box
Attaching package: ‘rsconnect’
The following object is masked from ‘package:shiny’:
serverInfo
Parsed with column specification:
cols(
date = col_date(format = ""),
time = col_time(format = ""),
abbreviation_canton_and_fl = col_character(),
ncumul_tested = col_double(),
ncumul_conf = col_double(),
new_hosp = col_double(),
current_hosp = col_double(),
current_icu = col_double(),
current_vent = col_double(),
ncumul_released = col_double(),
ncumul_deceased = col_double(),
source = col_character(),
current_isolated = col_double(),
current_quarantined = col_double(),
current_quarantined_riskareatravel = col_double(),
TotalPosTests1 = col_character(),
ninst_ICU_intub = col_character()
)
Warning: 8254 parsing failures.
row col expected actual file
1 -- 17 columns 15 columns 'https://raw.githubusercontent.com/openZH/covid_19/master/COVID19_Fallzahlen_CH_total_v2.csv'
2 -- 17 columns 15 columns 'https://raw.githubusercontent.com/openZH/covid_19/master/COVID19_Fallzahlen_CH_total_v2.csv'
3 -- 17 columns 15 columns 'https://raw.githubusercontent.com/openZH/covid_19/master/COVID19_Fallzahlen_CH_total_v2.csv'
4 -- 17 columns 15 columns 'https://raw.githubusercontent.com/openZH/covid_19/master/COVID19_Fallzahlen_CH_total_v2.csv'
5 -- 17 columns 15 columns 'https://raw.githubusercontent.com/openZH/covid_19/master/COVID19_Fallzahlen_CH_total_v2.csv'
... ... .......... .......... .............................................................................................
See problems(...) for more details.
The rnaturalearthhires package needs to be installed.
Installing the rnaturalearthhires package.
Error in value[[3L]](cond) :
Failed to install the rnaturalearthhires package.
Please try installing the package for yourself using the following command:
install.packages("rnaturalearthhires", repos = "http://packages.ropensci.org", type = "source")
Calls: local ... tryCatch -> tryCatchList -> tryCatchOne -> <Anonymous>
Execution halted**
It seems like the rnaturalearthhires package is the problem, but I doi not need it to build the leaflet maps and tu run the app on RStudio. I have tried to call library(rnaturalearthhires) in the shiny dashboard code and even to add install.packages("rnaturalearthhires", repos = "http://packages.ropensci.org", type = "source"), but it does not work, I get an error message even before the end of deployment.
Does anyone had the same problem or know where is the issue?
Thanks
Here is the code for the app:
library(readr)
library(readxl)
library(dplyr)
library(plotly)
library(forcats)
library(ggplot2)
library(tidyverse)
library(lubridate)
library(rnaturalearth)
library(rnaturalearthdata)
library(sf)
library(maps)
library(gifski)
library(leaflet)
library(ggmap)
library(htmlwidgets)
library(htmltools)
library(leaflet.extras)
library(purrr)
library(shiny)
library(shinydashboard)
library(RColorBrewer)
library(rsconnect)
# Data sets
# Load Covid data for Switzerland from GitHub repository
data_swiss <- read_csv("https://raw.githubusercontent.com/openZH/covid_19/master/COVID19_Fallzahlen_CH_total_v2.csv")
# Load Canton population data from excell csv file made from Wikipedia data
canton_swiss <- read_xlsx("swiss_cantons.xlsx")
# Load Switzerland spatial data (canton polygons)
switzerland <- ne_states(country = 'switzerland', returnclass = 'sf')
switzerland <- st_as_sf(switzerland)
# Join data frames
data_swiss = left_join(data_swiss, canton_swiss, by = c(abbreviation_canton_and_fl = "Canton_abbr"))
# Modify dataframe by adding more variables
data_swiss <- data_swiss %>% group_by(abbreviation_canton_and_fl) %>%
mutate(new_cases = ncumul_conf - lag(ncumul_conf, default = first(ncumul_conf), order_by = date))
data_swiss <- data_swiss %>% group_by(abbreviation_canton_and_fl) %>%
mutate(new_deaths = ncumul_deceased - lag(ncumul_deceased, default = first(ncumul_deceased), order_by = date))
data_swiss <- data_swiss %>%
mutate(pop_10thous = Pop/10000)
data_swiss <- data_swiss %>%
mutate(new_cases_per_10thous = new_cases/pop_10thous)
data_swiss <- data_swiss %>%
mutate(new_deaths_per_10thous = new_deaths/pop_10thous)
data_swiss <- data_swiss %>%
mutate(new_cases_smoothed = zoo::rollmean(new_cases, k = 7, fill = NA))
data_swiss <- data_swiss %>%
mutate(new_deaths_smoothed = zoo::rollmean(new_deaths, k = 7, fill = NA))
data_swiss <- data_swiss%>%
mutate(ncumul_deceased_per_10thous = ncumul_deceased/pop_10thous)
data_swiss <- data_swiss%>%
mutate(ncumul_conf_per_10thous = ncumul_conf/pop_10thous)
# Merge with geo data
data_swiss_geo <- left_join(switzerland, data_swiss, by = c(postal = "abbreviation_canton_and_fl"))
# Create new data frame with Switzerland totals
data_swiss_noNA <- data_swiss %>%
mutate_if(is.numeric, funs(ifelse(is.na(.), 0, .)))
switzerland_new_cases <- data_swiss_noNA %>%
group_by(date) %>%
summarize(switzerland_new_cases = sum(new_cases, na.rm = TRUE))
switzerland_new_cases_smoothed <- data_swiss_noNA %>%
group_by(date) %>%
summarize(switzerland_new_cases_smoothed = sum(new_cases_smoothed, na.rm = TRUE)) %>%
select(-date)
switzerland_new_deaths <- data_swiss_noNA %>%
group_by(date) %>%
summarize(switzerland_new_deaths = sum(new_deaths, na.rm = TRUE))%>%
select(-date)
switzerland_new_deaths_smoothed <- data_swiss_noNA %>%
group_by(date) %>%
summarize(switzerland_new_deaths_smoothed = sum(new_deaths_smoothed, na.rm = TRUE)) %>%
select(-date)
data_total_swiss <- cbind(switzerland_new_cases, switzerland_new_cases_smoothed, switzerland_new_deaths, switzerland_new_deaths_smoothed)
# Calculate trend
tot14days_last <- data_swiss %>%
group_by(abbreviation_canton_and_fl) %>%
filter(date <= max(date), date >= max(date)-14) %>%
summarize(tot14days_last = sum(new_cases, na.rm = TRUE))
tot14days_previous <- data_swiss %>%
group_by(abbreviation_canton_and_fl) %>%
filter(date <= max(date)-15, date >= max(date)-29) %>%
summarize(tot14days_previous = sum(new_cases, na.rm = TRUE)) %>%
select(-abbreviation_canton_and_fl)
trend <- cbind(tot14days_last, tot14days_previous)
trend <- trend %>%
mutate(change_percemt = round((tot14days_last-tot14days_previous)/tot14days_last*100, 0))
trend_swiss_geo <- left_join(switzerland, trend, by = c(postal = "abbreviation_canton_and_fl"))
trend <- left_join(canton_swiss, trend, by = c(Canton_abbr = "abbreviation_canton_and_fl"))
# App
header <- dashboardHeader(title = "Covid-19 Switzerland")
sidebar <- dashboardSidebar(
sidebarMenu (
menuItem("Timeline", tabName = "Timeline", icon = icon("calendar-alt")),
menuItem("Maps and Stats", tabName = "Maps", icon = icon("chart-bar")),
menuItem("14 days trend", tabName = "Trend", icon = icon("chart-line")),
menuItem("About", tabName = "About", icon = icon("comment-alt")),
menuItem("Source code", icon = icon("code"),
href = "https://github.com/vivvi87/Swiss-Covid-Shiny-Dashboard"),
menuItem("Source data", icon = icon("database"),
href = "https://github.com/openZH/covid_19")
)
)
body <- dashboardBody(
tabItems(
tabItem(tabName = "Timeline",
fluidRow(
valueBoxOutput("box_cases"),
valueBoxOutput("box_deaths"),
valueBoxOutput("box_canton")
),
fluidRow(
tabBox(width = 10, title ="Switzerland Covid-19 timeline",
tabPanel("Cases", plotlyOutput("swiss_timeline")),
tabPanel("Deaths", plotlyOutput("swiss_timeline_d"))
),
box(width = 2,
sliderInput("dates", "Select dates:",
min(data_total_swiss$date), max(data_total_swiss$date),
value = c(as.Date("2020-09-20"), max(data_total_swiss$date))
)
)
),
fluidRow(
tabBox(width = 10, title ="Swiss cantons Covid-19 timeline",
tabPanel("Cases", plotlyOutput("canton_timeline")),
tabPanel("Deaths", plotlyOutput("canton_timeline_d"))
),
box(width = 2,
sliderInput("dates_canton", "Select dates:",
min(data_swiss$date), max(data_swiss$date),
value = c(as.Date("2020-09-20"), max(data_swiss$date))
),
selectInput("canton", "Select canton:",
selected = "Geneva",
choices = c(levels(as.factor(data_swiss$Canton))),
multiple = FALSE
)
)
)
),
tabItem(tabName = "Maps",
fluidRow(
tabBox(title = "Total cases",
tabPanel("Absolute", leafletOutput("map_cases_abs")),
tabPanel("Every 10000 people", leafletOutput("map_cases"))
),
tabBox(title = "Total deaths",
tabPanel("Absolute", leafletOutput("map_deaths_abs")),
tabPanel("Every 10000 people", leafletOutput("map_deaths"))
)
),
fluidRow(
tabBox(title = "Total cases",
tabPanel("Absolute", plotlyOutput("cases_abs")),
tabPanel("Every 10000 people", plotlyOutput("cases"))
),
tabBox(title = "Total deaths",
tabPanel("Absolute", plotlyOutput("deaths_abs")),
tabPanel("Every 10000 people", plotlyOutput("deaths"))
)
)
),
tabItem(tabName = "About",
fluidRow(
box(width = 12,
h2("About"),
"This dashboard has been built using the data found in the GitHub repository ", em("https://github.com/openZH/covid_19"), " which collect Covid-19 data for Switzerland and Lichtenstain.",
"The data is updated at best once a day at varying times, but in order to avoid missing values and errors, the data in Maps and stats are displayed with a 2 days delay, as indicated when hovering on the data.",
"The data analysis as well as the source code of the dashboard can be found at ", em("https://github.com/vivvi87/Swiss-Covid-Shiny-Dashboard"), ". Both source code and data can be directly accessed from the sidebar."
)
)
),
tabItem(tabName = "Trend",
fluidRow(
valueBoxOutput("swiss_trend")
),
fluidRow(
box(title = "Map - 14 days variation %", width = 6,
leafletOutput("variation_map")
),
box(title = "Chart - 14 days variation %", width = 6,
plotlyOutput("variation_chart")
)
),
fluidRow(
DT::dataTableOutput("trend_table")
)
)
)
)
server <- function(input, output) {
output$swiss_timeline <- renderPlotly({
data_total_swiss %>%
filter(date >= input$dates[1] & date <= input$dates[2]) %>%
plot_ly() %>%
add_bars(x = ~date,
y = ~switzerland_new_cases,
color = I("black"),
opacity = 0.5,
text = ~paste(date, "<br>", "New cases: ", round(switzerland_new_cases, 1)),
hoverinfo = "text",
name = "New cases") %>%
add_lines(x = ~date,
y = ~switzerland_new_cases_smoothed,
color = I("orange"),
text = ~paste(date, "<br>", "New cases (7-days average): ", round(switzerland_new_cases_smoothed, 0)),
hoverinfo = "text",
name = "new cases (7-days average)") %>%
layout(yaxis = list(title = "Number of Covid-19 cases",
showgrid = F,
range = c(0, 11500)),
xaxis = list(title = " "),
legend = list(x = 0, y = 1)) %>%
config(displayModeBar = FALSE, displaylogo = FALSE)
})
output$swiss_timeline_d <- renderPlotly({
data_total_swiss %>%
filter(date >= input$dates[1] & date <= input$dates[2]) %>%
plot_ly() %>%
add_bars(x = ~date,
y = ~switzerland_new_deaths,
color = I("black"),
opacity = 0.5,
text = ~paste(date, "<br>", "New deaths: ", round(switzerland_new_deaths, 1)),
hoverinfo = "text",
name = "New deaths") %>%
add_lines(x = ~date,
y = ~switzerland_new_deaths_smoothed,
color = I("orange"),
text = ~paste(date, "<br>", "New deaths (7-days average): ", round(switzerland_new_deaths_smoothed, 0)),
hoverinfo = "text",
name = "new deaths (7-days average)") %>%
layout(yaxis = list(title = "Number of deaths",
showgrid = F,
range = c(0, 125)),
xaxis = list(title = " "),
legend = list(x = 0, y = 1)) %>%
config(displayModeBar = FALSE, displaylogo = FALSE)
})
output$canton_timeline <- renderPlotly({
data_swiss %>%
filter(date >= input$dates_canton[1] & date <= input$dates_canton[2]) %>%
filter(Canton == input$canton) %>%
plot_ly() %>%
mutate(Canton = as.character(Canton)) %>%
add_lines(x = ~date,
y = ~new_cases,
fill = "tozeroy",
fillcolor= 'rgba(153,102,204,0.5)',
line = list(color = 'rgba(153,102,204,0.6)'),
text = ~paste(Canton, "<br>", "Date: ", date, "<br>", "New Cases: ", new_cases),
hoverinfo = "text") %>%
layout(yaxis = list(title = "Number of Covid-19 Cases",
showgrid = F),
xaxis = list(title = " ", showgrid = F)) %>%
config(displayModeBar = FALSE, displaylogo = FALSE)
})
output$canton_timeline_d <- renderPlotly({
data_swiss %>%
filter(date >= input$dates_canton[1] & date <= input$dates_canton[2]) %>%
filter(Canton == input$canton) %>%
plot_ly() %>%
mutate(Canton = as.character(Canton)) %>%
add_lines(x = ~date,
y = ~new_deaths,
fill = "tozeroy",
fillcolor= 'rgba(153,102,204,0.5)',
line = list(color = 'rgba(153,102,204,0.6)'),
text = ~paste(Canton, "<br>", "Date: ", date, "<br>", "New deaths: ", new_deaths),
hoverinfo = "text") %>%
layout(yaxis = list(title = "Number of deaths",
showgrid = F),
xaxis = list(title = " ", showgrid = F)) %>%
config(displayModeBar = FALSE, displaylogo = FALSE)
})
output$variation_map <- renderLeaflet({
rc1 <- colorRampPalette(colors = c("purple", "white"), space = "Lab")(length(which(trend_swiss_geo$change_percemt < 0)))
rc2 <- colorRampPalette(colors = c("moccasin", "orange"), space = "Lab")(length(which(trend_swiss_geo$change_percemt > 0)))
rampcols <- c(rc1, rc2)
pal <- colorNumeric(palette = rampcols, domain = trend_swiss_geo$change_percemt)
trend_swiss_geo %>%
leaflet(options = leafletOptions(minZoom = 7.2)) %>%
setView(lat = 46.9, lng = 8.3, zoom = 7.2) %>%
addProviderTiles("CartoDB") %>%
addPolygons(fillColor = ~pal(change_percemt),
weight = 1,
opacity = 1,
color = "white",
dashArray = "3",
fillOpacity = 0.7,
highlight = highlightOptions(weight = 2,
color = "#666",
dashArray = "",
fillOpacity = 0.7,
bringToFront = TRUE),
label = ~paste0(name_en, ": ",
round(change_percemt, 0), " %")) %>%
addLegend(pal = pal,
values = ~change_percemt,
opacity = 0.7,
title = NULL,
position = "bottomright")
})
output$variation_chart <- renderPlotly({
trend %>%
plot_ly() %>%
add_bars(x = ~Canton,
y= ~change_percemt,
color = ~change_percemt < 0, colors = c("darkorange3", "mediumpurple3"),
opacity = 0.6,
text = ~paste(Canton, "<br>", round(change_percemt, 0), "% variation"),
hoverinfo = "text") %>%
layout(yaxis = list(title = "14 days variation %",
showgrid = F),
xaxis = list(title = " ",
showgrid = F)) %>%
hide_legend() %>%
config(displayModeBar = FALSE, displaylogo = FALSE)
})
output$map_cases_abs <- renderLeaflet({
data_swiss_geo_last <- data_swiss_geo %>%
filter(date == max(date)-2)
labels2 <- sprintf(
"%s<br/><strong>%s</strong><br/> %s total Covid-19 cases",
data_swiss_geo_last$date, data_swiss_geo_last$Canton, data_swiss_geo_last$ncumul_conf
) %>% lapply(htmltools::HTML)
data_swiss_geo_last %>%
leaflet(options = leafletOptions(minZoom = 7.2)) %>%
setView(lat = 46.9, lng = 8.3, zoom = 7) %>%
addProviderTiles("CartoDB") %>%
addPolygons(weight = 1, col = "grey") %>%
addCircleMarkers(~longitude, ~latitude,
radius = ~data_swiss_geo_last$ncumul_conf/2200,
stroke = TRUE,
color = "orange",
weight = 2,
fillOpacity = 0.5,
label = labels2)
})
output$map_cases <- renderLeaflet({
data_swiss_geo_last <- data_swiss_geo %>%
filter(date == max(date)-2)
labels1 <- sprintf(
"%s<br/><strong>%s</strong><br/> %s Covid-19 cases every 10000 people",
data_swiss_geo_last$date, data_swiss_geo_last$Canton, round(data_swiss_geo_last$ncumul_conf_per_10thous,0)
) %>% lapply(htmltools::HTML)
data_swiss_geo_last %>%
leaflet(options = leafletOptions(minZoom = 7.2)) %>%
setView(lat = 46.9, lng = 8.3, zoom = 7) %>%
addProviderTiles("CartoDB") %>%
addPolygons(weight = 1, col = "grey") %>%
addCircleMarkers(~longitude, ~latitude,
radius = ~(data_swiss_geo_last$ncumul_conf_per_10thous/50),
stroke = TRUE,
color = "orange",
weight = 2,
fillOpacity = 0.5,
label = labels1)
})
output$map_deaths_abs <- renderLeaflet({
data_swiss_geo_last <- data_swiss_geo %>%
filter(date == max(date)-2)
labels4 <- sprintf(
"%s<br/><strong>%s</strong><br/> %s total deaths",
data_swiss_geo_last$date, data_swiss_geo_last$Canton, data_swiss_geo_last$ncumul_deceased
) %>% lapply(htmltools::HTML)
data_swiss_geo_last %>%
leaflet(options = leafletOptions(minZoom = 7.2)) %>%
setView(lat = 46.9, lng = 8.3, zoom = 7) %>%
addProviderTiles("CartoDB") %>%
addPolygons(weight = 1, col = "grey") %>%
addCircleMarkers(~longitude, ~latitude,
radius = ~data_swiss_geo_last$ncumul_deceased/40,
stroke = TRUE,
color = "mediumorchid",
weight = 2,
fillOpacity = 0.4,
label = labels4)
})
output$map_deaths <- renderLeaflet({
data_swiss_geo_last <- data_swiss_geo %>%
filter(date == max(date)-2)
labels3 <- sprintf(
"%s<br/><strong>%s</strong><br/> %s deaths every 10000 people",
data_swiss_geo_last$date, data_swiss_geo_last$Canton, round(data_swiss_geo_last$ncumul_deceased_per_10thous,0)
) %>% lapply(htmltools::HTML)
data_swiss_geo_last %>%
leaflet(options = leafletOptions(minZoom = 7.2)) %>%
setView(lat = 46.9, lng = 8.3, zoom = 7) %>%
addProviderTiles("CartoDB") %>%
addPolygons(weight = 1, col = "grey") %>%
addCircleMarkers(~longitude, ~latitude,
radius = ~data_swiss_geo_last$ncumul_deceased_per_10thous,
stroke = TRUE,
color = "mediumorchid",
weight = 2,
fillOpacity = 0.4,
label = labels3)
})
output$cases_abs <- renderPlotly({
data_swiss %>%
plot_ly() %>%
filter(date == max(date)-2) %>%
add_bars(x = ~reorder(Canton, -ncumul_conf),
y = ~ncumul_conf,
color = I("black"),
opacity = 0.5,
hoverinfo = "text",
text = ~paste(date, "<br>", Canton, "<br>", ncumul_conf, "total cases")) %>%
layout(yaxis = list(title = "Total Covid-19 cases", showgrid = F),
xaxis = list(title = " ")) %>%
config(displayModeBar = FALSE, displaylogo = FALSE)
})
output$cases <- renderPlotly({
data_swiss %>%
plot_ly() %>%
filter(date == max(date)-2) %>%
add_bars(x = ~reorder(Canton, -ncumul_conf_per_10thous),
y = ~ncumul_conf_per_10thous,
color = I("black"),
opacity = 0.5,
hoverinfo = "text",
text = ~paste(date, "<br>", Canton, "<br>", round(ncumul_conf_per_10thous, 0), "total cases every 10000 people")) %>%
layout(yaxis = list(title = "Total Covid-19 cases", showgrid = F),
xaxis = list(title = " ")) %>%
config(displayModeBar = FALSE, displaylogo = FALSE)
})
output$deaths_abs <- renderPlotly({
data_swiss %>%
plot_ly() %>%
filter(date == max(date)-2) %>%
add_bars(x = ~reorder(Canton, -ncumul_deceased),
y = ~ncumul_deceased,
color = I("black"),
opacity = 0.5,
hoverinfo = "text",
text = ~paste(date, "<br>", Canton, "<br>", ncumul_deceased, "total deaths")) %>%
layout(yaxis = list(title = "Total deaths", showgrid = F),
xaxis = list(title = " ")) %>%
config(displayModeBar = FALSE, displaylogo = FALSE)
})
output$deaths <- renderPlotly({
data_swiss %>%
plot_ly() %>%
filter(date == max(date)-2) %>%
add_bars(x = ~reorder(Canton, -ncumul_deceased_per_10thous),
y = ~ncumul_deceased_per_10thous,
hoverinfo = "text",
color = I("black"),
opacity = 0.5,
text = ~paste(date, "<br>", Canton, "<br>", round(ncumul_deceased_per_10thous, 0), "total deaths every 10000 people")) %>%
layout(yaxis = list(title = "Total deaths", showgrid = F),
xaxis = list(title = " ")) %>%
config(displayModeBar = FALSE, displaylogo = FALSE)
})
output$box_cases <- renderValueBox({
box_cases_val <- summarize(data_total_swiss, sum(switzerland_new_cases))
valueBox(box_cases_val, "Total cases in Switzerland", color = "yellow", icon = icon("virus"))
})
output$box_deaths <- renderValueBox({
box_deaths_val <- summarize(data_total_swiss, sum(switzerland_new_deaths))
valueBox(box_deaths_val, "Total deaths in Switzerland", color = "yellow", icon = icon("skull"))
})
output$box_canton <- renderValueBox({
a <- data_swiss %>% filter(date == max(date))
box_canton_val <- a$Canton[which.max(a$ncumul_conf)]
valueBox(box_canton_val, "Canton with highest number of cases", color = "yellow", icon = icon("arrow-up"))
})
output$swiss_trend <- renderValueBox({
tot14days_last_swiss <- summarize(trend, sum(tot14days_last))
tot14days_previous_swiss <- summarize(trend, sum(tot14days_previous))
swiss_trend_val <- (tot14days_last_swiss-tot14days_previous_swiss)/tot14days_last_swiss*100
valueBox(paste0(round(swiss_trend_val, 0), "%"), "14 days variation of cases in Switzerland", color = "yellow", icon = if(swiss_trend_val >= 0){icon("arrow-alt-circle-up")} else {icon("arrow-alt-circle-down")})
})
output$trend_table <- DT::renderDataTable({
trend_table <- trend %>%
select(-Pop, -Canton_abbr)
DT::datatable(trend_table,
rownames = FALSE,
class = "hover",
colnames = c("Canton", "total cases last 14 days", "total cases previous 14 days", "variation %"))
})
}
ui <- dashboardPage(skin = "purple", header, sidebar, body)
shiny::shinyApp(ui, server)

how to create two independent drill down plot using Highcharter?

I'm working on shiny app that contains two drill down charts, both read from same data file the only difference is the first chart excute summation, while the second one gets averages, the issue is whatever the change I make both charts still conflicting , here is the used code
cate<-c("Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","drinks","drinks","groceries","groceries","groceries","dairy","dairy","dairy","dairy","groceries","technology","technology","technology","technology","technology","technology","technology","technology","groceries","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","drinks","drinks","groceries","groceries","groceries","dairy","dairy","dairy","dairy","groceries","technology","technology","technology","technology","technology","technology","technology","technology","groceries","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","drinks","drinks","groceries","groceries","groceries","dairy","dairy","dairy","dairy","groceries","technology","technology","technology","technology","technology","technology","technology","technology","groceries","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","drinks","drinks","groceries","groceries","groceries","dairy","dairy","dairy","dairy","groceries","technology","technology","technology","technology","technology","technology","technology","technology","groceries")
Sub_Product<-c("nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug")
Main_Product<-c("outdoor","indoor","outdoor","indoor","indoor","outdoor","indoor","indoor","indoor","indoor","outdoor","outdoor","n&o","n&o","indoor","indoor","indoor","indoor","outdoor","indoor","outdoor","outdoor","outdoor","indoor","outdoor","indoor","outdoor","outdoor","indoor","outdoor","n&o","outdoor","indoor","outdoor","indoor","indoor","outdoor","indoor","indoor","indoor","indoor","outdoor","outdoor","n&o","n&o","indoor","indoor","indoor","indoor","outdoor","indoor","outdoor","outdoor","outdoor","indoor","outdoor","indoor","outdoor","outdoor","indoor","outdoor","n&o","outdoor","indoor","outdoor","indoor","indoor","outdoor","indoor ","indoor ","indoor ","indoor ","outdoor","outdoor","n&o","n&o","indoor","indoor","indoor","indoor","outdoor","indoor","outdoor","outdoor","outdoor","indoor","outdoor","indoor","outdoor","outdoor","indoor","outdoor","n&o","outdoor","indoor","outdoor","indoor","indoor","outdoor","indoor ","indoor ","indoor ","indoor ","outdoor","outdoor","n&o","n&o","indoor","indoor","indoor","indoor","outdoor","indoor","outdoor","outdoor","outdoor","indoor","outdoor","indoor","outdoor","outdoor","indoor","outdoor","n&o")
Product<-c("abc","def","ghh","hig","lmn","opk","cba","dfw","ewr","csad","wer","casd","were","csad","rt","hgf","qeq","hgf","qer","qer2","erqerq","qdq","dwqer","qerqe","erqererq","e2342","ererq","qewrw","qrerqr","qreqw","qerqe","abc","def","ghh","hig","lmn","opk","cba","dfw","ewr","csad","wer","casd","were","csad","rt","hgf","qeq","hgf","qer","qer2","erqerq","qdq","dwqer","qerqe","erqererq","e2342","ererq","qewrw","qrerqr","qreqw","qerqe","abc","def","ghh","hig","lmn","opk","cba","dfw","ewr","csad","wer","casd","were","csad","rt","hgf","qeq","hgf","qer","qer2","erqerq","qdq","dwqer","qerqe","erqererq","e2342","ererq","qewrw","qrerqr","qreqw","qerqe","abc","def","ghh","hig","lmn","opk","cba","dfw","ewr","csad","wer","casd","were","csad","rt","hgf","qeq","hgf","qer","qer2","erqerq","qdq","dwqer","qerqe","erqererq","e2342","ererq","qewrw","qrerqr","qreqw","qerqe")
sum1<-c(43,90,135,125,87,4,23,120,4,127,70,68,129,63,131,90,67,110,90,119,81,68,15,29,49,11,76,82,65,83,25,43,90,135,125,87,4,23,120,4,127,70,68,129,63,131,90,67,110,90,119,81,68,15,29,49,11,76,82,65,83,25,43,90,135,125,87,4,23,120,4,127,70,68,129,63,131,90,67,110,90,119,81,68,15,29,49,11,76,82,65,83,25,43,90,135,125,87,4,23,120,4,127,70,68,129,63,131,90,67,110,90,119,81,68,15,29,49,11,76,82,65,83,25)
sum2<-c(14567,11111,3287,3563,9633,11162,3044,8437,4382,11250,3932,5587,4175,9708,4970,8388,10673,4301,12475,13494,12519,5632,3898,12472,4381,14085,10041,4276,12953,11143,12905,14567,11111,3287,3563,9633,11162,3044,8437,4382,11250,3932,5587,4175,9708,4970,8388,10673,4301,12475,13494,12519,5632,3898,12472,4381,14085,10041,4276,12953,11143,12905,14567,11111,3287,3563,9633,11162,3044,8437,4382,11250,3932,5587,4175,9708,4970,8388,10673,4301,12475,13494,12519,5632,3898,12472,4381,14085,10041,4276,12953,11143,12905,14567,11111,3287,3563,9633,11162,3044,8437,4382,11250,3932,5587,4175,9708,4970,8388,10673,4301,12475,13494,12519,5632,3898,12472,4381,14085,10041,4276,12953,11143,12905)
avg1<-c(48,132,115,83,84,77,111,102,113,96,136,97,89,97,66,18,123,29,37,118,66,87,52,11,97,25,144,21,40,6,36,48,132,115,83,84,77,111,102,113,96,136,97,89,97,66,18,123,29,37,118,66,87,52,11,97,25,144,21,40,6,36,48,132,115,83,84,77,111,102,113,96,136,97,89,97,66,18,123,29,37,118,66,87,52,11,97,25,144,21,40,6,36,48,132,115,83,84,77,111,102,113,96,136,97,89,97,66,18,123,29,37,118,66,87,52,11,97,25,144,21,40,6,36)
avg2<-c(6775,3142,3916,12828,9889,4025,11374,10594,4263,8871,11229,4787,7478,5316,5299,14068,3981,12993,12435,13845,4320,7472,14285,10221,11883,7783,13980,11426,13120,8632,14540,6775,3142,3916,12828,9889,4025,11374,10594,4263,8871,11229,4787,7478,5316,5299,14068,3981,12993,12435,13845,4320,7472,14285,10221,11883,7783,13980,11426,13120,8632,14540,6775,3142,3916,12828,9889,4025,11374,10594,4263,8871,11229,4787,7478,5316,5299,14068,3981,12993,12435,13845,4320,7472,14285,10221,11883,7783,13980,11426,13120,8632,14540,6775,3142,3916,12828,9889,4025,11374,10594,4263,8871,11229,4787,7478,5316,5299,14068,3981,12993,12435,13845,4320,7472,14285,10221,11883,7783,13980,11426,13120,8632,14540)
dat<-data.frame(cate,Sub_Product,Main_Product,Product,sum1,sum2,avg1,avg2)
all_products<-c("Furniture","drinks","groceries","dairy","technology")
ACClist<-c("sum1","sum2")
AVGlist<-c("avg1","avg2")
library (shinyjs)
library (tidyr)
library (data.table)
library (highcharter)
library (dplyr)
library (shinydashboard)
library (shiny)
library (shinyWidgets)
header <-dashboardHeader()
body <- dashboardBody(fluidRow(
column(width = 12,
radioGroupButtons(
inputId = "l1PAD", label = NULL,size = "lg",
choices = all_products, justified = TRUE,
individual = TRUE)
)),
fluidRow(
highchartOutput("accuPA",height = "300px"),
highchartOutput("avgPA",height = "300px")
))
sidebar <- dashboardSidebar(collapsed = T,
radioGroupButtons(
"accuselectPA","sum",choices=ACClist,
direction = "vertical",width = "100%",justified = TRUE
),
br(),
radioGroupButtons(
"avgselectPA","Average ",choices=AVGlist,
direction = "vertical",width = "100%",justified = TRUE
))
ui <- dashboardPage(header, sidebar, body)
server <- function(input, output, session) {
observe({
print(input$l1PAD)
datz<-reactive({
dat%>%filter(cate==input$l1PAD)
})
print(datz())
str(datz())
output$accuPA <- renderHighchart({
summarized <- datz() %>%
group_by(Main_Product) %>%
summarize(Quantity = sum(!!sym(input$accuselectPA)))
summarized <- arrange(summarized, desc(Quantity))
tibbled <- tibble(name = summarized$Main_Product, y = summarized$Quantity)
drilldownHandler <- JS("function(event) {Shiny.onInputChange('ClickedInput', event.point.drilldown);}")
installDrilldownReceiver <- JS("function() {
var chart = this;
Shiny.addCustomMessageHandler('drilldown', function(message) {
var point = chart.get(message.point)
chart.addSeriesAsDrilldown(point, message.series);
});
}")
highchart() %>%
hc_chart(events = list(load = installDrilldownReceiver, drilldown = drilldownHandler)) %>%
hc_xAxis(type = "category") %>%
hc_add_series(tibbled, "column", hcaes(x = name, y = y, drilldown = name, id = name), color = "#e6b30a") %>%
hc_plotOptions(column = list(stacking = "normal")) %>%
hc_drilldown(allowPointDrilldown = TRUE)
})
observeEvent(input$ClickedInput, {
levels <- strsplit(input$ClickedInput, "_", fixed = TRUE)[[1]]
resemblences <- c("Main_Product", "Product", "Sub_Product")
dataSubSet <- datz()
for (i in 1:length(levels)) {
dataSubSet <- datz()[datz()[[resemblences[i]]] == levels[i],]}
print(dataSubSet)
str(dataSubSet)
normalized <- data.frame(category = dataSubSet[[resemblences[length(levels) + 1]]],amount= dataSubSet[, input$accuselectPA])
print(normalized)
str(normalized)
summarized <- normalized %>%group_by(category) %>% summarize(Quantity = sum(amount))
summarized <- arrange(summarized, desc(Quantity))
tibbled <- tibble(name = summarized$category, y = summarized$Quantity)
nextLevelCodes = lapply(tibbled$name, function(fac) {paste(c(levels, as.character(fac)), collapse = "_")
}) %>% unlist
tibbled$id = nextLevelCodes
if (length(levels) < length(resemblences) - 1) {
tibbled$drilldown = nextLevelCodes
}
session$sendCustomMessage("drilldown", list(
series = list(type = "column",name = paste(levels, sep = "_"),data = list_parse(tibbled)
),
point = input$ClickedInput
))
})
output$trial <- renderText({input$ClickedInput})
})
observe({
print(input$l1PAD)
datz2<-reactive({
dat%>%filter(cate==input$l1PAD)
})
print(datz2())
str(datz2())
output$avgPA <- renderHighchart({
summarized2 <- datz2() %>%
group_by(Main_Product) %>%
summarize(Quantity2 = mean(!!sym(input$avgselectPA)))
summarized2 <- arrange(summarized2, desc(Quantity2))
tibbled2 <- tibble(name = summarized2$Main_Product, y = summarized2$Quantity2)
drilldownHandler2 <- JS("function(event) {Shiny.onInputChange('ClickedInput2', event.point.drilldown);}")
installDrilldownReceiver2 <- JS("function() {
var chart = this;
Shiny.addCustomMessageHandler('drilldown', function(message) {
var point = chart.get(message.point)
chart.addSeriesAsDrilldown(point, message.series);
});
}")
highchart() %>%
hc_chart(events = list(load = installDrilldownReceiver2, drilldown = drilldownHandler2)) %>%
hc_xAxis(type = "category") %>%
hc_add_series(tibbled2, "column", hcaes(x = name, y = y, drilldown = name, id = name), color = "#e6b30a") %>%
hc_plotOptions(column = list(stacking = "normal")) %>%
hc_drilldown(allowPointDrilldown = TRUE)
})
observeEvent(input$ClickedInput2, {
levels2 <- strsplit(input$ClickedInput2, "_", fixed = TRUE)[[1]]
resemblences2 <- c("Main_Product", "Product", "Sub_Product")
dataSubSet2 <- datz2()
for (i in 1:length(levels2)) {
dataSubSet2 <- datz2()[datz2()[[resemblences2[i]]] == levels2[i],]}
print(dataSubSet2)
str(dataSubSet2)
normalized2 <- data.frame(category = dataSubSet2[[resemblences2[length(levels2) + 1]]],amount= dataSubSet2[, input$avgselectPA])
print(normalized2)
str(normalized2)
summarized2 <- normalized2 %>%group_by(category) %>% summarize(Quantity2 = mean(amount))
summarized2 <- arrange(summarized2, desc(Quantity2))
tibbled2 <- tibble(name = summarized2$category, y = summarized2$Quantity2)
nextLevelCodes2 = lapply(tibbled2$name, function(fac) {paste(c(levels2, as.character(fac)), collapse = "_")
}) %>% unlist
tibbled2$id = nextLevelCodes2
if (length(levels2) < length(resemblences2) - 1) {
tibbled2$drilldown = nextLevelCodes2
}
session$sendCustomMessage("drilldown", list(
series = list(type = "column",name = paste(levels2, sep = "_"),data = list_parse(tibbled2)
),
point = input$ClickedInput2
))
})
output$trial <- renderText({input$ClickedInput2})
})
}
shinyApp(ui, server)
all needed is just copy and paste the code above and try to drill down in the first chart to see the breakdown of total count it will not respond while chart 2 will respond to the click on chart one column
the hover text on each column shows the difference between two charts
as how the first one show the summation while the second one shows the average value.
the data frame might be long but it is a sample of my dataset
minor request, I need only the 3rd level on both plots to be line chart
update another unsuccessful trial ------------------
cate<-c("Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","drinks","drinks","groceries","groceries","groceries","dairy","dairy","dairy","dairy","groceries","technology","technology","technology","technology","technology","technology","technology","technology","groceries","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","drinks","drinks","groceries","groceries","groceries","dairy","dairy","dairy","dairy","groceries","technology","technology","technology","technology","technology","technology","technology","technology","groceries","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","drinks","drinks","groceries","groceries","groceries","dairy","dairy","dairy","dairy","groceries","technology","technology","technology","technology","technology","technology","technology","technology","groceries","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","drinks","drinks","groceries","groceries","groceries","dairy","dairy","dairy","dairy","groceries","technology","technology","technology","technology","technology","technology","technology","technology","groceries")
Sub_Product<-c("nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug")
Main_Product<-c("outdoor","indoor","outdoor","indoor","indoor","outdoor","indoor","indoor","indoor","indoor","outdoor","outdoor","n&o","n&o","indoor","indoor","indoor","indoor","outdoor","indoor","outdoor","outdoor","outdoor","indoor","outdoor","indoor","outdoor","outdoor","indoor","outdoor","n&o","outdoor","indoor","outdoor","indoor","indoor","outdoor","indoor","indoor","indoor","indoor","outdoor","outdoor","n&o","n&o","indoor","indoor","indoor","indoor","outdoor","indoor","outdoor","outdoor","outdoor","indoor","outdoor","indoor","outdoor","outdoor","indoor","outdoor","n&o","outdoor","indoor","outdoor","indoor","indoor","outdoor","indoor ","indoor ","indoor ","indoor ","outdoor","outdoor","n&o","n&o","indoor","indoor","indoor","indoor","outdoor","indoor","outdoor","outdoor","outdoor","indoor","outdoor","indoor","outdoor","outdoor","indoor","outdoor","n&o","outdoor","indoor","outdoor","indoor","indoor","outdoor","indoor ","indoor ","indoor ","indoor ","outdoor","outdoor","n&o","n&o","indoor","indoor","indoor","indoor","outdoor","indoor","outdoor","outdoor","outdoor","indoor","outdoor","indoor","outdoor","outdoor","indoor","outdoor","n&o")
Product<-c("abc","def","ghh","hig","lmn","opk","cba","dfw","ewr","csad","wer","casd","were","csad","rt","hgf","qeq","hgf","qer","qer2","erqerq","qdq","dwqer","qerqe","erqererq","e2342","ererq","qewrw","qrerqr","qreqw","qerqe","abc","def","ghh","hig","lmn","opk","cba","dfw","ewr","csad","wer","casd","were","csad","rt","hgf","qeq","hgf","qer","qer2","erqerq","qdq","dwqer","qerqe","erqererq","e2342","ererq","qewrw","qrerqr","qreqw","qerqe","abc","def","ghh","hig","lmn","opk","cba","dfw","ewr","csad","wer","casd","were","csad","rt","hgf","qeq","hgf","qer","qer2","erqerq","qdq","dwqer","qerqe","erqererq","e2342","ererq","qewrw","qrerqr","qreqw","qerqe","abc","def","ghh","hig","lmn","opk","cba","dfw","ewr","csad","wer","casd","were","csad","rt","hgf","qeq","hgf","qer","qer2","erqerq","qdq","dwqer","qerqe","erqererq","e2342","ererq","qewrw","qrerqr","qreqw","qerqe")
sum1<-c(43,90,135,125,87,4,23,120,4,127,70,68,129,63,131,90,67,110,90,119,81,68,15,29,49,11,76,82,65,83,25,43,90,135,125,87,4,23,120,4,127,70,68,129,63,131,90,67,110,90,119,81,68,15,29,49,11,76,82,65,83,25,43,90,135,125,87,4,23,120,4,127,70,68,129,63,131,90,67,110,90,119,81,68,15,29,49,11,76,82,65,83,25,43,90,135,125,87,4,23,120,4,127,70,68,129,63,131,90,67,110,90,119,81,68,15,29,49,11,76,82,65,83,25)
sum2<-c(14567,11111,3287,3563,9633,11162,3044,8437,4382,11250,3932,5587,4175,9708,4970,8388,10673,4301,12475,13494,12519,5632,3898,12472,4381,14085,10041,4276,12953,11143,12905,14567,11111,3287,3563,9633,11162,3044,8437,4382,11250,3932,5587,4175,9708,4970,8388,10673,4301,12475,13494,12519,5632,3898,12472,4381,14085,10041,4276,12953,11143,12905,14567,11111,3287,3563,9633,11162,3044,8437,4382,11250,3932,5587,4175,9708,4970,8388,10673,4301,12475,13494,12519,5632,3898,12472,4381,14085,10041,4276,12953,11143,12905,14567,11111,3287,3563,9633,11162,3044,8437,4382,11250,3932,5587,4175,9708,4970,8388,10673,4301,12475,13494,12519,5632,3898,12472,4381,14085,10041,4276,12953,11143,12905)
avg1<-c(48,132,115,83,84,77,111,102,113,96,136,97,89,97,66,18,123,29,37,118,66,87,52,11,97,25,144,21,40,6,36,48,132,115,83,84,77,111,102,113,96,136,97,89,97,66,18,123,29,37,118,66,87,52,11,97,25,144,21,40,6,36,48,132,115,83,84,77,111,102,113,96,136,97,89,97,66,18,123,29,37,118,66,87,52,11,97,25,144,21,40,6,36,48,132,115,83,84,77,111,102,113,96,136,97,89,97,66,18,123,29,37,118,66,87,52,11,97,25,144,21,40,6,36)
avg2<-c(6775,3142,3916,12828,9889,4025,11374,10594,4263,8871,11229,4787,7478,5316,5299,14068,3981,12993,12435,13845,4320,7472,14285,10221,11883,7783,13980,11426,13120,8632,14540,6775,3142,3916,12828,9889,4025,11374,10594,4263,8871,11229,4787,7478,5316,5299,14068,3981,12993,12435,13845,4320,7472,14285,10221,11883,7783,13980,11426,13120,8632,14540,6775,3142,3916,12828,9889,4025,11374,10594,4263,8871,11229,4787,7478,5316,5299,14068,3981,12993,12435,13845,4320,7472,14285,10221,11883,7783,13980,11426,13120,8632,14540,6775,3142,3916,12828,9889,4025,11374,10594,4263,8871,11229,4787,7478,5316,5299,14068,3981,12993,12435,13845,4320,7472,14285,10221,11883,7783,13980,11426,13120,8632,14540)
dat<-data.frame(cate,Sub_Product,Main_Product,Product,sum1,sum2,avg1,avg2)
all_products<-c("Furniture","drinks","groceries","dairy","technology")
ACClist<-c("sum1","sum2")
AVGlist<-c("avg1","avg2")
library (shinyjs)
library (tidyr)
library (data.table)
library (highcharter)
library (dplyr)
library (shinydashboard)
library (shiny)
library (shinyWidgets)
header <-dashboardHeader()
body <- dashboardBody(fluidRow(
column(width = 12,
radioGroupButtons(
inputId = "l1PAD", label = NULL,size = "lg",
choices = all_products, justified = TRUE,
individual = TRUE)
)),
fluidRow(
highchartOutput("accuPA",height = "300px"),
highchartOutput("avgPA",height = "300px")
))
sidebar <- dashboardSidebar(collapsed = T,
radioGroupButtons(
"accuselectPA","sum",choices=ACClist,
direction = "vertical",width = "100%",justified = TRUE
),
br(),
radioGroupButtons(
"avgselectPA","Average ",choices=AVGlist,
direction = "vertical",width = "100%",justified = TRUE
))
ui <- dashboardPage(header, sidebar, body)
server <- function(input, output, session) {
observe({
print(input$l1PAD)
datz<-reactive({
dat%>%filter(cate==input$l1PAD)
})
TYT<-reactive({
datz()%>%select(1:4)
})
nont<-reactive({
datz()%>%pull(input$avgselectPA)
})
print(datz())
str(datz())
print(nont())
str(nont())
urt<-reactive({
data_frame(TYT(),nont())
})
print(urt())
str(urt())
output$accuPA <- renderHighchart({
summarized <- datz() %>%
group_by(Main_Product) %>%
summarize(Quantity = sum(!!sym(input$accuselectPA)))
summarized <- arrange(summarized, desc(Quantity))
tibbled <- tibble(name = summarized$Main_Product, y = summarized$Quantity)
drilldownHandler <- JS("function(event) {Shiny.onInputChange('ClickedInput', event.point.drilldown);}")
installDrilldownReceiver <- JS("function() {
var chart = this;
Shiny.addCustomMessageHandler('drilldown', function(message) {
var point = chart.get(message.point)
chart.addSeriesAsDrilldown(point, message.series);
});
}")
highchart() %>%
hc_chart(events = list(load = installDrilldownReceiver, drilldown = drilldownHandler)) %>%
hc_xAxis(type = "category") %>%
hc_add_series(tibbled, "column", hcaes(x = name, y = y, drilldown = name, id = name), color = "#e6b30a") %>%
hc_plotOptions(column = list(stacking = "normal")) %>%
hc_drilldown(allowPointDrilldown = TRUE)
})
observeEvent(input$ClickedInput, {
levels <- strsplit(input$ClickedInput, "_", fixed = TRUE)[[1]]
resemblences <- c("Main_Product", "Product", "Sub_Product")
dataSubSet <- datz()
for (i in 1:length(levels)) {
dataSubSet <- datz()[datz()[[resemblences[i]]] == levels[i],]}
print(dataSubSet)
str(dataSubSet)
normalized <- data.frame(category = dataSubSet[[resemblences[length(levels) + 1]]],amount= dataSubSet[, input$accuselectPA])
print(normalized)
str(normalized)
summarized <- normalized %>%group_by(category) %>% summarize(Quantity = sum(amount))
summarized <- arrange(summarized, desc(Quantity))
tibbled <- tibble(name = summarized$category, y = summarized$Quantity)
nextLevelCodes = lapply(tibbled$name, function(fac) {paste(c(levels, as.character(fac)), collapse = "_")
}) %>% unlist
tibbled$id = nextLevelCodes
if (length(levels) < length(resemblences) - 1) {
tibbled$drilldown = nextLevelCodes}
session$sendCustomMessage("drilldown", list(
series = list(type = "column",name = paste(levels, sep = "_"),data = list_parse(tibbled)
),
point = input$ClickedInput
))
})
output$avgPA<-renderHighchart({
datSum <- urt() %>%
group_by(Main_Product) %>%
summarize(Quantity = mean('nont')
)
datSum <- arrange(datSum,desc(Quantity))
Lvl1dfStatus <- tibble(name = datSum$Main_Product, y = datSum$Quantity, drilldown = tolower(name))
#Second Tier # Generalized to not use one single input
# Note: I am creating a list of Drilldown Definitions here.
Level_2_Drilldowns <- lapply(unique(urt()$Main_Product), function(x_level) {
# x_level is what you called 'input' earlier.
datSum2 <- urt()[urt()$Main_Product == x_level,]
datSum2 <- datSum2 %>%
group_by(Product) %>%
summarize(Quantity = mean('nont')
)
datSum2 <- arrange(datSum2,desc(Quantity))
# Note: The "drilldown" variable has to be unique, this is why we use level 1 plus level 2 names.
Lvl2dfStatus <- tibble(name = datSum2$Product,y = datSum2$Quantity, drilldown = tolower(paste(x_level, name, sep = "_")))
list(id = tolower(x_level), type = "column", data = list_parse(Lvl2dfStatus))
})
#Third Tier # Generalized through all of level 2
# Note: Again creating a list of Drilldown Definitions here.
Level_3_Drilldowns <- lapply(unique(urt()$Main_Product), function(x_level) {
datSum2 <- urt()[urt()$Main_Product == x_level,]
lapply(unique(datSum2$Product), function(y_level) {
datSum3 <- datSum2[datSum2$Product == y_level,]
datSum3 <- datSum3 %>%
group_by(Sub_Product) %>%
summarize(Quantity = mean('nont')
)
datSum3 <- arrange(datSum3,desc(Quantity))
Lvl3dfStatus <- tibble(name = datSum3$Sub_Product,y = datSum3$Quantity)
# Note: The id must match the one we specified above as "drilldown"
list(id = tolower(paste(x_level, y_level, sep = "_")), type = "column", data = list_parse2(Lvl3dfStatus))
})
}) %>% unlist(recursive = FALSE)
highchart() %>%
hc_xAxis(type = "category") %>%
hc_add_series(Lvl1dfStatus, "column", hcaes(x = name, y = Product), color = "#E4551F") %>%
hc_plotOptions(column = list(stacking = "normal")) %>%
hc_drilldown(
allowPointDrilldown = TRUE,
series = c(Level_2_Drilldowns, Level_3_Drilldowns)
)
})
#THE NEXT }) is for observe
})
}
shinyApp(ui, server)
Here you go, both graphs operate independently of each other's drilldowns.
I simplified your code as well as you had a lot of observes and reactives that were not needed (in this example at least).
cate<-c("Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","drinks","drinks","groceries","groceries","groceries","dairy","dairy","dairy","dairy","groceries","technology","technology","technology","technology","technology","technology","technology","technology","groceries","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","drinks","drinks","groceries","groceries","groceries","dairy","dairy","dairy","dairy","groceries","technology","technology","technology","technology","technology","technology","technology","technology","groceries","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","drinks","drinks","groceries","groceries","groceries","dairy","dairy","dairy","dairy","groceries","technology","technology","technology","technology","technology","technology","technology","technology","groceries","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","Furniture","drinks","drinks","groceries","groceries","groceries","dairy","dairy","dairy","dairy","groceries","technology","technology","technology","technology","technology","technology","technology","technology","groceries")
Sub_Product<-c("nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","nov","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","oct","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","sept","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug","aug")
Main_Product<-c("outdoor","indoor","outdoor","indoor","indoor","outdoor","indoor","indoor","indoor","indoor","outdoor","outdoor","n&o","n&o","indoor","indoor","indoor","indoor","outdoor","indoor","outdoor","outdoor","outdoor","indoor","outdoor","indoor","outdoor","outdoor","indoor","outdoor","n&o","outdoor","indoor","outdoor","indoor","indoor","outdoor","indoor","indoor","indoor","indoor","outdoor","outdoor","n&o","n&o","indoor","indoor","indoor","indoor","outdoor","indoor","outdoor","outdoor","outdoor","indoor","outdoor","indoor","outdoor","outdoor","indoor","outdoor","n&o","outdoor","indoor","outdoor","indoor","indoor","outdoor","indoor","indoor","indoor","indoor","outdoor","outdoor","n&o","n&o","indoor","indoor","indoor","indoor","outdoor","indoor","outdoor","outdoor","outdoor","indoor","outdoor","indoor","outdoor","outdoor","indoor","outdoor","n&o","outdoor","indoor","outdoor","indoor","indoor","outdoor","indoor","indoor","indoor","indoor","outdoor","outdoor","n&o","n&o","indoor","indoor","indoor","indoor","outdoor","indoor","outdoor","outdoor","outdoor","indoor","outdoor","indoor","outdoor","outdoor","indoor","outdoor","n&o")
Product<-c("abc","def","ghh","hig","lmn","opk","cba","dfw","ewr","csad","wer","casd","were","csad","rt","hgf","qeq","hgf","qer","qer2","erqerq","qdq","dwqer","qerqe","erqererq","e2342","ererq","qewrw","qrerqr","qreqw","qerqe","abc","def","ghh","hig","lmn","opk","cba","dfw","ewr","csad","wer","casd","were","csad","rt","hgf","qeq","hgf","qer","qer2","erqerq","qdq","dwqer","qerqe","erqererq","e2342","ererq","qewrw","qrerqr","qreqw","qerqe","abc","def","ghh","hig","lmn","opk","cba","dfw","ewr","csad","wer","casd","were","csad","rt","hgf","qeq","hgf","qer","qer2","erqerq","qdq","dwqer","qerqe","erqererq","e2342","ererq","qewrw","qrerqr","qreqw","qerqe","abc","def","ghh","hig","lmn","opk","cba","dfw","ewr","csad","wer","casd","were","csad","rt","hgf","qeq","hgf","qer","qer2","erqerq","qdq","dwqer","qerqe","erqererq","e2342","ererq","qewrw","qrerqr","qreqw","qerqe")
sum1<-c(43,90,135,125,87,4,23,120,4,127,70,68,129,63,131,90,67,110,90,119,81,68,15,29,49,11,76,82,65,83,25,43,90,135,125,87,4,23,120,4,127,70,68,129,63,131,90,67,110,90,119,81,68,15,29,49,11,76,82,65,83,25,43,90,135,125,87,4,23,120,4,127,70,68,129,63,131,90,67,110,90,119,81,68,15,29,49,11,76,82,65,83,25,43,90,135,125,87,4,23,120,4,127,70,68,129,63,131,90,67,110,90,119,81,68,15,29,49,11,76,82,65,83,25)
sum2<-c(14567,11111,3287,3563,9633,11162,3044,8437,4382,11250,3932,5587,4175,9708,4970,8388,10673,4301,12475,13494,12519,5632,3898,12472,4381,14085,10041,4276,12953,11143,12905,14567,11111,3287,3563,9633,11162,3044,8437,4382,11250,3932,5587,4175,9708,4970,8388,10673,4301,12475,13494,12519,5632,3898,12472,4381,14085,10041,4276,12953,11143,12905,14567,11111,3287,3563,9633,11162,3044,8437,4382,11250,3932,5587,4175,9708,4970,8388,10673,4301,12475,13494,12519,5632,3898,12472,4381,14085,10041,4276,12953,11143,12905,14567,11111,3287,3563,9633,11162,3044,8437,4382,11250,3932,5587,4175,9708,4970,8388,10673,4301,12475,13494,12519,5632,3898,12472,4381,14085,10041,4276,12953,11143,12905)
avg1<-c(48,132,115,83,84,77,111,102,113,96,136,97,89,97,66,18,123,29,37,118,66,87,52,11,97,25,144,21,40,6,36,48,132,115,83,84,77,111,102,113,96,136,97,89,97,66,18,123,29,37,118,66,87,52,11,97,25,144,21,40,6,36,48,132,115,83,84,77,111,102,113,96,136,97,89,97,66,18,123,29,37,118,66,87,52,11,97,25,144,21,40,6,36,48,132,115,83,84,77,111,102,113,96,136,97,89,97,66,18,123,29,37,118,66,87,52,11,97,25,144,21,40,6,36)
avg2<-c(6775,3142,3916,12828,9889,4025,11374,10594,4263,8871,11229,4787,7478,5316,5299,14068,3981,12993,12435,13845,4320,7472,14285,10221,11883,7783,13980,11426,13120,8632,14540,6775,3142,3916,12828,9889,4025,11374,10594,4263,8871,11229,4787,7478,5316,5299,14068,3981,12993,12435,13845,4320,7472,14285,10221,11883,7783,13980,11426,13120,8632,14540,6775,3142,3916,12828,9889,4025,11374,10594,4263,8871,11229,4787,7478,5316,5299,14068,3981,12993,12435,13845,4320,7472,14285,10221,11883,7783,13980,11426,13120,8632,14540,6775,3142,3916,12828,9889,4025,11374,10594,4263,8871,11229,4787,7478,5316,5299,14068,3981,12993,12435,13845,4320,7472,14285,10221,11883,7783,13980,11426,13120,8632,14540)
dat<-data.frame(cate,Sub_Product,Main_Product,Product,sum1,sum2,avg1,avg2, stringsAsFactors = FALSE)
ACClist<-c("sum1","sum2")
AVGlist<-c("avg1","avg2")
library (shinyjs)
library (tidyr)
library (data.table)
library (highcharter)
library (dplyr)
library (shinydashboard)
library (shiny)
library (shinyWidgets)
header <-dashboardHeader()
body <- dashboardBody(fluidRow(
column(width = 12,
radioGroupButtons(
inputId = "l1PAD", label = NULL,size = "lg",
choices = unique(dat$cate), justified = TRUE,
individual = TRUE)
)),
fluidRow(
box(
title = "Summation of dataset", highchartOutput("accuPA",height = "300px")
),
box(
title = "Mean of dataset", highchartOutput("avgPA",height = "300px")
)
))
sidebar <- dashboardSidebar(collapsed = T,
radioGroupButtons(
"accuselectPA","sum",choices=ACClist,
direction = "vertical",width = "100%",justified = TRUE
),
br(),
radioGroupButtons(
"avgselectPA","Average ",choices=AVGlist,
direction = "vertical",width = "100%",justified = TRUE
))
ui <- dashboardPage(header, sidebar, body)
server <- function(input, output, session) {
#data set
dat_filtered <- reactive({
dat[dat$cate == input$l1PAD,]
})
#Acc/sum graph
output$accuPA<-renderHighchart({
#LEVEL 1
datSum <- dat_filtered() %>%
group_by(Main_Product) %>%
summarize(Quantity = mean(get(input$accuselectPA)))
datSum <- arrange(datSum,desc(Quantity))
Lvl1dfStatus <- tibble(name = datSum$Main_Product, y = datSum$Quantity, drilldown = tolower(name))
#LEVEL 2
Level_2_Drilldowns <- lapply(unique(dat_filtered()$Main_Product), function(x_level) {
datSum2 <- dat_filtered()[dat_filtered()$Main_Product == x_level,]
datSum2 <- datSum2 %>%
group_by(Product) %>%
summarize(Quantity = mean(get(input$accuselectPA)))
datSum2 <- arrange(datSum2,desc(Quantity))
Lvl2dfStatus <- tibble(name = datSum2$Product,y = datSum2$Quantity, drilldown = tolower(paste(x_level, name, sep = "_")))
list(id = tolower(x_level), type = "column", data = list_parse(Lvl2dfStatus))
})
#LEVEL 3
Level_3_Drilldowns <- lapply(unique(dat_filtered()$Main_Product), function(x_level) {
datSum2 <- dat_filtered()[dat_filtered()$Main_Product == x_level,]
lapply(unique(datSum2$Product), function(y_level) {
datSum3 <- datSum2[datSum2$Product == y_level,]
datSum3 <- datSum3 %>%
group_by(Sub_Product) %>%
summarize(Quantity = mean(get(input$accuselectPA)))
datSum3 <- arrange(datSum3,desc(Quantity))
Lvl3dfStatus <- tibble(name = datSum3$Sub_Product,y = datSum3$Quantity)
list(id = tolower(paste(x_level, y_level, sep = "_")), type = "column", data = list_parse2(Lvl3dfStatus))
})
}) %>% unlist(recursive = FALSE)
highchart() %>%
hc_xAxis(type = "category") %>%
hc_add_series(Lvl1dfStatus, "column", hcaes(x = name, y = y), color = "#E4551F") %>%
hc_plotOptions(column = list(stacking = "normal")) %>%
hc_drilldown(
allowPointDrilldown = TRUE,
series = c(Level_2_Drilldowns, Level_3_Drilldowns)
)
})
#Avg/Avg graph
output$avgPA<-renderHighchart({
#LEVEL 1
datSum <- dat_filtered() %>%
group_by(Main_Product) %>%
summarize(Quantity = mean(get(input$avgselectPA)))
datSum <- arrange(datSum,desc(Quantity))
Lvl1dfStatus <- tibble(name = datSum$Main_Product, y = datSum$Quantity, drilldown = tolower(name))
#LEVEL 2
Level_2_Drilldowns <- lapply(unique(dat_filtered()$Main_Product), function(x_level) {
datSum2 <- dat_filtered()[dat_filtered()$Main_Product == x_level,]
datSum2 <- datSum2 %>%
group_by(Product) %>%
summarize(Quantity = mean(get(input$avgselectPA)))
datSum2 <- arrange(datSum2,desc(Quantity))
Lvl2dfStatus <- tibble(name = datSum2$Product,y = datSum2$Quantity, drilldown = tolower(paste(x_level, name, sep = "_")))
list(id = tolower(x_level), type = "column", data = list_parse(Lvl2dfStatus))
})
#LEVEL 3
Level_3_Drilldowns <- lapply(unique(dat_filtered()$Main_Product), function(x_level) {
datSum2 <- dat_filtered()[dat_filtered()$Main_Product == x_level,]
lapply(unique(datSum2$Product), function(y_level) {
datSum3 <- datSum2[datSum2$Product == y_level,]
datSum3 <- datSum3 %>%
group_by(Sub_Product) %>%
summarize(Quantity = mean(get(input$avgselectPA)))
datSum3 <- arrange(datSum3,desc(Quantity))
Lvl3dfStatus <- tibble(name = datSum3$Sub_Product,y = datSum3$Quantity)
list(id = tolower(paste(x_level, y_level, sep = "_")), type = "column", data = list_parse2(Lvl3dfStatus))
})
}) %>% unlist(recursive = FALSE)
highchart() %>%
hc_xAxis(type = "category") %>%
hc_add_series(Lvl1dfStatus, "column", hcaes(x = name, y = y), color = "#E4551F") %>%
hc_plotOptions(column = list(stacking = "normal")) %>%
hc_drilldown(
allowPointDrilldown = TRUE,
series = c(Level_2_Drilldowns, Level_3_Drilldowns)
)
})
}
shinyApp(ui, server)

Resources