Using both hc_motion and hc_drilldown in R Highcharter Map - r

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)
)

Related

Adding Images to animations in plotly (R)

I am trying to create an animation where an image has to move together with the dot that you can see in this image:
I have a dataset about Formula 1 and I want to show the image of the car instead of the dot in the image.
Here you have a summary of my dataset:
And the code of the graph:
prep = data[data$year == 2021,] %>% split(.$date) %>% accumulate(., ~bind_rows(.x,.y))%>%
bind_rows(.id = "frame")
prep2 = data[data$year == 2021,] %>% split(.$date) %>%
bind_rows(.id = "frame")
prep%>%
plot_ly(x = ~name, y = ~points, color = ~factor(name)) %>%
add_lines(frame = ~as.Date(frame, format = '%Y-%m-%d'))%>%
add_markers(data = prep2, frame = ~as.Date(frame, format = '%Y-%m-%d'))%>%
layout(yaxis = list(title = 'Puntos'),showlegend = FALSE,xaxis = list(title = 'Fecha de la carrera',range = c(as.Date(min(data$date[data$year == 2021]), format="%d/%m/%Y"),as.Date(max(data$date[data$year == 2021]), format="%d/%m/%Y"))))%>%
animation_slider(currentvalue = list(prefix = "Carrera "))

Mapview highlight SpatialLines upon hover

I want to highlight all lines going to a node/marker on a map in mapview. In the example code here, the nodes represent capital cities. Upon hovering on one of the cities, I would like all 4 lines going to/from that city to become highlighted. The hover option inside mapview had no effect, when I tried it. Thanks.
library(dplyr)
library(readr)
library(janitor)
library(sp)
library(purrr)
cc = read_csv("http://techslides.com/demos/country-capitals.csv")
nodes =
cc %>%
clean_names() %>%
mutate(capital_latitude = as.numeric(capital_latitude)) %>%
select(capital_name, capital_longitude, capital_latitude) %>%
filter(capital_name %in% c("Warsaw", "El-Aaiún", "Jamestown", "Antananarivo", "Manama"))
edges =
full_join(
nodes %>% rename(from = capital_name, from_lon = capital_longitude, from_lat = capital_latitude) %>% mutate(index = 1),
nodes %>% rename(to = capital_name, to_lon = capital_longitude, to_lat = capital_latitude) %>% mutate(index = 1),
by = "index") %>%
mutate(from_to = paste(from, "_", to)) %>%
filter(from != to) %>%
select(-index) %>%
rowwise() %>%
mutate(capital_lines = pmap(list(from_lon = from_lon, from_lat = from_lat, to_lon = to_lon, to_lat = to_lat, from_to = from_to),
function(from_lon, from_lat, to_lon, to_lat, from_to) {
Line(cbind(c(from_lon, to_lon),
c(from_lat, to_lat))) %>%
Lines(., ID = from_to)}
)) %>%
mutate(capital_lines = list(SpatialLines(list(capital_lines))))
mapview(nodes, xcol = "capital_longitude", ycol = "capital_latitude") +
mapview(do.call(rbind, edges$capital_lines))
library(mapview)
mapviewOptions(fgb = FALSE)
mapview(shp, highlight = leaflet::highlightOptions(color = "red", weight = 2, sendToBack = TRUE))
This works for me.
See details in https://github.com/r-spatial/mapview/issues/392.

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

Missing diacritics in GT table output

I am using GT package in R to create tables for my diploma thesis and I ran into a problem. The diploma is to be written in the czech language.
When GT draws the table it does not display the letter ě properly and shows e instead.
The code for GT table:
desc_sex[,2:ncol(desc_sex)] %>% gt(rowname_col = "sex"
) %>% tab_stubhead(
label = html("Kategorie")
) %>% cols_align(
align = "center",
columns = everything()
) %>% cols_label(
n = html("n"),
procent = html("%")
) %>% tab_row_group(
label = html("<b>Sledované regiony celkem"),
rows = 7:9
) %>% tab_row_group(
label = html("<b>Krajský soud v Ostravě"),
rows = 4:6
) %>% tab_row_group(
label = html("<b>Městský soud v Praze"),
rows = 1:3
) %>% summary_rows(
groups = T,
fns = list(
Celkem = ~sum(.)),
formatter = fmt_number,
decimals = 0
)
Here are the data in CSV compliant format:
"reg_reside","sex","n","procent","single"
"MSPH","Muž",93,46.5,52
"MSPH","Žena",83,41.5,34
"MSPH","Manželský pár",24,12,0
"KSOS","Muž",113,56.5,51
"KSOS","Žena",68,34,30
"KSOS","Manželský pár",19,9.5,0
"Celkem","Muž",206,51.5,103
"Celkem","Žena",151,37.8,64
"Celkem","Manželský pár",43,10.8,0
Here is how the output looks in GT - the mistake is in Ostrave (should be Ostravě) and Mestsky (should be Městský):
You can try using html entities like i.e. ě = &ecaron;
desc_sex[,2:ncol(desc_sex)] %>%
gt(rowname_col = "sex") %>%
tab_stubhead(label = html("Kategorie")) %>%
cols_align(align = "center",columns = everything()) %>%
cols_label(n = html("n"),
procent = html("%")) %>%
tab_row_group(label = html("<b>Sledované regiony celkem"),
rows = 7:9) %>%
tab_row_group(label = html("<b>Krajský soud v Ostrav&ecaron;"),
rows = 4:6) %>%
tab_row_group(label = html("<b>M&ecaron;stský soud v Praze"),
rows = 1:3) %>%
summary_rows(groups = T,
fns = list(Celkem = ~sum(.)),
formatter = fmt_number,
decimals = 0)

Resources