Change title using dropdown

Question

We would like to change the figure title based on the dataset selected in the dropdown. Following the tutorial here, we tried the following:

var trace1 = {
    x: [0,1,2,3],
    y: [0,1,2,3],
    mode: 'lines+markers',
    type: 'scatter',
    name: 'data 1',
    visible: true
}

var trace2 = {
    x: [0,1,2,3],
    y: [0,1,4,9],
    mode: 'lines+markers',
    type: 'scatter',
    name: 'data 2',
    visible: false
}

var data = [trace1, trace2];

var layout = {
    title: {
        'text': 'Title to change'
    },
    xaxis: {
        title: {
            'text': 'x'
        }
    },
    updatemenus: [{
        x: -0.1,
        xanchor: 'right',
        y: 0.5,
        yanchor: 'bottom',
        type: 'dropdown',
        buttons: [{
            method: 'restyle',
            args: [{'visible': [true, false], 'line.color': 'red', 'title.text': 'Title 1'}],
            label: 'Data set 0'
        }, {
            method: 'restyle',
            args: [{'visible': [false, true], 'line.color': 'blue', 'title.text': 'Title 2'}],
            label: 'Data set 1'
        }]
    }],
};

pltDiv = document.getElementById('tester');
Plotly.plot(pltDiv, data, layout);

Switching between the datasets via the dropdown correctly changes the visibility and line colors of the plots, but does not change the plot titles.

Any help would be appreciated, thank you :).

title.text is a layout attribute, so you can’t update it using restyle which acts on traces. You need to invoke Plotly.update for that

So, something like:

        buttons: [{
            method: 'update',
            args: [{'visible': [true, false], 'line.color': 'red'}, {'title.text': 'Title 1'}],
            label: 'Data set 0'
        }, {
            method: 'update',
            args: [{'visible': [false, true], 'line.color': 'blue'}, {'title.text': 'Title 2'}],
            label: 'Data set 1'
        }]

should work.

More info on Plotly.update here:

Thank you very much for the help :). We had tried invoking ‘update’, but hadn’t specified the ‘title.text’ attribute in a separate object in the ‘args’ array. It all works now.

Best wishes.

1 Like