Show data values in Chart.js bars (version 3)(在 Chart.js 条形图中显示数据值(版本 3))
问题描述
关于这个主题有很多答案(在 chart.js 中的条形顶部显示值),但这都是关于版本 2.x
There is a thread with many answers on this topic (Show values on top of bars in chart.js), but it's all about version 2.x
getDatasetMeta() 已被弃用:https://www.chartjs.org/docs/3.0.2/getting-started/v3-migration.html
数据标签"插件尚未移植到 3.x:https://github.com/chartjs/chartjs-plugin-datalabels
The "datalabels" plugin has not been ported to 3.x: https://github.com/chartjs/chartjs-plugin-datalabels
您找到任何可行的解决方案了吗?数据值如何显示在垂直条形图顶部(或水平条形图旁边)?
Have you found any working solutions? How can data values be displayed on top of vertical barcharts (or next to horizontal barcharts)?
推荐答案
您可以使用数据标签插件的测试版.
You can use the beta of the datalabels plugin.
文档:https://v2_0_0-rc_1--chartjs-plugin-datalabels.netlify.app/
脚本标签:<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.0.0-rc/dist/chartjs-plugin-datalabels.min.js"></script>
安装命令:npm i chartjs-plugin-datalabels@next
活生生的例子:
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.3.0/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.0.0-rc"></script>
<canvas id="myChart" width="850" height="520"></canvas>
<script>
var ctx = document.getElementById('myChart');
Chart.register(ChartDataLabels); // first way of registering the plugin, registers them for all your charts
var myChart = new Chart(ctx, {
type: 'bar',
plugins: [ChartDataLabels], // second way of registering plugin, register plugin for only this chart
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
data: [12, 19, 3, 5, 2, 3],
label: 'Advisor Closed MTD',
backgroundColor: 'rgb(192,111,94)',
barThickness: 25,
datalabels: {
color: '#FFCE56'
}
}],
},
options: {
responsive: false,
plugins: {
datalabels: {
anchor: 'end', // remove this line to get label in middle of the bar
align: 'end',
formatter: (val) => (`${val}%`),
labels: {
value: {
color: 'blue'
}
}
}
}
}
});
</script>
这篇关于在 Chart.js 条形图中显示数据值(版本 3)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Chart.js 条形图中显示数据值(版本 3)
基础教程推荐
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
