JohnCoene / echarts4r

🐳 ECharts 5 for R
http://echarts4r.john-coene.com/
Other
585 stars 82 forks source link

How to put javascript function in json rendered by e_inspect()? #560

Closed rdatasculptor closed 10 months ago

rdatasculptor commented 10 months ago

Consider this chart:

USArrests |>
  e_charts(Assault) |>
  e_scatter(Murder) |>
  e_tooltip(formatter = htmlwidgets::JS("
          function(params){
            return('Assault: ' + params.value[0] + 
          '<br />Murder: ' + params.value[1])
          }
        ") )

The chart contains tooltips:

image

So what if I change the chart first in a json by using e_inspect() and change it back again to an echart by using echarts_from_json()? like this:

USArrests |>
  e_charts(Assault) |>
  e_scatter(Murder) |>
  e_tooltip(formatter = htmlwidgets::JS("
          function(params){
            return('Assault: ' + params.value[0] + 
          '<br />Murder: ' + params.value[1])
          }
        ") ) |> 
  e_inspect(json = TRUE) |>
  echarts_from_json()

this is the result:

image

Obviously the tooltip javascript function is not recogized anymore.

Any ideas about how to deal with this? Is there a way (in R) to store the javascript function of the tooltip in the json in such a way that it can retrieved properly after changing it back to an echart?

munoztd0 commented 10 months ago

As always nice catch/riddle @rdatasculptor. Just added new feature in #561 so just install the github version of echarts4r and add the jswrapper = TRUE flag

library(echarts4r)

plot <- USArrests |>
  e_charts(Assault) |>
  e_scatter(Murder) |>
  e_tooltip(
    formatter = htmlwidgets::JS("function(params){return('Assault: ' + params.value[0] +'<br />Murder: ' + params.value[1])}        ")
    ) |> 
  e_inspect(json = TRUE, pretty =TRUE) |>
  echarts_from_json(jswrapper = TRUE)

plot

Let me know how it goes !

rdatasculptor commented 10 months ago

great work @munoztd0 !!! it works like a charm :) You solved this one really fast. Very cool.

Another (entirely different) issue is that the json doesn't contain the renderer parameter if you set it as "svg". Do you think that can be added to the json as well somehow? Maybe I will file another issue for that.

munoztd0 commented 10 months ago

Can you please open a new issue for this

rdatasculptor commented 9 months ago

@munoztd0 Take a look at what @helgasoft did: https://github.com/helgasoft/echarty/issues/3#issuecomment-1728137024 Very interesting approach. I will dig into this. Not sure yet if echarts4r can benefit from it.

Edit. Don't think it is much different from your approach 🧐, but cool anyway!