Get value in province label with highmaps in the highcharter package - r

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

Related

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

Highcharts in R: sort xAxis in Line Chart

I have a simple line chart, but some categories do not have all periods (xAxis), so the xAxis is not ordered at the end.
That is an example data:
The chart looks like that (with "2019-01" and "2019-03" exchanged)
Example Code
df <- data.frame(PERIODO = c("2017-01","2017-03","2018-01","2018-03",
"2018-03","2019-01",rep("2019-03",2),
"2020-01"),
CATEGORIA = c(rep("A",4),rep("B",2),"A","B","B"),
FRECUENCIA = c(2,3,3,1,2,4,1,1,2))
highchart() %>%
hc_xAxis(type = "category") %>%
hc_add_series(df, "line",
hcaes(x = PERIODO, y = FRECUENCIA,
group = CATEGORIA),
dataLabels = list(enabled = TRUE,
style = list(fontSize = '13px'))
) %>%
hc_legend(enabled = TRUE, align = "right",layout = 'vertical',verticalAlign= "middle") %>%
hc_tooltip(shared = TRUE, crosshairs = TRUE
,style = list(fontSize = "18px")
Someone knows about how to keep the xAxis order by PERIODO: 2017-01,2017-03,2018-01,2018-03,2019-01,2019-03,2020-01
Perhaps you can put your dates PERIODO in Date format (use first day of the month if you only have months).
df$PERIODO <- as.Date(paste0(df$PERIODO, "-01"))
Then, use type = "datetime" instead of category for your hc_xAxis argument. You can indicate what you want as labels on your x-axis using dateTimeLabelFormats.
highchart() %>%
hc_xAxis(type = "datetime",
dateTimeLabelFormats = list(month = '%b %Y')) %>%
...
Default labels and more information can be found here.

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

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 :

Creating an index bar chart in Highcharter

I'm trying to create a bar chart showing Cost of Living indexed to the U.S. value (100) in the Highcharter package in R. So I want the bars the start at 100 and either extend to the right or the left of 100. I have the basic bar chart down, but I can't figure out how to move the center line of the chart to 100. I'm trying to get it to look something like this: http://drawingwithnumbers.artisart.org/moving-the-center-line-of-a-bar-chart-with-a-gantt-chart/
Here's the data I'm working with:
States <- c('Tennessee','Michigan','Indiana','Ohio','Kentucky','West Virginia','North Carolina','Virginia','Pennsylvania','Delaware','New Jersey','Maryland','New York')
Cost_of_Living <- c(88.7,88.9,90,90.8,90.9,91.1,94.9,100.7,101.7,108.1,125.1,129.7,139.1)
costliving <- data.frame(States, Cost_of_Living)
And here's the code I have for the bar chart, just the basic bar chart
costliving_graph <- highchart() %>%
hc_title(text = "Cost of Living by State (2020)") %>%
hc_add_series (costliving, "bar", hcaes(x = States, y = Cost_of_Living)) %>%
hc_xAxis(categories = costliving$States) %>%
hc_yAxis(title = list(text = "Indexed to the U.S. (U.S. Value = 100)"))%>%
hc_plotOptions (bar = list(colorByPoint = TRUE)) %>%
hc_legend (enabled = FALSE)%>%
hc_tooltip(pointFormat = "MSA Regional Price Parities: {point.y}", headerFormat ="")
costliving_graph
Any help would be great! Thanks in advance
After checking examples on highcharter website I changed the charttype to columnrange and added new vars low and high to the dataframe. Try this:
library(highcharter)
library(dplyr)
States <- c('Tennessee','Michigan','Indiana','Ohio','Kentucky','West Virginia','North Carolina','Virginia','Pennsylvania','Delaware','New Jersey','Maryland','New York')
Cost_of_Living <- c(88.7,88.9,90,90.8,90.9,91.1,94.9,100.7,101.7,108.1,125.1,129.7,139.1)
costliving <- data.frame(States, Cost_of_Living) %>%
mutate(low = pmin(Cost_of_Living, 100),
high = pmax(Cost_of_Living, 100))
costliving_graph <- highchart() %>%
hc_title(text = "Cost of Living by State (2020)") %>%
hc_add_series(costliving, "columnrange", hcaes(x = States, y = Cost_of_Living, low = low, high = high)) %>%
hc_xAxis(categories = costliving$States) %>%
hc_yAxis(title = list(text = "Indexed to the U.S. (U.S. Value = 100)"))%>%
hc_plotOptions (bar = list(colorByPoint = TRUE)) %>%
hc_legend (enabled = FALSE)%>%
hc_tooltip(pointFormat = "MSA Regional Price Parities: {point.y}", headerFormat ="")
costliving_graph

Plotting two columns using highchart in R shiny returns argument object is missing with no value

I tried to make interactive map using R shiny which will show plot of male and female citizens in some cities. Data frame sample is shown below.
df1 <- read.table(header = TRUE, text = "city,year,male,female,long,lat
A,2017,1038,876,35.54331,139.12333
A,2018,1281,911,35.54331,139.12333
B,2017,832,517,35.14189,140.664113
B,2018,914,589,35.14189,140.664113", sep = ",")
df2 <- df1
The interactive map is built by using leaflet package and if the city marker is clicked, a plot which built by highchart will be shown.
output$chart <- renderHighchart({
df2 <- df1[df1$city == click_marker(),]
hchart() %>%
hc_add_series(df2, "column", hcaes(x = year, y = male, group = city, name = "Male")) %>%
hc_add_series(df2, "column", hcaes(x = year, y = female, group = city, name = "Female")) %>%
hc_xAxis(title = list(text = "Year")) %>%
hc_yAxis(title = list(text = "Amount (Thousands)"))
})
highchartOutput('chart')
I expect the output is a plot that show amount of male and female in the city for each year given but the output that I got is "argument object is missing, with no default."
What if you change hchart to highchart and the names to lowercase? Apparently they have to be found in the data.frame.
highchart() %>%
hc_add_series(df2, "column", hcaes(x = year, y = male, group = city, name = "male")) %>%
hc_add_series(df2, "column", hcaes(x = year, y = female, group = city, name = "female")) %>%
hc_xAxis(title = list(text = "Year")) %>%
hc_yAxis(title = list(text = "Amount (Thousands)"))

Resources