How to create a "mapbubble" map with {highcharter) with example? - r

Maybe it's duplicated with mapbubble does not work with highcharter highmaps but there was no answer to the question...
From the example taken at https://jkunst.com/highcharter/articles/maps.html with a map of type "mappoint", I try to achieve the same with "mapbubble". I created for this a column z
library(httr)
library(jsonlite)
library(geojsonio)
library(highcharter)
library(dplyr)
ausgeojson <- GET("https://raw.githubusercontent.com/johan/world.geo.json/master/countries/AUS.geo.json") %>%
content() %>%
fromJSON(simplifyVector = FALSE) %>%
as.json()
ausmap <- highchart(type = "map") %>%
hc_add_series(mapData = ausgeojson, showInLegend = FALSE)
ausmap
airports <- read.csv("https://raw.githubusercontent.com/ajdapretnar/datasets/master/data/global_airports.csv")
airports <- airports %>%
filter(country == "Australia", name != "Roma Street Railway Station")
airports <- airports %>%
mutate(z=runif(n=nrow(airports),min=1,max=20))
airp_geojson <- geojson_json(airports, lat = "latitude", lon = "longitude")
# works with mappoint
ausmap %>%
hc_add_series(
data = airp_geojson,
type = "mappoint",
dataLabels = list(enabled = FALSE),
name = "Airports",
tooltip = list(pointFormat = "{point.name}")
)
# doesn't work with mapbubble
ausmap %>%
hc_add_series(
data = airp_geojson,
type = "mapbubble",
value = "z",
dataLabels = list(enabled = FALSE),
name = "Airports",
tooltip = list(pointFormat = "{point.name}")
)

The problem is probably due to the fact that {highcharter} cannot access the other columns of the geojson file.
Example if I add another column to the tooltip argument in the mappoint case :
ausmap %>%
hc_add_series(
data = airp_geojson,
type = "mappoint",
dataLabels = list(enabled = FALSE),
name = "Airports",
tooltip = list(pointFormat = "{point.name} : {point.altitude}")
)
I don't see altitude :

Related

Tooltip missing value in maps highcharts not working (with R)

When creating a map in R with highcharter, I would like to include a tooltip for missing values. To be sure that nullFormat is recognized I included also a datalabel for missing values and this works.
So nullFormat datalabels is working.
But nullFormat for a tooltip is not working.
require(dplyr)
mapdata <- get_data_from_map(download_map_data("custom/usa-and-canada"))
glimpse(mapdata)
data_fake <- mapdata |>
select(code = `hc-a2`) |>
mutate(value = 1e5 * abs(rt(nrow(mapdata), df = 10)))
# value NT on not available
data_fake$value[data_fake$code == "AZ"] <- NA
glimpse(data_fake)
highchart(type = "map") |>
hc_chart(map = download_map_data("custom/usa-and-canada")) |>
hc_add_series(
data_fake
, joinBy = c("hc-a2", "code")
, name = "Fake data"
, dataLabels = list(enabled = TRUE, format = "{point.name}", nullFormat = "N/A")
) |>
hc_colorAxis(auxpar = NULL) |>
hc_tooltip(valueDecimals = 0, nullFormat = "Missing data")

Highcharts - Highcharter in R - Getting Tooltip values from df rather than map

