Display variable names when hovering a scatter plot

Tags: , ,



Here’s a plot made with {echarts4r} that comes from this answer on GitHub:

library(echarts4r)
library(tibble)

mtcars %>%
  rownames_to_column("model") %>%  
  e_charts(mpg) %>%
  e_y_axis(drat) %>%
  e_scatter(drat, symbol_size = 15, bind = model, scale = NULL) %>%
  e_tooltip(formatter = htmlwidgets::JS("
              function(params){
                return('<strong>' + params.name +  
              '</strong><br />x-axis: ' + params.value[0] +  
                '<br />y-axis: ' + params.value[1]
                )} 
              "))

As you can see, the name of the car model and the values are displayed when you hover a point. However, I don’t know how to display the variable names in the same way. I know I could manually replace “x-axis” and “y-axis” with their names but I would like to do it automatically.

I checked the documentation of echarts about this, but using {a} (for example) does not work.

Any idea?

Edit: I use echarts4r 0.3.3

Answer

The thing that you are asking for does not exist in the params passed for e_tooltip. you can access them by passing params to the console.log and inspecting this log in the browser:

mtcars %>%
  rownames_to_column("model") %>%  
  e_charts(mpg) %>%
  e_y_axis(drat) %>%
  e_scatter(drat, symbol_size = 15, bind = model, scale = NULL) %>%
  e_tooltip(formatter = htmlwidgets::JS("
              function(params){
              var obj_str = JSON.stringify(params);
              console.log(obj_str);
                return('<strong>' + params.name +  
              '</strong><br />' + params.seriesName + ': ' + params.value[0] +  
                '<br />mpg: ' + params.value[1]
                )} 
              "))

you will note that the x-axis name is under params.seriesName but the y-axis name is not found.

here is an example of what you’d find if you were to inspect the console.log for params:

{"componentType":"series",
  "componentSubType":"scatter",
  "componentIndex":0,
  "seriesType":"scatter",
  "seriesIndex":0,
  "seriesId":"u0000dratu00000",
  "seriesName":"drat",
  "name":"Ford Pantera L",
  "dataIndex":9,
  "data":{"value":[15.8,4.22],
  "name":"Ford Pantera L"},
  "value":[15.8,4.22],
  "color":"#c23531",
  "dimensionNames":["x","y"],
  "encode":{"x":[0],"y":[1]},
  "marker":"<span style="display:inline-block;
            margin-right:5px;
            border-radius:10px;
            width:10px;height:10px;
            background-color:#c23531;"></span>",
  "$vars":["seriesName","name","value"]
}

In this case, the paste0 approach of @Edo below seems very reasonable.



Source: stackoverflow