Reputation: 2982
There is an example of a stacked area chart:
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) {
for(var i=1; i<traces.length; i++) {
for(var 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'});
But stacking is done manually, so values are not correct:
When you mouse over the first vertical line, you see values 2, 3 and 6. But if you look in the source code, correct values are 2, 1 and 3.
Is there a way to get stacking for area charts with correct values?
Upvotes: 1
Views: 2827
Reputation: 12418
The original values can be used as text labels for the hover info, prior to the values being summed for the stacked chart.
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'});
<script src="https://cdn.plot.ly/plotly-1.2.1.min.js"></script>
<div id="myDiv" style="width: 480px; height: 400px;"></div>
Upvotes: 3