如何使用react-chartjs-2为Chart.js v3.3.0实现自定义图例
Chart.js v3.3.0自定义图例实现方案
功能支持说明
Chart.js v3.3.0版本完全支持自定义图例配置,你代码中注释的generateLabels就是官方提供的图例标签生成接口,除此之外如果需要完全自定义HTML结构的图例,还可以配合插件能力实现。
基础自定义图例示例(基于generateLabels)
修正你注释的generateLabels写法,返回符合规范的图例项配置即可自定义图例展示内容,示例代码如下:
plugins: { legend: { display: true, onClick: () => { console.log('do nothing'); }, position: 'bottom', labels: { usePointStyle: true, pointStyle: 'circle', generateLabels: (chart) => { const data = chart.data; if (data.labels.length && data.datasets.length) { const total = data.datasets[0].data.reduce((prev, curr) => prev + curr, 0); return data.labels.map((label, index) => { const dataset = data.datasets[0]; return { // 可自定义图例文本,支持拼接数值、百分比等内容 text: `${label}:${dataset.data[index]}(${Math.round(dataset.data[index]/total*100)}%)`, fillStyle: dataset.backgroundColor[index], strokeStyle: dataset.backgroundColor[index], pointStyle: 'circle', hidden: !chart.getDataVisibility(index), index: index } }) } return []; }, }, }, title: { text: 'Gender', display: true, }, }, type: 'doughnut', data: { labels: defaultColors, datasets: [ { label: 'label1', data: [1, 2], backgroundColor: getBackground, borderWidth: 0, }, ], }, width: 'auto', height: '100%',
完全自定义HTML图例示例
如果内置图例的样式无法满足需求,可以关闭默认图例,通过自定义插件生成完全自主控制的DOM结构:
// 页面提前准备图例容器 <div id="custom-legend"></div> plugins: { legend: { // 关闭默认图例 display: false }, // 注册自定义图例插件 customLegend: { id: 'customLegend', afterUpdate: (chart) => { const legendEl = document.getElementById('custom-legend'); if (!legendEl) return; let legendHtml = '<div style="display: flex; gap: 20px; justify-content: center; margin-top: 12px;">'; const total = chart.data.datasets[0].data.reduce((prev, curr) => prev + curr, 0); chart.data.labels.forEach((label, index) => { const dataset = chart.data.datasets[0]; const color = dataset.backgroundColor[index]; const value = dataset.data[index]; legendHtml += ` <div style="display: flex; align-items: center;"> <span style="width: 10px; height: 10px; border-radius: 50%; background: ${color}; margin-right: 6px;"></span> <span>${label}:${value}(${Math.round(value/total*100)}%)</span> </div> ` }) legendHtml += '</div>'; legendEl.innerHTML = legendHtml; } } }
内容的提问来源于stack exchange,提问作者Khanh Nguyen
相关产品推荐
相关产品推荐

