我已经使用 LwC 和 ChartJS v2.8.0 版本在 salesforce 中构建了简单的条形图,所以现在我尝试使用 chartjs-plugin-datalabels v1.0.0 插件在每个条形上显示数据值。我已经在代码中加载了这个插件,并按照插件文档中的指定注册了该插件,但数据值没有显示在每个栏上。
有人能指出我在这里缺少什么吗?这会有帮助的。
这是 LwC 代码:
import { LightningElement,api, wire, track } from 'lwc';
import chartjs from '@salesforce/resourceUrl/chartjs_v280';
import ChartDataLabels from '@salesforce/resourceUrl/ChartjsPluginDataLabels';
import { loadScript } from 'lightning/platformResourceLoader';
export default class ChartDemocmp extends LightningElement {
//chart;
isChartJsInitialized;
chartConfiguration;
renderedCallback() {
Promise.all([
loadScript(this, chartjs),
loadScript(this, ChartDataLabels)
])
.then(()=>{
console.log('Loaded');
//this.isChartJsInitialized = true;
if(this.chart){
this.chart.destroy();//destory the chart once data is updated to show the new chart
}
const ctx = this.template.querySelector("canvas.barChart").getContext('2d');
//Chart.register(ChartDataLabels);
//chartjs.plugins.register(ChartDataLabels);
Chart.plugins.register(ChartDataLabels);
this.chart = new Chart(ctx,{
type: 'bar',
data: {
labels: ["data1","data2","data3","data4","data5","data6","data7"],
datasets: [
{
label: 'dataset',
barPercentage: 0.5,
barThickness: 6,
maxBarThickness: 8,
minBarLength: 2,
backgroundColor: "blue",
data: [65, 59, 80, 81, 56, 55, 40],
},
],
},
// plugins: [ChartDataLabels],
options: {
resposive:true,
plugins: {
datalabels: {
color: "black",
labels: {
title: {
font: {
weight: "bold"
}
}
}
}
}
}
});
})
.catch(error => {
console.log('error chart--> '+JSON.stringify(error));
});
}
}
这是 salesforce 中条形图的屏幕截图,其中每个条形上均未显示值:
我认为问题在于缺少 Y 比例定义,默认值为
ticks.beginAtZero: false
。默认情况下,该插件计算标签在整个条上的位置(基于数据值),而不是在可见条上。要强制插件使用可见栏,您应该使用 clamp: true
选项。
夹紧文档:https://chartjs-plugin-datalabels.netlify.app/guide/positioning.html#clamping
Chart.plugins.register(ChartDataLabels);
new Chart(
document.getElementById('myChart'),
{
type: 'bar',
data: {
labels: ["data1","data2","data3","data4","data5","data6","data7"],
datasets: [
{
label: 'dataset',
barPercentage: 0.5,
barThickness: 6,
maxBarThickness: 8,
minBarLength: 2,
backgroundColor: "blue",
data: [65, 59, 80, 81, 56, 55, 40],
},
]
},
options: {
resposive:true,
plugins: {
datalabels: {
clamp: true,
color: "black",
labels: {
title: {
font: {
weight: "bold"
}
}
}
}
}
}
});
.myChartDiv {
max-width: 600px;
max-height: 400px;
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/Chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chartjs-plugin-datalabels.min.js"></script>
<html>
<body>
<div class="myChartDiv">
<canvas id="myChart" width="600" height="400"/>
</div>
</body>
</html>
最后你能解决这个问题吗?我在完全相同的设置下遇到了同样的问题