gpt4 book ai didi

javascript - 如何在 chart.js 中为条形图绘制基线

转载 作者:行者123 更新时间:2023-11-30 08:28:38 25 4
gpt4 key购买 nike

我有这样的条形图

enter image description here

我需要画水平虚线如下所示

enter image description here

我正在使用图表 js 来创建此图表。请帮我画出这条基线。

var ctx = document.getElementById("baseLinebar");

var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["25", "60", "15", "30"],
datasets: [{
data: [25, 60, 15, 30],
backgroundColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)'
]
}]
},
options: {
scales: {
xAxes: [{
gridLines: {
display:false
},
barThickness:40
}],
yAxes: [{
gridLines: {
display:false
}
}]

}
}
});

最佳答案

这里我们使用了 horizo​​nalLinePlugin 并将其注册到 Chart pluginService。您可以使用 horizo​​ntalLine 作为 configoption 的属性。使用这个 fiddle

JS

var config = {
type: 'bar',
data: {
labels: ["25", "60", "15", "30"],
datasets: [{
data: [25, 60, 15, 30],
backgroundColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)'
]
}]
},
options: {
scales: {
xAxes: [{
gridLines: {
display: true
},
barThickness: 40,
stacked: true

}],
yAxes: [{
gridLines: {
display: true
},
stacked: true

}]

},
horizontalLine: [{
y: 50,
style: "rgba(255, 0, 0, .4)",
text: "max"
}, {
y: 15,
text: "min"
}]
}
};

;
var ctx = document.getElementById("canvas");

var horizonalLinePlugin = {
afterDraw: function (chartInstance) {
var yScale = chartInstance.scales["y-axis-0"];
var canvas = chartInstance.chart;
var ctx = canvas.ctx;
var index;
var line;
var style;

if (chartInstance.options.horizontalLine) {
for (index = 0; index < chartInstance.options.horizontalLine.length; index++) {
line = chartInstance.options.horizontalLine[index];

if (!line.style) {
style = "rgba(169,169,169, .6)";
} else {
style = line.style;
}

if (line.y) {
yValue = yScale.getPixelForValue(line.y);
} else {
yValue = 0;
}

ctx.lineWidth = 3;

if (yValue) {
ctx.beginPath();
ctx.moveTo(0, yValue);
ctx.lineTo(canvas.width, yValue);
ctx.strokeStyle = style;
ctx.stroke();
}

if (line.text) {
ctx.fillStyle = style;
ctx.fillText(line.text, 0, yValue + ctx.lineWidth);
}
}
return;
};
}
};
Chart.pluginService.register(horizonalLinePlugin);

var myChart = new Chart(ctx, config);

关于javascript - 如何在 chart.js 中为条形图绘制基线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41221339/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com