When using the highcharter package in R, I am attempting to plot multiple line charts simultaneously. The challenge arises when dealing with different datasets containing values ranging from millions to billions, requiring a numeric symbols formatter implemented through JS. However, this approach unintentionally modifies date formats and groups all information into a single box.
My goal is to generate line plots resembling those depicted in this image.
Data:
structure(list(Date = structure(c(17256, 17347, 17439, 17531,
17621, 17712, 17804, 17896, 17986, 18077, 18169, 18261, 18352,
18443, 18535, 18627, 18717, 18808, 18900), class = "Date"), Amount = c(23046000,
22207000, 16127000, 15341000, 16529000, 16646000, 27638000, 25777000,
28478000, 20579000, 13703000, 24954000, 27012000, 18010000, 13332000,
21300000, 15122000, 17606000, 17110000)), row.names = c(NA, -19L
), class = c("data.table", "data.frame"))
structure(list(Date = structure(c(17256, 17347, 17439, 17531,
17621, 17712, 17804, 17896, 17986, 18077, 18169, 18261, 18352,
18443, 18535, 18627, 18717, 18808, 18900), class = "Date"), Amount = c(2025000,
2217000, 2122000, 2893000, 3352000, 2837000, 4073000, 1916000,
2170000, 2663000, 11215000, 11834000, 10065000, 5382000, 6461000,
4929000, 5282000, 4386000, 5186000)), row.names = c(NA, -19L), class = c("data.table",
"data.frame"))
Code:
library(highcharter)
library(dplyr)
highchart(type = "stock") %>%
hc_add_series(data= data1,hcaes(x= Date, y = Amount),type = "line") %>%
hc_add_series(data= data2,hcaes(x= Date, y = Amount),type = "line")
Sample utilizing a tooltip formatter:
library(highcharter)
library(dplyr)
js <- JS("function () {
function test(labelValue) {
const sign = Math.sign(Number(labelValue));
// Nine Zeroes for Billions
return Math.abs(Number(labelValue)) >= 1.0e12
? sign * (Math.abs(Number(labelValue)) / 1.0e12).toFixed(2) + 'T'
: // Six Zeroes for Millions
Math.abs(Number(labelValue)) >= 1.0e9
? sign * (Math.abs(Number(labelValue)) / 1.0e9).toFixed(2) + ' B'
: // Three Zeroes for Thousands
Math.abs(Number(labelValue)) >= 1.0e6
? sign * (Math.abs(Number(labelValue)) / 1.0e6).toFixed(2) + ' M'
: // Three Zeroes for Thousands
Math.abs(Number(labelValue)) >= 1.0e3
? sign * (Math.abs(Number(labelValue)) / 1.0e3).toFixed(2) + ' K'
: Math.abs(Number(labelValue));
};
return this.points.reduce(function (s, point) {
return s + '<br/>' + point.series.name + ': ' +
test(point.y);
}, '<b>' + this.x + '</b>');
}
")
highchart(type = "stock") %>%
hc_add_series(data= data1,hcaes(x= Date, y = Amount),type = "line") %>%
hc_add_series(data= data2,hcaes(x= Date, y = Amount),type = "line") %>%
hc_tooltip(formatter = js)
Output: with formatted tooltips