javascriptplotlyplotly.js

Plotly value on plot being changed using a reference json


I am building a simple stock tracker which includes a volume graph. The volume is in the ranges of 1k +- 100, while the prices are in the range 1440 +- 5. Because of this if I add in the volume directly in the same graph it zooms out. So I scaled the volume accordingly. Now although they are in the same range, I want to see the actual value when I hover over it.

This is the code for plotting the volume

        const barTrace = {
    x: {{vol_x | safe}},
    y: {{vol_y | safe}},
    type: 'scatter',
    mode: 'lines',
    name: 'Volume',
    marker: {
      color: 'rgba(255, 0, 0, 0.3)' // Bar color
    }
  };
data.push(barTrace);

This is my current code for updating the value based on a reference id.

document.getElementById('graph').on('plotly_hover', function(data){
  data.points.forEach(function(hoverData){
    const traceName = hoverData.data.name; // Assuming curveNumber corresponds to the trace's index
    const value = hoverData.y;
    // Check if the hovered point belongs to the specific line
    if (traceName === 'Volume') {
      const reference = {{ vol_reference | safe }};
      const displayedValue = reference[value];
      console.log(displayedValue)
  }})
});

This logs the real value displayedValue to console. However I am stumped on how to replace the indicator next to volume. That is, the 1443.2 should be replaced with displayedValue.

Plotly chart

P.S. I am using flask so for those who are unaware {{value}} is replace with the real value which is either an array or json data


Solution

  • I suggest you use a secondary axis for the volume instead of re-scaling the values, by setting yaxis: 'y2' to the trace ('y2' refers to yaxis2 in the layout, which you can tweak like the primary axes) :

    const barTrace = {
      yaxis: 'y2',
      x: {{vol_x | safe}},
      y: {{vol_y | safe}},
      type: 'scatter',
      mode: 'lines',
      name: 'Volume',
      marker: {
        color: 'rgba(255, 0, 0, 0.3)' // Bar color
      }
    };
    data.push(barTrace);
    

    See also Multiple Axes in JavaScript.