Search code examples
plotlykotlin-multiplatform

Plotly.kt Shows Image in Tooltip Hover


I am using Plotly.kt in a Kotlin/JS application and I want to show image, video and another chart when hovering on a data point on the graph. According to this, it is possible to disable the default hover by setting hoverinfo = none. However, I did not find a way to listen to the hover event. Could anyone help on this?


Solution

  • The plot div object of PlotlyJS implements the .on() method for processing the PlotlyJS event, which is discussed in here. However, the .on() method is not wrapped in Plotly.kt. So, a temporary solution is to treat the plotDiv as dynamic, so that the .on() method can be used without compilation error. Or, use the js() function to run the Javascript code directly.

    The following is adapted from this official example.

    private fun drawDeserialization(element: HTMLElement): Unit {
        val plot = Plotly.plot {
            scatter {
                x(1, 2, 3, 4)
                y(10, 15, 13, 17)
                mode = ScatterMode.markers
                type = TraceType.scatter
                hoverinfo = "none"
            }
        }
        val serialized = plot.toJsonString()
        val deserialized = Plot(Json.decodeFromString(MetaSerializer, serialized as String).toMutableMeta())
    
        element.append.plotDiv(plot = deserialized)
    
        // option 1: Get synamic reference to the plotDiv object
        val pdiv: dynamic = element?.firstElementChild
        pdiv.on("plotly_click") { event -> alert("Caught Hovering Event!") }
    
        // option 2: Run the Javascript code directly
        js("pdiv.on('plotly_click', function() {alert('Caught Hovering Event!');})")
    }