问题描述
如何在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中找到了答案(),但它使用的是旧版本的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);
}
}
});
}
}
这篇关于如何在ChartJs中显示数据值或索引标签(最新版本)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!