I'm attempting to create a map graph with highlighted tiles using highcharter in R.
I managed to retrieve a JSON map, create a dataframe with my data, and generate a highcharter map graph. I'm now customizing the toolip, which should display the country name, region and the number integer in my dataframe's count column. Using the hc_tooltip() function returns the name and region, but doesn't find the values. I suspect this is due to the tooltip function looking in the map data rather than my dataframe. I'm unsure how to change that. Here's an example:
map <- "https://code.highcharts.com/mapdata/custom/world-highres.geo.json" %>%
GET() %>%
content() %>%
jsonlite::fromJSON(simplifyVector = FALSE)
sample_table <- data.frame(name = c("Spain","France","China"),
continent = c("Europe","Europe","Asia"),
occurences = c(150,70,120))
cols3 <- scales::viridis_pal(option = "turbo",
begin = 0.4,
direction = 1)(length(unique(sample_table$name)))
highchart(type = "map") %>%
hc_title(text = "Map Title") %>%
hc_subtitle(text = "Map Subtitle") %>%
hc_add_series_map(map = map, df = sample_table, joinBy = "name", value = "occurences",
dataLabels = list(enabled = TRUE
,format = "{point.properties.hc-a2}")
) %>%
hc_colors(cols3) %>%
hc_colorAxis(stops = color_stops(colors = cols3)) %>%
hc_tooltip(
useHTML = TRUE,
formatter = JS(
"
function(){
outHTML = '<b>' + this.point.name + '</b> <br>' + this.point.continent +
'</b> <br>' + this.point.occurences
return(outHTML)
}
"
))%>%
hc_mapNavigation(enabled = TRUE)
Where the table contains the following
name continent occurences
1 Spain Europe 150
2 France Europe 70
3 China Asia 120
As you can see from the image, I get the country and continent name as intended, but I do not get the number of occurrences. Is there a way to get the tooltip values from both the map data and the dataframe?
When you included hc_add_series_map you defined the value of the variable to chart as "occurences". To include this column in your formatter, try using:
this.point.value
instead of referencing the column name.
Here is the complete example:
library(highcharter)
library(httr)
map <- "https://code.highcharts.com/mapdata/custom/world-highres.geo.json" %>%
GET() %>%
content()
sample_table <- data.frame(name = c("Spain","France","China"),
continent = c("Europe","Europe","Asia"),
occurences = c(150,70,120))
cols3 <- scales::viridis_pal(option = "turbo",
begin = 0.4,
direction = 1)(length(unique(sample_table$name)))
highchart(type = "map") %>%
hc_title(text = "Map Title") %>%
hc_subtitle(text = "Map Subtitle") %>%
hc_add_series_map(map = map,
df = sample_table,
joinBy = "name",
value = "occurences",
dataLabels = list(enabled = TRUE,format = "{point.properties.hc-a2}")
) %>%
hc_colors(cols3) %>%
hc_colorAxis(stops = color_stops(colors = cols3)) %>%
hc_tooltip(
useHTML = TRUE,
formatter = JS(
"
function(){
outHTML = '<b>' + this.point.name + '</b> <br>' + this.point.continent +
'</b> <br>' + this.point.value;
return(outHTML)
}
"
)) %>%
hc_mapNavigation(enabled = TRUE)
Map

Plotly animated map not showing countries with NA values

I posted this in the plotly community forum but got absolutely no activity! Hope you can help here:
I have map time-series data, some countries don’t have data and plotly does not plot them at all. I can have them outlined and they look different but it appears nowhere that the data is missing there (i.e. I want a legend entry). How can I achieve this? Here is a reprex:
library(plotly)
library(dplyr)
data = read.csv('https://github.com/lc5415/COVID19/raw/master/data.csv')
l <- list(color = toRGB("grey"), width = 0.5)
g <- list(
scope = 'world',
countrycolor = toRGB('grey'),
showframe = T,
showcoastlines = TRUE,
projection = list(type = 'natural earth')
)
map.time = data %>%
plot_geo() %>%
add_trace(z = ~Confirmed, color = ~Confirmed, frame = ~Date, colors = 'Blues',
text = ~Country, locations = ~Alpha.3.code, marker = list(line = l)) %>%
colorbar(title = 'Confirmed') %>%
layout(
title = 'Number of confirmed cases over time',
geo = g
) %>%
animation_opts(redraw = F) %>%
animation_slider(
currentvalue = list(
prefix = paste0("Days from ",
format(StartDate, "%B %dnd"),": "))) %>%
plotly_build()
map.time
Note that the countries with missing data (e.g. Russia) have as many data points as all other countries, the issue is not that they do not appear in the dtaframe passed to plotly.
The obvious way to handle this is to create a separate labels column for the tooltip that reads "No data" for NA values (with the actual value otherwise), then make your actual NA values 0. This will give a uniform appearance to all the countries but correctly tells you when a country has no data.
map.time = data %>%
mutate_if(is.numeric, function(x) {x[is.na(x)] <- -1; x}) %>%
plot_geo() %>%
add_trace(z = ~Confirmed, color = ~Confirmed, frame = ~Date, colors = 'Blues',
text = ~Country, locations = ~Alpha.3.code,
marker = list(line = l)) %>%
colorbar(title = 'Confirmed') %>%
layout(
title = 'Number of confirmed cases over time',
geo = g
) %>%
animation_opts(redraw = F) %>%
animation_slider(
currentvalue = list(
prefix = paste0("Days from ",
format(StartDate, "%B %dnd"),": "))) %>%
plotly_build()
Which gives:

