Search code examples
javascriptchartsplotlystacked-area-chart

How do I display both value and name in stacked area chart in plotly.js?


In the solution provided by @emackey in the link below, it displays only value in the solution, not the name of the trace. How do I display the names too, not only the values?

How do I make stacked area chart in plotly.js with correct values?

// This code was provided by emackey in stackoverflow

var stacksDiv = document.getElementById("myDiv");
var traces = [
    {x: [1,2,3], y: [2,1,4], fill: 'tozeroy'},
    {x: [1,2,3], y: [1,1,2], fill: 'tonexty'},
    {x: [1,2,3], y: [3,0,2], fill: 'tonexty'}
];
function stackedArea(traces) {
    var i, j;
    for(i=0; i<traces.length; i++) {
        traces[i].text = [];
        traces[i].hoverinfo = 'text';
        for(j=0; j<(traces[i]['y'].length); j++) {
            traces[i].text.push(traces[i]['y'][j].toFixed(0));
        }
    }
    for(i=1; i<traces.length; i++) {
        for(j=0; j<(Math.min(traces[i]['y'].length, traces[i-1]['y'].length)); j++) {
            traces[i]['y'][j] += traces[i-1]['y'][j];
        }
    }
    return traces;
}

Plotly.newPlot(stacksDiv, stackedArea(traces), {title: 'stacked and filled line chart'});
// This code was provided by emackey in stackoverflow


<script src="https://cdn.plot.ly/plotly-1.2.1.min.js"></script>
<div id="myDiv" style="width: 480px; height: 400px;"></div>


Solution

  • You just need to change one line:

    traces[i].hoverinfo = 'text';
    

    should become

    traces[i].hoverinfo = 'text+name';