如何使用正确的值在 plotly.js 中制作堆积面积图?
How do I make stacked area chart in plotly.js with correct values?
有一个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'});
但是堆叠是手动完成的,所以值不正确:
当您将鼠标悬停在第一条垂直线上时,您会看到值 2、3 和 6。
但是如果您查看源代码,正确的值为 2、1 和 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>
有一个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'});
但是堆叠是手动完成的,所以值不正确:
当您将鼠标悬停在第一条垂直线上时,您会看到值 2、3 和 6。 但是如果您查看源代码,正确的值为 2、1 和 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>