The following code works to add a “Draw line” button in the toolbar: live demo
How to get notified (with an event) when a new line has been drawn with Plotly JS?
In my case I want to do a fetch(...) request when a line has been drawn, and also remove the previous drawn line if any. Indeed, there should be only 1 line on the plot.
Hi @stamljf , I don’t know about JS, but in python the shapes are stored in a list. Here is an example app where I delete some shapes based on the name:
Thanks @AIMPED. This works: when we draw a second line, it erases both the previous one and the current one: live demo.
<script src="https://cdn.plot.ly/plotly-2.16.2.min.js"></script>
<div id="myDiv"></div>
<script>
var data = [{x: [1, 2, 3, 4], y: [10, 15, 13, 17], mode: 'markers'}];
Plotly.newPlot('myDiv', data, {}, {modeBarButtons: [["drawline"]]});
var myDiv = document.getElementById('myDiv');
myDiv.on('plotly_relayout', (event) => {
if ('shapes' in event) {
if (event["shapes"].length > 1) {
console.log(event["shapes"].slice(-1));
Plotly.relayout(myDiv, { shapes: [] });
}
}
});
</script>
Would you know how to remove the first line when we draw a second line? It would be a better UX: we only keep one line. When drawing a second line, we remove the previous one.