Which event is triggered when a shape has been drawn with Plotly ("Draw line" toolbar icon)?

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.

I didn’t find this in the Plotly Python documentation about shapes (and also not in the JS doc).

<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, {}, {modeBarButtonsToAdd: ["drawline"]});
</script>

Hi,

I would assume, the relayoutData is getting changed. At least the shape information pops up in the Relayout Data

I adapted the example here (added a button for rectangular shapes). The screenshot shows the Relayout data right after drawing the rectangle.

2 Likes

Thanks a lot, I’ll try this!

Would you know how to delete all previous shapes when a new shape has been drawn?

Something along this line, but with remove/delete instead of visible=false? :slight_smile:

myDiv.on('plotly_relayout', (event) => {
    console.log(event);
    if ('shapes' in event) {
         Plotly.relayout($('#map'), { 'shapes[0].visible': false });
    }
});

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.