Shiny app does not work once deployed - rnaturalearthhires? - r
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)
Related
R shinydashboard + highcharter: arguments are not named in hc_add_series
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)
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
Firefox Leaflet Not Displaying Map Shapes in Shiny App Default Page When Published on shinyapps.io (other browsers are working fine)
I've just created my first Shiny app and published to the Internet - https://craycrayjodie.shinyapps.io/MapApp/ When launching the app and viewing in Chrome and I.E the default page ('Map' tab) loads as expected - with the "March" data displayed on the map. This is specified in the sliderTextInput for the page. However, when I load the app and view in Firefox (i.e. the 'Map' tab), the "March" data is not displayed on the map when the app loads by default in Firefox. I need to move the sliderTextInput, then the data loads on the map in the Browser. This is only an issue for Firefox, the other browsers (i.e. Chrome and IE) are fine and have the March data loaded and displayed on the map when the default 'Map' page loads. I have published my files up to GitHub - https://github.com/craycrayjodie/DataVis Also, my app.R logic is as follows: library(dplyr) library(lubridate) library(sf) library(leaflet) library(shinythemes) library(RColorBrewer) library(shinyWidgets) library(rmapshaper) library(rsconnect) library(shiny) library(ggplot2) library(highcharter) library(magrittr) library(htmlwidgets) library(RColorBrewer) library(shinycssloaders) ################################################################################################### myAusdata_by_month_sf = readRDS("myAusdata_by_month.rds") #load previously saved datafile myAusdata_by_month_5 = readRDS("myAusdata_by_month_5.rds") #load previously saved datafile areas_by_weeks = readRDS("areas_by_weeks.rds") #load previously saved datafile # Options for Spinner options(spinner.color="pink", spinner.type = 7, spinner.color.background="#ffffff", spinner.size=1) ui <- shinyUI( navbarPage( title = "Australians Mobility Changes During COVID", theme = shinytheme("yeti"), tabPanel("Map", div(class = "outer", tags$head( includeCSS("styles.css") ), leafletOutput("map", width = "100%", height = "100%"), absolutePanel(bottom = 30, left = 250, draggable = TRUE, # slider title, step increments sliderTextInput("choices", "Select month:", choices = unique(myAusdata_by_month_sf$month), animate = animationOptions(interval = 1500, loop = FALSE), grid = TRUE, selected = "March", width = 400)) ), tags$div(id = "cite", 'Data downloaded from Facebook for Good by Jodie Anderson (2020).' ) ), tabPanel("Story", highchartOutput("timeline", height = "800px" ) %>% withSpinner(), includeMarkdown("analysis.md"), br() ), tabPanel("Heatmap", highchartOutput("heatmap", height = "100%") %>% withSpinner(), br() ), tabPanel("About", includeMarkdown("about.md"), br() ) ) ) # Define server logic server <- function(input, output, session) { filteredData <- reactive({ myAusdata_by_month_sf %>% filter(month %in% input$choices) }) popup <- reactive({ sprintf("%s: %.1f%%", filteredData()$polygon_name, filteredData()$AvRelChange*100) }) output$map <- renderLeaflet({ mypalette <- colorNumeric(palette = "PuOr", domain = myAusdata_by_month_sf$AvRelChange, na.color = "transparent") leaflet(myAusdata_by_month_sf) %>% setView(134, -29, 4) %>% addProviderTiles("Esri.WorldGrayCanvas") %>% addLegend(pal=mypalette, values=~AvRelChange, opacity=1, title = "Mobility Change (%)", position = "bottomleft", labFormat = labelFormat(prefix = "(", suffix = ")", between = ", ", transform = function(x) 100 * x)) }) observe({ mypalette <- colorNumeric(palette = "PuOr", domain = myAusdata_by_month_sf$AvRelChange, na.color = "transparent") leafletProxy("map", data = filteredData()) %>% clearShapes() %>% addPolygons(fillColor = ~mypalette(AvRelChange), stroke=TRUE, fillOpacity = 1, color = "grey", weight = 0.3, label = popup(), labelOptions = labelOptions( style = list("font-weight" = "normal", padding = "2px 2px"), textsize = "13px", direction = "auto", offset = c(20, -25))) }) output$timeline <- renderHighchart ({ hc <- myAusdata_by_month_5 %>% hchart ('spline', hcaes(x= date, y=AvRelChange, group=NAME_1)) %>% hc_colors(brewer.pal(8, "Dark2")) %>% hc_title(text="Australians Mobility Changes", style=list(fontWeight="bold", fontSize="30px"), align="left") %>% hc_subtitle(text="During the coronavirus pandemic", style=list(fontWeight="bold"), align="left") %>% hc_xAxis(title = list(text=NULL), plotBands = list(list(label = list(text = "Australia<br>in<br>lockdown"), color = "rgba(100, 0, 0, 0.1)",from = datetime_to_timestamp(as.Date('2020-03-16', tz = 'UTC')), to = datetime_to_timestamp(as.Date('2020-03-31', tz = 'UTC'))))) %>% hc_yAxis(title=list(text = "Mobility Change (%)"), showLastLabel = FALSE, labels = list(format = "{value}%")) %>% hc_caption(text = "The Change in Mobility metric looks at how much people are moving around and compares it to a baseline period that predates most social distancing measures.<br> The baseline period for this dataset is the four weeks of February 2020 (i.e. from the 2nd to the 29th).", useHTML = TRUE)%>% hc_credits(text = "www.highcharts.com", href = "www.highcharts.com", enabled = TRUE, style = list(fontSize="10px")) %>% hc_tooltip(crosshairs = TRUE, borderWidth = 2, valueSuffix = "%") %>% hc_navigator(enabled = TRUE) %>% hc_rangeSelector(enabled = TRUE) %>% hc_plotOptions(series = list(marker = list(enabled = FALSE), lineWidth = 4)) %>% hc_add_annotation(labels = list(list(point = list(xAxis = 0,yAxis = 0,x = datetime_to_timestamp(as.Date('2020-07-13', tz = 'UTC')),y = 7),shape = "rect", text = "10th July: QLD opens borders", useHTML = TRUE))) %>% hc_add_annotation(labels = list(list(point = list(xAxis = 0,yAxis = 0,x = datetime_to_timestamp(as.Date('2020-07-20', tz = 'UTC')),y = -22),shape = "rect", text = "30th June: Vic in lockdown", useHTML = TRUE))) %>% hc_add_annotation(labels = list(list(point = list(xAxis = 0,yAxis = 0,x = datetime_to_timestamp(as.Date('2020-08-20', tz = 'UTC')),y = -30),shape = "rect", text = "2nd Aug: Vic restrictions ease", useHTML = TRUE))) %>% hc_add_annotation(labels = list(list(point = list(xAxis = 0,yAxis = 0,x = datetime_to_timestamp(as.Date('2020-11-14', tz = 'UTC')),y = -41),shape = "rect", text = "16th Nov: SA restrictions in place<br>21st Nov: SA restrictions lifted", useHTML = TRUE))) hc }) output$heatmap <- renderHighchart ({ hc1 <- areas_by_weeks %>% hchart(type = "heatmap", hcaes(x = date, y = polygon_name, value = AvRelChange)) %>% hc_title(text="Australians Mobility Changes", style=list(fontWeight="bold", fontSize="30px"), align="left") %>% hc_subtitle(text="During the coronavirus pandemic", style=list(fontWeight="bold"), align="left") %>% hc_boost(useGPUTranslations = TRUE) %>% hc_size(height = 5000, width = 550) %>% hc_colorAxis(labels = list(format = '{value}%'), stops = color_stops(10, rev(brewer.pal(10, "RdBu")))) %>% hc_legend(itemMarginTop = 75, layout = "vertical", verticalAlign = "top", align = "right", valueDecimals = 0) %>% hc_xAxis(labels = list(enabled = FALSE), tickInterval = 5, title = NULL, lineWidth = 0, tickLength = 20) %>% hc_yAxis(title=list(text = ""), reversed = TRUE, gridLineWidth = 0) %>% hc_tooltip(pointFormat = '{point.date} <br> {point.polygon_name}: <b>{point.value} %') %>% hc_credits(position = list(align = 'center', x = 135, y = -4), text = "www.highcharts.com", href = "http://www.highcharts.com", enabled = TRUE, style = list(fontSize="10px")) %>% hc_caption(align = 'center', text = "The white coloured boxes in the heatmap represent gaps in data.", useHTML = TRUE) hc1 }) } # Run the application shinyApp(ui = ui, server = server) If a clever cookie can please advise on what changes I need to make to get the app working when the page loads with Firefox, that would be fabulous :)
Plotly subplots with shared legend in R
I have made twoplots using plotly, which are working fine individually, but when combined using subplot I can't seem to figure out how to combine the legends. I have tried to use showlegend = F in plot_ly in one of the plots, but this just removes it completely - what I want is to control both subplots with the same legend. My code is as follows: coronavirus_not_china <- coronavirus %>% filter(!(country == "China")) cases_not_china_plot <- coronavirus_not_china %>% group_by(type, date) %>% summarise(total_cases = sum(cases)) %>% pivot_wider(names_from = type, values_from = total_cases) %>% arrange(date) %>% mutate(active = confirmed - death - recovered) %>% mutate(active_total = cumsum(active), recovered_total = cumsum(recovered), death_total = cumsum(death)) %>% plot_ly(x = ~ date, y = ~ active_total, name = 'Active', fillcolor = '#1f77b4', type = 'scatter', mode = 'none', stackgroup = 'one', showlegend = F) %>% add_trace(y = ~ death_total, name = "Death", fillcolor = '#E41317') %>% add_trace(y = ~recovered_total, name = 'Recovered', fillcolor = 'forestgreen') %>% layout(title = "Distribution of Covid19 Cases outside China", legend = list(x = 0.1, y = 0.9), yaxis = list(title = "Number of Cases", showgrid = T)) coronavirus_china <- coronavirus %>% filter((country == "China")) cases_china_plot <- coronavirus_china %>% group_by(type, date) %>% summarise(total_cases = sum(cases)) %>% pivot_wider(names_from = type, values_from = total_cases) %>% arrange(date) %>% mutate(active = confirmed - death - recovered) %>% mutate(active_total = cumsum(active), recovered_total = cumsum(recovered), death_total = cumsum(death)) %>% plot_ly(x = ~ date, y = ~ active_total, name = 'Active', fillcolor = '#1f77b4', type = 'scatter', mode = 'none', stackgroup = 'one', showlegend = T) %>% add_trace(y = ~ death_total, name = "Death", fillcolor = '#E41317') %>% add_trace(y = ~recovered_total, name = 'Recovered', fillcolor = 'forestgreen') %>% layout(title = "Distribution of Covid19 Cases inside China", legend = list(x = 0.1, y = 0.9), yaxis = list(title = "Number of Cases", showgrid = F)) And I create the subplots as: subplot(cases_not_china_plot, cases_china_plot, nrows = 2, margin = 0.05, shareX = T) %>% layout(title="Coronavirus cases outside China and in China", ylab("Number of cases")) I am quite new to R, so if there is a smarter way to do what I desire, please let me know. With the above code, my output is:
How to filter Date (Year) in shiny based on sliderInput choice?
I am working with shiny and have a sliderInput() and selectInput() inside my ui.R file. I would like that based on the user choice of these both fields, to plot the selected data within hchart function. I am very close to solve the problem, but with my code, its just filtering the first number and the last number of the year and not everything between. I tried with the between function but it didnt work. This is my ui.R code: tabItem(tabName = "crimetypesbyyear", fluidRow( box( title = "Date", status = "primary", solidHeader = TRUE, width = 6, sliderInput("ctypeDate", label = "Select Year", min = 2001, max = 2016, step = 1, sep = '', value = c(2001,2016)) ), box( title = "Crime Type", status = "primary", solidHeader = TRUE, width = 6, height = 162, selectInput("ctypeCrimeType", label= "Select Crime Type", choices = unique(cc$Primary.Type)) ), box( title = "Plot", status = "danger", solidHeader = TRUE, width = 12, highchartOutput(outputId = "ctypeOutput") ), And this is my server.R code: output$ctypeOutput <- renderHighchart({ ctypeAnalysis <- cc[cc$Primary.Type == input$ctypeCrimeType,] %>% group_by(Year2) %>% summarise(Total = n()) %>% filter(Year2 %in% cbind(input$ctypeDate[1],input$ctypeDate[2])) hchart(ctypeAnalysis %>% na.omit(), "column", hcaes(x = Year2, y = Total, color = Total)) %>% hc_exporting(enabled = TRUE, filename = paste(input$ctypeCrimeType, "by_Year", sep = "_")) %>% hc_title(text = paste("Crime Type by Year",input$ctypeCrimeType, sep = ": ")) %>% hc_subtitle(text = "(2001 - 2016)") %>% hc_xAxis(title = list(text = "Year")) %>% hc_yAxis(title = list(text = "Crimes")) %>% hc_colorAxis(stops = color_stops(n = 10, colors = c("#d98880", "#85c1e9", "#82e0aa"))) %>% hc_add_theme(hc_theme_smpl()) %>% hc_legend(enabled = FALSE) }) So this line of code should be corrected: ctypeAnalysis <- cc[cc$Primary.Type == input$ctypeCrimeType,] %>% group_by(Year2) %>% summarise(Total = n()) %>% filter(Year2 %in% cbind(input$ctypeDate[1],input$ctypeDate[2])), somebody any idea?
Since Year 2 is formatted as a factor, you need to convert it back to numeric values. You can do this in the same step as the filtering function, like so: ... filter(as.numeric(levels(Year2))[Year2] >= input$ctypeDate[1] & as.numeric(levels(Year2))[Year2] <= input$ctypeDate[2])