如何增大Chart.js图表图例的标签字体大小?
Chart.js 增大图例标签字号实现方法
问题描述
需要增大Chart.js绘制的折线图中,顶部Label 1/Label 2/Label 3对应的图例文字字号,效果参考:
现有配置已完成坐标轴、标题的字号设置,未找到图例字号的配置入口。
实现方法
图例的样式配置归属于options.plugins.legend节点,和已配置的title插件平级,只需在该节点下指定labels.font.size参数即可自定义图例标签字号,字号数值可根据实际需求调整。
核心修改片段
在现有代码的plugins对象中,和title配置平级添加如下图例配置即可:
plugins: { title: { display: true, }, // 新增图例配置 legend: { labels: { font: { size: 24 // 此处设置需要的图例字号,示例值24和现有y轴刻度字号一致 } } } }
完整可用配置
var data = { labels: x_axis_labels, datasets: [ { label: 'Label 1', data: data_1, borderColor: 'rgb(46,138,207)', backgroundColor: 'rgb(46,138,207)', yAxisID: 'y', }, { label: 'Label 2', data: data_2, borderColor: 'rgb(214,224,52)', backgroundColor: 'rgb(214,224,52)', yAxisID: 'y1', }, { data: data_3, label:'Label 3', borderColor: 'rgb(244,67,54)', backgroundColor: 'rgb(244,67,54)', yAxisID: 'y1', pointStyle:'dash', borderDash: [20, 30], pointBackgroundColor: "transparent", }, ] }; const config = { type: 'line', data: data, options: { responsive: true, interaction: { mode: 'index', intersect: false, }, stacked: false, plugins: { title: { display: true, }, // 新增图例字号配置 legend: { labels: { font: { size: 24 } } } }, scales: { x:{ title:{ display: true, text: 'X axis name', font: {size:30}, }, ticks: { font: { size: 20, } } }, y: { title:{ display: true, text: 'First y axis name', font: {size:30} }, type: 'linear', display: true, position: 'left', ticks: { font: { size: 24, } } }, y1: { title:{ display: true, text: 'Second Y axis name', font: {size:30} }, type: 'linear', display: true, position: 'right', ticks:{ font:{ size:24, } }, grid: { drawOnChartArea: false, }, }, }, }, };
补充:如果需要调整图例字体的其他属性,比如字重、字体族,直接在
font对象下添加weight、family等参数即可,配置逻辑和坐标轴字体完全一致。
内容的提问来源于stack exchange,提问作者Spartan 117
相关产品推荐
相关产品推荐

