Chart.js如何移除柱状图标题下方的多余标签
Chart.js柱状图标题下方多余标签移除方案
问题场景
使用Chart.js开发婚姻状态统计柱状图时,标题下方出现非预期多余标签,需要移除。
原有实现代码
//MARITAL STATUS var marital_status=obj.marital_status; var ctx2 = document.getElementById('marital_status_chart').getContext('2d'); var myChart2 = new Chart(ctx2, { type: 'bar', data: { labels: ["Single","Married", "Widowed","Separated","Others"], datasets: [{ data: [marital_status.Single, marital_status.Married, marital_status.Widowed,marital_status.Separated,marital_status.Others], borderWidth: 1, backgroundColor: my_backgroundColors, hoverBackgroundColor: my_hoverBackgroundColor, hoverBorderColor: my_hoverBorderColor, }] }, plugins: [ChartDataLabels], options: { plugins: { datalabels: { color: 'black' }, title: { display: true, text: 'Marital Status' } } } });
实际运行效果

问题原因
标题下方的多余元素是Chart.js默认开启的图例(legend)组件,当前图表仅包含单个数据集,无需图例展示,默认渲染规则下就会出现这个冗余元素。
修复方案
在配置项的options.plugins节点下新增legend配置,将display设为false关闭默认图例渲染即可。修改后的options配置片段如下:
options: { plugins: { // 关闭默认图例,移除冗余标签 legend: { display: false }, datalabels: { color: 'black' }, title: { display: true, text: 'Marital Status' } } }
替换原有配置后重新渲染图表,多余标签即可消失。
内容的提问来源于stack exchange,提问作者beginner
相关产品推荐
相关产品推荐

