如何使用ChartJS创建堆叠图

时间:2016-08-24 15:45:26

标签: javascript backbone.js graph charts chart.js

截至目前,我已成功使用ChartJS创建了折线图。但我想把它叠加成图形。

以下是我现在所拥有的:

define(['backbone'], function(Backbone)
{
    var fifthSubViewModel = Backbone.View.extend(
    {
        template: _.template($('#myChart5-template').html()),

        render: function(){
          $(this.el).html(this.template());
          var ctx = this.$el.find('#lineChart5')[0];
          var lineChart = new Chart(ctx, {
          type: 'line',
            data: {
              labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
              datasets: [{
                label: "Unavailable Unit",
                backgroundColor: "rgba(38, 185, 154, 0.31)",
                borderColor: "rgba(38, 185, 154, 0.7)",
                pointBorderColor: "rgba(38, 185, 154, 0.7)",
                pointBackgroundColor: "rgba(38, 185, 154, 0.7)",
                pointHoverBackgroundColor: "#fff",
                pointHoverBorderColor: "rgba(220,220,220,1)",
                pointBorderWidth: 1,
                data: this.model.attributes.unavailThisYear
              }, {
                label: "Vacant Unit",
                backgroundColor: "rgba(3, 88, 106, 0.3)",
                borderColor: "rgba(3, 88, 106, 0.70)",
                pointBorderColor: "rgba(3, 88, 106, 0.70)",
                pointBackgroundColor: "rgba(3, 88, 106, 0.70)",
                pointHoverBackgroundColor: "#fff",
                pointHoverBorderColor: "rgba(151,187,205,1)",
                pointBorderWidth: 1,
                data: this.model.attributes.vacThisYear 
              }]
            },
            options: {
              scales: {
                yAxes: [{
                  scaleLabel: {
                    display: true,
                    labelString: 'Income in $'
                  }
                }]
              }
            }
          });
        },
        initialize: function(){
            console.log("In the initialize function");
            this.listenTo(this.model, 'change', this.render);
            this.listenTo(this.model, 'destroy', this.remove);
            this.render();
        }   
    });

    return fifthSubViewModel;
});

目前,我在一张图表上获得了两个折线图。但我不知何故想让它们堆叠起来。我的意思是第二个线图起点应该是第一个线图的位置。因此,该区域不应重叠。有什么方法可以告诉我的折线图从其他折线图结束的值开始,以便得到堆叠图。

当前屏幕截图未堆叠:

enter image description here

1 个答案:

答案 0 :(得分:2)

根据最新chartjs版本的文档,您需要在要堆叠它们的轴上将stacked属性设置为true。所以在你的情况下,它将是:

       options: {
          scales: {
            yAxes: [{
              scaleLabel: {
                display: true,
                labelString: 'Income in $'
              },
              stacked: true
            }]
          }
        }

有关更多信息,请转到ChartJs Docs