Get value in province label with highmaps in the highcharter package

I'm trying to get the value in the province label from this example:
library("dplyr")
library('highcharter')
library("viridisLite")
data("USArrests", package = "datasets")
data("usgeojson")
USArrests <- USArrests %>%
mutate(state = rownames(.))
highchart() %>%
hc_title(text = "Violent Crime Rates by US State") %>%
hc_subtitle(text = "Source: USArrests data") %>%
hc_add_series_map(usgeojson, USArrests, name = "Murder arrests (per 100,000)",
value = "Murder", joinBy = c("woename", "state"),
dataLabels = list(enabled = TRUE,
format = '{point.properties.postalcode}'))
I want to have the value 'Murder' from the USArrests in the dataLabels rather than the state abbr. How should this be done?
Thanks,
Tim
To change dataLabels format you could add map serie like:
hc_add_series_map(usgeojson, USArrests, name = "Murder arrests (per 100,000)",
value = "Murder", joinBy = c("woename", "state"),
dataLabels = list(enabled = TRUE,
format = '{point.value}'))
Important here is format = '{point.value}' - this will make Highcharts use value of a point and a value is set in point from "Murder" (value = "Murder").

Displaying datatable in highcharter tooltip

Using the first block of code in this post I want to create a tooltip that would display the list of doctors visiting a clinic on a particular day.I tried the following code which displays nothing
library(DT)
tltp = DT:: datatable(data.frame(Doctors = x[x$Clinic=="{point.series}"&x$VisitDate == "{point.x}",2]))
hc%>%hc_tooltip(pointFormat = tltp)
I also tried using the tooltip_table which gives error
tltp = tooltip_table(x = NULL, y = x[x$Clinic=="{point.series}"&x$VisitDate == "{point.x}",2]
hc%>%hc_tooltip(pointFormat = tltp)
Error: unexpected symbol in:
"tltp = tooltip_table(x = NULL, y = x[x$Clinic=="{point.series}"&x$VisitDate == "{point.x}",2]
tltp"
Apologies I am not fluent in writing javascript.
As the official page recommend, to use highcharter is good alternative read how highchartsjs works. So, see this example with a simple custom tooltip.
hc <- hchart(visits, "column", x = as.Date(VisitDate), y = freq, group = Clinic) %>%
hc_plotOptions(column = list(
dataLabels = list(enabled = FALSE),
stacking = "normal",
enableMouseTracking = TRUE)
)
Adding the simple tooltip using the column names: Clinic and freq
hc %>%
hc_tooltip(pointFormat = "this is and clinic {point.Clinic} and freq {point.freq}")
The tooltip_table function is to make tables in the tooltip:
tt <- tooltip_table(c("Clinic", "Freq"), c("{point.series.name}", "{point.y}"))
hc %>%
hc_tooltip(pointFormat = tt, useHTML = TRUE)
If you need other data to show in the tooltip you can create the columun:
visits$doctors <- sample(letters, size = nrow(visits))
And then create the chart again (using the new data) and use this column in the tooltip:
hchart(visits, "column", x = as.Date(VisitDate), y = freq, group = Clinic) %>%
hc_plotOptions(column = list(
dataLabels = list(enabled = FALSE),
stacking = "normal",
enableMouseTracking = TRUE)
) %>%
hc_tooltip(pointFormat = "Here is the doctor {point.doctors}")

Resources