如何在plotly.js中使用正确的值制作堆积面积图?

时间:2016-01-07 14:24:42

标签: javascript charts plotly

堆积区域图表有example

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'});

但堆叠是手动完成的,因此值不正确:

enter image description here

当您将鼠标悬停在第一条垂直线上时,您会看到值2,3和6。 但是如果你查看源代码,正确的值是2,1和3。

有没有办法为具有正确值的区域图表进行堆叠?

1 个答案:

答案 0 :(得分:3)

在对堆积图表求和的值之前,原始值可用作悬停信息的文本标签。

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>