使用 javascript 的堆积条形图

Stacked bar plot using javascript

大家好,我正在尝试使用 canvasJS 为以下嵌套列表绘制堆叠条:

pepidstat=[[[2016, 61, 'Feb'], [2011, 367, 'Feb'], [2013, 83, 'Feb'], [2014, 89, 'Feb'], [2015, 106, 'Feb']], [[2016, 43, 'Jan'], [2011, 128, 'Jan'], [2013, 150, 'Jan'], [2014, 74, 'Jan'], [2015, 121, 'Jan']]]

我的可行 javascript 是:

<script type="text/javascript">
  window.onload = function () {
    var chartbar = new CanvasJS.Chart("chartContainerBar",
    {
      title:{
      text: "Yearly Growth of Total Peptides"
      },
      animationEnabled: true,
      axisX: {
    interval: 1,
    labelFontSize: 10,
    lineThickness: 0
      },

      data:pepiddata
    });

    chartbar.render();
    chartbar={};
  }
  var pepidstatlist = {{ pepidstat|safe }};
  var pepiddata = [];var pepiddataSeries = { type: "stackedBar",showInLegend: "true" };
  var pepidname= [];
  var pepiddataPoints = [];
  for (pi = 0; pi < pepidstatlist.length;pi++) {
    piname = pepidstatlist[pi][0][2];
    for (pj = 0; pj < pepidstatlist[pi].length;pj++) {
      pidx=pepidstatlist[pi][pj][0];
      pidy=pepidstatlist[pi][pj][1];
      pepiddataPoints.push({
    x:pidx,      
    y: pidy,
    label: pidx,
    name:piname,
    toolTipContent: "{name}-{label}:{y}",   
      });
    }
    pepiddataSeries.name = piname; // here I want pass each month name

  }
  pepiddataSeries.dataPoints = pepiddataPoints;
  pepiddata.push(pepiddataSeries); 
  </script>

除了我无法在数据系列中分配每个月的名称外,此脚本运行良好。你能建议我在哪里需要修改我的脚本吗? 谢谢

您只是在创建一个数据系列。创建两个dataSeries并将其推送到数据。其他一切正常。

 
pepidstat=[[[2011, 61, 'Feb'], [2012, 367, 'Feb'], [2013, 83, 'Feb'], [2014, 89, 'Feb'], [2015, 106, 'Feb']], [[2011, 43, 'Jan'], [2012, 128, 'Jan'], [2013, 150, 'Jan'], [2014, 74, 'Jan'], [2015, 121, 'Jan']]]

var pepidstatlist = pepidstat;
var pepiddata = [];
var pepidname= [];

for (pi = 0; pi < pepidstatlist.length;pi++) {
 piname = pepidstatlist[pi][0][2]; //month 
  var pepiddataPoints = [];
 for (pj = 0; pj < pepidstatlist[pi].length;pj++) {  
  pidx=pepidstatlist[pi][pj][0]; //Year
  pidy=pepidstatlist[pi][pj][1]; //value
  pepiddataPoints.push({
     x:pidx,      
     y: pidy,
     label: pidx,
     name:piname,
     toolTipContent: "{name}-{label}:{y}",   
  });
 }
  var pepiddataSeries = { type: "stackedBar", showInLegend: "true" };
 pepiddataSeries.name = piname; // here I want pass each month name
 pepiddataSeries.dataPoints = pepiddataPoints;
 pepiddata.push(pepiddataSeries);
}

var chartbar = new CanvasJS.Chart("chartContainer",
{
 title:{
  text: "Yearly Growth of Total Peptides"
 },
 animationEnabled: true,
 axisX: {
  interval: 1,
  labelFontSize: 10,
  lineThickness: 0
 },
 data: pepiddata,
});

chartbar.render();
<script src="http://canvasjs.com/assets/script/canvasjs.min.js"></script>
<br/><!-- Just so that JSFiddle's Result label doesn't overlap the Chart -->
<div id="chartContainer" style="height: 360px; width: 100%;"></div>

提示:根据数组中的年份值对数组进行排序。