是否可以为不同的数据集设置不同的条形宽度?我在一个堆栈中有几个数据集,在其自己的堆栈中有另一个数据集。单个数据集应该比其他堆栈窄
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
});
最佳答案
这实际上可以在 Chart.js 中完成,但解决方案有点“hackish”。其要点是,您可以创建第二个 x 轴比例并将 barThickness
属性设置为小于其他轴的值。然后将数据集分配给此访问权限,最后将比例显示设置为 false。
您最终会在 1 个轴上得到一些数据集,在不同的隐藏轴上得到另一个数据集。其他一切仍然有效(没有像您在问题中提到的那样的破坏性效果)。
以下是您的选择。
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'
添加到要绑定(bind)到新轴的数据集。
这是一个codepen example展示了这一切。
您甚至可以通过更改周围的比例来对水平条形图执行此操作。看这个codepen example显示这个。
关于javascript - Chart.js 条形图中的多个条形宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42683812/