Reputation: 942
I am trying to create a custom tooltip that in echarts4r
, shows in an addition to the values of the different stacks, also shows the total (equal to the height of the bar): so something like this (from chart.js: Place tooltip for stacked bar charts on top of bar):
This codes just misses the totals
library(echarts4r)
library(tidyverse)
set.seed(2018)
dt <- data.frame(a =letters[1:10],
x = rnorm(10, mean = 20, sd = 5),
y = rnorm(10, mean = 20, sd = 5),
z = rnorm(10, mean = 10, sd = 5))
dt %>%
mutate(total = x +y +z) %>%
e_charts(a) %>%
e_bar(x, stack = "stack") %>%
e_bar(y, stack = "stack") %>%
e_bar(z, stack = "stack") %>%
e_grid(containLabel = T) %>%
e_tooltip(trigger = "axis")
This code shows the data somewhat OK, but does not have the right labels and is not as pleasing to look at (for example misses the colour code)
dt %>%
mutate(total = x +y +z) %>%
e_charts(a) %>%
e_bar(x, stack = "stack", bind = total) %>%
e_bar(y, stack = "stack", bind = total) %>%
e_bar(z, stack = "stack", bind = total) %>%
e_grid(containLabel = T) %>%
e_tooltip(formatter = htmlwidgets::JS("
function(params)
{
return `<strong>${params.value[0]}</strong>
<br/> ${params.value[1]}
<br/>Total: ${params.name}`
} "))
Upvotes: 1
Views: 890
Reputation: 125687
Adapting this answer this could be achieved like so:
Note: Additionally I slightly increased the width, right aligned the numbers and computed the total inside the formatter function.
library(echarts4r)
library(tidyverse)
set.seed(2018)
dt <- data.frame(a =letters[1:10],
x = rnorm(10, mean = 20, sd = 5),
y = rnorm(10, mean = 20, sd = 5),
z = rnorm(10, mean = 10, sd = 5))
dt %>%
e_charts(a) %>%
e_bar(x, stack = "stack") %>%
e_bar(y, stack = "stack") %>%
e_bar(z, stack = "stack") %>%
e_grid(containLabel = T) %>%
e_tooltip(trigger = "axis", formatter = htmlwidgets::JS('
function (params) {
let tooltip = `<p style="width: 100px;">${params[0].axisValue}</p>`;
let total = 0
params.forEach(({ seriesName, marker, value }) => {
value = value || [0, 0];
tooltip += `<p style="width: 100px;">${marker} ${seriesName}<span style="float: right;"><strong>${value[1]}</strong></span></p>`;
total += Number(value[1]);
});
tooltip += `<p style="width: 100px;">Total<span style="float: right;"><strong>${total}</strong></span>`;
return tooltip;
}'))
Upvotes: 3