2016-11-06 134 views
1

Can Chart.js v2.x能够使用一个y轴生成包含2个拆散线的组合堆积条形图吗?如果是这样,怎么样?Chart.js v2 - 组合堆积条形图和2个拆散线

小提琴有2个y轴。下降线,如果右侧y轴的最大值为6000,那么渲染效果会更好,左轴也是如此。

jsfiddle example

以下是供参考的代码。

 // set default no fill beneath the line 
     Chart.defaults.global.elements.line.fill = false; 


     // stacked bar with 2 unstacked lines - nope 
     var barChartData = { 
      labels: ['2016', '2017', '2018', '2019'], 
      datasets: [{ 
      type: 'bar', 
      label: 'a', 
      yAxisID: "y-axis-0", 
      backgroundColor: "rgba(217,83,79,0.75)", 
      data: [1000, 2000, 4000, 5000] 
      }, { 
      type: 'bar', 
      label: 'b', 
      yAxisID: "y-axis-0", 
      backgroundColor: "rgba(92,184,92,0.75)", 
      data: [500, 600, 700, 800] 
      }, { 
      type: 'line', 
      label: 'c', 
      yAxisID: "y-axis-0", 
      backgroundColor: "rgba(51,51,51,0.5)", 
      data: [1500, 2600, 4700, 5800] 
      }, { 
      type: 'line', 
      label: 'd', 
      yAxisID: "y-axis-1", 
      backgroundColor: "rgba(151,187,205,0.5)", 
      data: [5000, 3000, 1000, 0] 
      }] 
     }; 


     var ctx = document.getElementById("chart").getContext("2d"); 
     // allocate and initialize a chart 
     var ch = new Chart(ctx, { 
      type: 'bar', 
      data: barChartData, 
      options: { 
      title: { 
       display: true, 
       text: "Chart.js Bar Chart - Stacked" 
      }, 
      tooltips: { 
       mode: 'label' 
      }, 
      responsive: true, 
      scales: { 
       xAxes: [{ 
       stacked: true 
       }], 
       yAxes: [{ 
       stacked: true, 
       position: "left", 
       id: "y-axis-0", 
       }, { 
       stacked: false, 
       position: "right", 
       id: "y-axis-1", 
       }] 
      } 
      } 
     }); 

回答

1

原来,我只需要一个修改或两个,所以2 y轴使用相同的规模。看到这个jsfiddle。现在图表呈现更好。关键的,在我的情况下,增加一个ticks节点,这两个属性既yAxes对象:

ticks: { 
    beginAtZero: true, 
    suggestedMax: 5800 
} 

当然,suggestedMax值不会被硬编码。此外,由于2个刻度现在相同,因此我通过此属性设置隐藏了正确的刻度display: false

随着小提琴演示,我们现在在堆叠的条形图上显示了2条垛线。