I want to reproduce the default tooltip with some additions. However, when I try to do so, it left-aligns both serie and group names, and I am not sure how to fix it.
Some sample data and what I tried to do:
library(dplyr)
library(echarts4r)
library(htmlwidgets)
set.seed(10)
data <- data.frame(name = rep(c("Bob", "Michael"), each = 10),
x = rep(0:9, 2),
y = sample(0:5, 20, replace = TRUE),
add = sample(1:100, 20, replace = TRUE))
# Default tooltip
data %>%
group_by(name) %>%
e_chart(x = x) %>%
e_line(serie = y) %>%
e_tooltip(trigger = "axis")
# My attempt to recreate the formatting while adding new things
data %>%
group_by(name) %>%
e_chart(x = x) %>%
e_line(serie = y, bind = add) %>%
e_tooltip(trigger = "axis",
formatter = JS("
function(params){
var colorSpan = color => `<span style='display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:` + color + `'></span>`;
let rez = '<strong>Day ' + params[0].value[0] + '</strong>';
params.forEach(item => {
var xx = '<br />' + colorSpan(item.color) + ' ' + item.seriesName +
' <strong>' + item.value[1] + '</strong> (' + item.name + ')'
rez += xx;
});
return (rez)}"))
So, the default tooltip looks like this (values are right aligned):
And my tooltip looks something like this, which is not very readable:
I want to add things to the tooltip while keeping the formatting mostly untouched, but do not know how to do so with right alignment. I am not very familiar with echarts and JS in general though, so I have some troubles with it.
EDIT
So, thanks to @Russ we now have a workaround, which is not exactly what I was hoping to get, but a solution nonetheless. Does not look as pretty as the default tooltip, but for now we have what we have.
Still, @Russ's solution does have some issues, so I post my edited version of his answer here. Not sure how to apply css to echarts' tooltip to remove margins caused by <pre>
tag, but that does not matter too much right now
# Adding whitespaces after the name
data <- data %>%
mutate(nameAlt = stringr::str_pad(name, max(nchar(name)), "right"))
data %>%
group_by(nameAlt) %>%
e_chart(x = x) %>%
e_line(serie = y, bind = add) %>%
e_tooltip(trigger = "axis",
formatter = JS("
function(params){
var colorSpan = color => `<span style='display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:` + color + `'></span>`;
let rez = '<strong>Day ' + params[0].value[0] + '</strong><pre>';
params.forEach(item => {
var xx = colorSpan(item.color) + item.seriesName +
'<span style=`float:right;margin-left:20px;`><strong>' + item.value[1] + '</strong> (' + item.name + ')</span></br>'
rez += xx;
});
rez += '</pre>'
return (rez)}")) %>%
# Removing whitespaces from the legend
e_legend(formatter = JS("function(name){return(name.trim())}"))
Result: