2017-03-08 152 views
0

是否可以針對不同的數據集具有不同的條寬?我在一個堆棧中有幾個數據集,另一個數據集在它自己的堆棧中。單個數據集應該比其他堆棧更窄Chart.js條形圖中的多個條寬度

Example。這裏我複製了左邊的堆棧,導致它是正確堆棧寬度的兩倍。這打破了一定的影響,其中包括非零邊界

var data = { 
    labels: ["1", "2", "3", "4", "5"], 
    datasets: [ 
    { 
     label: "d1", 
     backgroundColor: "rgba(182,127,0,1)", 
     borderColor: "rgba(117,61,41,1)", 
     borderWidth: 1, 
     data: [42, 78, 64, 90, 97], 
     stack: "s1" 
    }, 
    { 
     label: "d2", 
     backgroundColor: "rgba(71,161,65,1)", 
     borderColor: "rgba(36,93,56,1)", 
     borderWidth: 1, 
     data: [27, 63, 46, 64, 43], 
     stack: "s1" 
    }, 
    { 
     label: "d3", 
     backgroundColor: "rgba(255,141,106,1)", 
     borderColor: "rgba(99,60,32,1)", 
     borderWidth: 1, 
     data: [18, 50, 23, 83, 35], 
     stack: "s1" 
    }, 
    { 
     label: "d1", 
     backgroundColor: "rgba(182,127,0,1)", 
     borderColor: "rgba(117,61,41,1)", 
     borderWidth: 1, 
     data: [42, 78, 64, 90, 97], 
     stack: "s1b" 
    }, 
    { 
     label: "d2", 
     backgroundColor: "rgba(71,161,65,1)", 
     borderColor: "rgba(36,93,56,1)", 
     borderWidth: 1, 
     data: [27, 63, 46, 64, 43], 
     stack: "s1b" 
    }, 
    { 
     label: "d3", 
     backgroundColor: "rgba(255,141,106,1)", 
     borderColor: "rgba(99,60,32,1)", 
     borderWidth: 1, 
     data: [18, 50, 23, 83, 35], 
     stack: "s1b" 
    }, 
    { 
     label: "d4", 
     backgroundColor: "rgba(160,160,160,1)", 
     borderColor: "rgba(60,60,60,1)", 
     borderWidth: 1, 
     data: [152, 141, 170, 194, 128], 
     stack: "s2", 
     barPercentage: 0.3 
    } 
    ] 
}; 
var options = { 
    scales: { 
    xAxes: [{ 
     categoryPercentage: 0.6, 
     barPercentage: 1 
    }] 
    }, 
    legend: { 
    display: false 
    } 
}; 

var barChart = new Chart($("#myChart"), { 
    type: 'bar', 
    data: data, 
    options: options 
}); 

回答

1

這實際上可以在chart.js中做,但解決方案有點「hackish」。其要點是您可以創建第二個x軸刻度並將barThickness屬性設置爲小於其他軸的值。然後,將您的數據集分配給此訪問權限,最後將比例顯示設置爲false。

您最終會得到一個軸上的一些數據集,而另一個數據集則隱藏在另一個不同的軸上。其他一切仍然有效(沒有像你在你的問題中提到的破壞效果)。

以下是您的選擇的樣子。

var options = { 
    scales: { 
    xAxes: [{ 
     categoryPercentage: 0.6, 
     barPercentage: 1, 
    }, { 
     id: 'x-axis-2', 
     type: 'category', 
     display: false, 
     categoryPercentage: 0.6, 
     barPercentage: 1, 
     barThickness: 20, 
     gridLines: { 
     offsetGridLines: true 
     } 
    }], 
    }, 
    legend: { 
    display: false 
    } 
}; 

你必須確保你添加xAxisID: 'x-axis-2'你要綁定到新中軸線爲準數據集。

這是一個codepen example演示所有這一切。

您甚至可以通過更改周圍的比例來爲水平條形圖執行此操作。看到這個codepen example顯示這一點。

+0

看起來很像我需要的東西,但它是否適用於水平條形圖?我嘗試切換你的例子,但第二軸不再顯示http://codepen.io/MalikDrako/pen/RpjLRd?editors=0010它也看起來像在某些地方交換軸,但不是別人 - 嘗試設置tye類型以y軸爲對數,但似乎將其設置爲垂直軸。 –

+0

是的,你可以看到我更新的答案中的例子 – jordanwillis