2016-11-06 92 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條垛線。