【发布时间】:2022-10-14 19:45:56
【问题描述】:
帮我找出我的错误。
我使用chart.js 2.7.0。我有一个条形图,想添加两条线。其中一个应该是直的 通过所有图表。我尝试了两种方法,但对我没有帮助。
在第一种方式中,我添加到数据集价值观:
export const chartConfiguration = () => ({
type: 'bar',
data: {
labels: null,
datasets: [
{
label: 'Hourly',
fill: false,
data: [0.3494, 0.3361, 0.325, 0.3224],
borderColor: '#ff0000',
pointBackgroundColor: '#ff0000',
type: 'line',
},
{
label: 'Average',
fill: false,
data: Array(4).fill(1),
borderColor: '#d67735',
pointBackgroundColor: '#d67735',
type: 'line',
pointRadius: 0,
pointHitRadius: 0,
lineTension: 0,
beginAtZero: true
}]
},
options: {
title: {
display: true,
position: 'top',
fontColor: '#3f7ba2',
fontStyle: 550,
fontSize: 15
},
legend: {display: false},
scales: {
xAxes: [{
stacked: true,
ticks: {
stepSize: 1,
min: 0,
autoSkip: false,
fontColor: '#3f7ba2',
fontStyle: 550,
fontSize: 11,
padding: 5
},
gridLines: {
color: '#dedfe7'
}
}],
yAxes: [{
stacked: true,
ticks: {
min: 0,
fontColor: '#62aae8',
padding: 5
},
gridLines: {
color: '#dedfe7',
tickMarkLength: 15
}
}],
},
annotation: {
events: ['mouseenter', 'mouseleave'],
annotations: []
},});
我以为这行得通,但我错了。问题是标签为“Hourly”的第一行的值 = 0.3494,而标签为“Average”的第二行的值 = 1。 Chart.js 绘制第二行不是按值 1,而是按值 0.3494 + 1 = 1.3494 绘制。我试图找到像 beginFromZero 这样的任何选项,但这里不存在 这是屏幕截图:
- 我尝试了第二种方法:我添加了一个插件,但它根本不起作用,我不知道为什么:
export const chartConfiguration = () => ({
type: 'bar',
data: {
labels: null,
datasets: [{
label: ' ',
data: [1.9 , 2.0, 1.7, 1.8],
borderColor: '#b1c8de',
backgroundColor: '#b1c8de',
pointBackgroundColor: '#b1c8de',
tension: 0,
fill: false,
offsetGridLines: true
}]
},
options: {
title: {
display: true,
position: 'top',
text: currentFullDate,
fontColor: '#3f7ba2',
fontStyle: 550,
fontSize: 15
},
legend: {display: false},
scales: {
xAxes: [{
stacked: true,
ticks: {
stepSize: 1,
min: 0,
autoSkip: false,
fontColor: '#3f7ba2',
fontStyle: 550,
fontSize: 11,
padding: 5
},
gridLines: {
color: '#dedfe7'
}
}],
yAxes: [{
stacked: true,
ticks: {
min: 0,
fontColor: '#62aae8',
padding: 5
},
gridLines: {
color: '#dedfe7',
tickMarkLength: 15
}
}],
},
config : {
plugins: {
afterDatasetsDraw: function(chart) {
let lineAt = 1;
const ctxPlugin = chart.chart.ctx;
const xAxe = this._chart.scales[chart.config.options.scales.xAxes[0].id];
const yAxe = this._chart.scales[chart.config.options.scales.yAxes[0].id];
if (yAxe.min !== 0) {
return;
}
ctxPlugin.strokeStyle = '#d67735';
ctxPlugin.beginPath();
lineAt = (lineAt - yAxe.min) * (100 / yAxe.max);
lineAt = (100 - lineAt) / 100 * (yAxe.height) + yAxe.top;
ctxPlugin.moveTo(xAxe.left, lineAt);
ctxPlugin.lineTo(xAxe.right, lineAt);
ctxPlugin.stroke();
}
} }
});
【问题讨论】:
-
仅当您堆叠数据集时才会发生这种情况,因此请分享您的所有配置
-
@LeeLenalee,谢谢你的提示。我添加了所有配置。
标签: javascript charts chart.js line chart.js2