'Plotly JS - replace Y data dynamically and redraw chart

I have a Plotly.JS chart with altitude chart in meters.

What I want to do is a button, where the user can click to change the units from meters to feet, or back from feets to meters. The chart of course should update.

HTML part:

<head>
  <!-- Plotly.js -->
    <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>

<body>
<button id="btn" onclick="myFunction()">meters/feet</button>
<div id="altitudeDiv" class="plot_synchro" style="width: 99%"></div>
</body>

JS part:

var data_alt = [{
  x: ['2022-03-01 10:50', '2022-03-01 11:50', '2022-03-01 12:50'],
  y: [100, 120, 110],
  type: 'scatter',
  line: {
    color: '#347C2C'
  },
  fill: 'tozeroy',
}];
var layout = {
  height: 200,
  margin: {
    l: 35,
    r: 20,
    b: 50,
    t: 10,
    pad: 5
  },
  automargin: true,

};

var options = {
  displayModeBar: false,
  responsive: true
};

Plotly.newPlot('altitudeDiv', data_alt, layout, options);

function myFunction() {
    alert('test');
  // here we should change the X values from meters to feet
  // feet = meters * 3.2
  // or from feet back to meters
  
  // I can add new data but not sure how to iterate over existing data and replace the values
  data_alt[0]['x'][4] = '2022-03-01 13:50';
  data_alt[0]['y'][4] = '115';
  Plotly.redraw('altitudeDiv');
  
}

The JS Fiddle: https://jsfiddle.net/a2m68nzu/



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source