如何在 ChartJs 中显示数据值或索引标签(最新版本)
如何在 ChartJs(最新版本)中显示数据值或索引标签,如下图所示:
How to show data values or index labels in ChartJs (Latest Version) as in the below image:
我正在使用 ChartJs 在我的 React 项目中显示图表.一切正常,除了这个.
I am using the ChartJs to display charts in my React Project. Everything is working fine, except this.
我在 stackoverflow (https://stackoverflow.com/a/31632707) 中找到了答案,但它使用的是旧的chartjs 的版本,并且不适用于我正在使用的版本.
I found an answer in stackoverflow (https://stackoverflow.com/a/31632707), But it uses an old version of chartjs and is not working on the one which I am using.
我的 ChartJs 代码:
var ctx = document.getElementById("myChart");
var BarChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Jan","Feb","March"],
datasets: [{
label: "Chart Data",
data: [10,20,15],
backgroundColor: "red",
borderColor: "green",
borderWidth: 1
}]
},
options: {
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}],
xAxes: [{
ticks: {
maxRotation: 180
}
}]
}
}
});
我尝试使用函数添加它:ctx.fillText(bar.value, bar.x, bar.y - 5);
,但是它显示的.fillText不是函数
I tried adding it using the function: ctx.fillText(bar.value, bar.x, bar.y - 5);
, But its showing .fillText is not a function
推荐答案
终于搞定了.
在 onComplete() 函数中使用了以下代码:
Used the following code in the onComplete() function:
animation: {
onComplete: function () {
var ctx = this.chart.ctx;
ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontFamily, 'normal', Chart.defaults.global.defaultFontFamily);
ctx.fillStyle = "black";
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
this.data.datasets.forEach(function (dataset)
{
for (var i = 0; i < dataset.data.length; i++) {
for(var key in dataset._meta)
{
var model = dataset._meta[key].data[i]._model;
ctx.fillText(dataset.data[i], model.x, model.y - 5);
}
}
});
}
}
相关文章