angular - Angular Chartjs 重叠条形图与 Chartjs 版本 2.7
问题描述
我正在尝试编写一个角度页面,该页面将显示带有 chartjs 2.7 版的重叠条形图。我正在关注此网址上的代码
https://jsfiddle.net/17hvoa9t/11/
我发现它适用于chartjs ver 2.5,但我需要它才能与Chartjs 2.7一起使用
当我使用 chartjs 2.7 时,只有 1 个条形集重叠,而其他两个没有重叠。我一直在阅读有关 barPercentage 和 categoryPercentage 的charts.org,但尝试为这两个数据集设置它们,但它仍然不起作用。
这是渲染的页面
到目前为止,这是我的代码
ngOnInit() {
var data = {
labels: ["x1", "x2", "x3"],
datasets: [{
label: "First",
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderWidth: 1,
data: [10, 20, 30],
xAxisID: "bar-x-axis1",
}, {
label: "Second",
backgroundColor: 'rgba(255, 206, 86, 0.2)',
borderWidth: 1,
data: [5, 30, 35],
xAxisID: "bar-x-axis2",
}]
};
var options = {
scales: {
xAxes: [{
stacked: true,
id: "bar-x-axis1",
barThickness: 30,
type: 'category',
categoryPercentage: 0.8,
barPercentage: 0.9,
gridLines: {
offsetGridLines: true
}
}, {
display: false,
stacked: true,
id: "bar-x-axis2",
barThickness: 70,
// these are needed because the bar controller defaults set only the first x axis properties
type: 'category',
categoryPercentage: 0.8,
barPercentage: 0.9,
gridLines: {
offsetGridLines: true
}
}],
yAxes: [{
stacked: false,
ticks: {
beginAtZero: true
},
}, {
type: 'category',
categoryPercentage: 0.8,
barPercentage: 0.9,
gridLines: {
offsetGridLines: true
}
}
]
}
};
var ctx = document.getElementById("myChart").getContext("2d");
var myBarChart = new Chart(ctx, {
type: 'bar',
data: data,
options: options
});
}
}
HTML
<canvas id="myChart" width="500" height="300"></canvas>
解决方案
您的第二个 x 轴需要offset
设置为true
:
{
display: false,
stacked: true,
id: "bar-x-axis2",
barThickness: 70,
// these are needed because the bar controller defaults set only the first x axis properties
type: 'category',
offset: true, // <-- This property needs added
categoryPercentage: 0.8,
barPercentage: 0.9,
gridLines: {
offsetGridLines: true
}
}
chart.js笛卡尔坐标轴文档声明这默认为true
,但这显然仅适用于第一个轴。
如果为 true,则会在两条边上添加额外的空间,并缩放轴以适合图表区域。默认情况下,此设置
true
用于条形图中的类别比例。
推荐阅读
- python - 如何在 sklearn.DictionaryLearning 中使 V 变得稀疏?
- google-apps-script - 不相交范围的 Google 脚本保护问题
- sql - 单行子查询返回多于一行 - 当查询应返回 1 行时
- python - 如何解决python中属性错误的问题?
- bash - BASH - 检查文件是否存在,如果存在,将文件名附加到 .txt
- django - HTML表单数据未保存在数据库中 - django
- firebase - 有没有办法在层次结构的较低级别覆盖 Firebase 规则?
- xquery - 为什么我不能欺骗我的 IP 地址并欺骗 Marklogic 函数 'xdmp:get-request-client-address' 以为我在世界其他地方?
- javascript - 使用剪贴板 javascript API 复制 HTML 文本
- html - CSS 悬停未按预期工作。为什么?