Chart.js气泡图:实现数据标签在点下、数值在点上的布局
实现Chart.js气泡图的双标签位置自定义
当然可以分别设置标签和数值的位置,不用把它们合并成一个字符串!下面给你两种可行的方案,按需选择:
方案一:使用chartjs-plugin-datalabels插件(推荐)
这个插件专门用来自定义数据标签,支持为每个数据点添加多个独立配置的标签,非常灵活。
步骤1:引入插件
如果用npm安装:
npm install chartjs-plugin-datalabels
或者直接通过CDN引入:
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.2.0/dist/chartjs-plugin-datalabels.min.js"></script>
步骤2:配置双标签
在图表的配置中,通过plugins.datalabels.labels定义两个标签:一个显示数值在气泡上方,一个显示数据集标签在气泡下方:
const bubbleChart = new Chart(document.getElementById('myBubbleChart'), { type: 'bubble', data: { datasets: [ { label: '用户活跃度', data: [{ x: 15, y: 25, r: 10, value: 89 }, { x: 30, y: 40, r: 12, value: 76 }], backgroundColor: 'rgba(54, 162, 235, 0.6)' }, { label: '用户留存率', data: [{ x: 20, y: 30, r: 8, value: 65 }, { x: 35, y: 45, r: 9, value: 72 }], backgroundColor: 'rgba(255, 99, 132, 0.6)' } ] }, plugins: [ChartDataLabels], options: { plugins: { datalabels: { labels: { // 数值标签:放在气泡上方 value: { formatter: (dataPoint) => dataPoint.value, // 取数据中的value字段 anchor: 'bottom', // 锚点在气泡底部,文本自然在上方 align: 'center', offset: 8, // 与气泡的距离 color: '#2c3e50', font: { size: 12, weight: 'bold' } }, // 数据集标签:放在气泡下方 datasetLabel: { formatter: (_, context) => context.dataset.label, // 取数据集的label anchor: 'top', // 锚点在气泡顶部,文本自然在下方 align: 'center', offset: 8, color: '#7f8c8d', font: { size: 10 } } } } } } });
方案二:自定义绘制(无需额外插件)
如果不想引入第三方插件,可以利用Chart.js的自定义插件钩子,手动在画布上绘制文本:
const bubbleChart = new Chart(document.getElementById('myBubbleChart'), { type: 'bubble', data: { datasets: [ { label: '用户活跃度', data: [{ x: 15, y: 25, r: 10, value: 89 }, { x: 30, y: 40, r: 12, value: 76 }], backgroundColor: 'rgba(54, 162, 235, 0.6)' } ] }, options: { plugins: { // 自定义插件 customLabels: { afterDraw: (chart) => { const ctx = chart.ctx; // 遍历每个数据集和数据点 chart.data.datasets.forEach((dataset, datasetIdx) => { const meta = chart.getDatasetMeta(datasetIdx); meta.data.forEach((datapoint, idx) => { const { x, y } = datapoint.tooltipPosition(); const bubbleRadius = datapoint.r; const value = dataset.data[idx].value; const label = dataset.label; // 绘制数值(气泡上方) ctx.save(); ctx.textAlign = 'center'; ctx.fillStyle = '#2c3e50'; ctx.font = 'bold 12px Arial'; ctx.fillText(value, x, y - bubbleRadius - 5); // 向上偏移半径+5像素 // 绘制标签(气泡下方) ctx.fillStyle = '#7f8c8d'; ctx.font = '10px Arial'; ctx.fillText(label, x, y + bubbleRadius + 5); // 向下偏移半径+5像素 ctx.restore(); }); }); } } } } });
两种方案都能完美实现你要的效果:数值在气泡上方,数据集标签在气泡下方,完全不需要合并文本。如果需要调整对齐方式或者样式,直接修改对应的配置(比如align、font、offset等参数)就可以了。
内容的提问来源于stack exchange,提问作者Josh Gomes
相关产品推荐
相关产品推荐

