To add this information, I've written a JS function that goes into the call for e_tooltip
. There is only one element that I can't get dynamically—the row count for the data.
In the JS, where you see the number 32, that's the only information you would have to update in this code (other than the data in the e_
functions).
Assumptions:
- the
binwidth
was not specified when calling for the histogram (echarts4r
calculated bin width)
- the plot's first series is a histogram
- the plot's second series is density
Use the row count and this function to create the formatted tooltip your looking for.
ttFrm <- function(rowCt) { # use row count to call function
htmlwidgets::JS(paste0("
function(data) {
console.log(data);
h = data[0]; /* histogram */
d = data[1]; /* density */
bc = h.value[1]; /* bin count */
ds = d.value[1]; /* density */
/* bin width = count in bin / count in dataset / density */
br = bc/", rowCt, "/ds/2; /* bin span divided by two */
bL = h.axisValue - br; /* bin low */
bH = h.axisValue + br; /* bin high */
return(
'<b>' + bL + ' - ' + bH + '</b><br /><span style=\"color:' +
h.color + ';\">●</span> ' + h.seriesName +
'<b style=\"padding-left: 2em;\">' +
bc + '</b><br /><span style=\"color:' +
d.color + ';\">●</span> ' + d.seriesName +
'<b style=\"padding-left: 2em;\">' +
ds + '</b><br/>')
}"))
}
Here's an example of how you can apply this formatting. (The call for the plot is from an echarts4r
example plot.)
mtcars |>
e_charts(elementId = 'chart') |>
e_histogram(mpg, name = "histogram") |>
e_density(mpg, areaStyle = list(opacity = .4),
smooth = TRUE, name = "density", y_index = 1) |>
e_tooltip(
trigger = "axis", confine = T,
textStyles = list(overflow = "breakall", width = 50),
formatter = ttFrm(nrow(mtcars))) # <<---- I'm new!!

Here's another example. Here I swapped out the data for the iris
dataset.
iris |>
e_charts(elementId = 'chart') |>
e_histogram(Sepal.Width, name = "histogram") |>
e_density(Sepal.Width, areaStyle = list(opacity = .4),
smooth = TRUE, name = "density", y_index = 1) |>
e_tooltip(
trigger = "axis", confine = T, digits = 3,
textStyles = list(overflow = "breakall", width = 50),
formatter = ttFrm(nrow(iris)))
