Chart.js 2.9.4双Y轴折线图:如何仅隐藏右侧Y轴对应图例
解决Chart.js 2.9.4双Y轴图例重复问题
针对双Y轴导致图例重复的问题,有两种直接可行的解决方式:
方式一:单独隐藏右侧Y轴数据集的图例
在每个对应右侧Y轴(yAxisID: 'B')的数据集配置中,添加legend: { display: false },让该数据集不生成图例项。
修改后的数据集代码片段:
{ yAxisID: 'B', label: [{% for key2, val in value.items %}{% if forloop.first %}'{{ key }}',{% endif %}{% endfor %}], backgroundColor: fixedColors({{ forloop.counter0 }}), borderColor: fixedColors({{ forloop.counter0 }}), borderWidth: 3.5, data: [{% for key2, val in value.items %}'{{ val }}',{% endfor %}], fill: false, lineTension: 0, tension: 0.0, legend: { display: false } // 新增该行,隐藏当前数据集的图例 },
方式二:通过图例过滤器批量控制
在图表的options中配置legend.filter函数,只保留对应左侧Y轴(yAxisID: 'A')的图例项。这种方式无需逐个修改数据集,适合批量处理场景。
修改后的options配置片段:
options: { responsive: true, title: { display: true, text: 'Estimated Marginal Means of {{ dep_var }}' }, // 新增图例过滤规则 legend: { filter: function(item, chart) { // 仅保留左侧Y轴数据集对应的图例 return chart.data.datasets[item.datasetIndex].yAxisID === 'A'; } }, tooltips: { mode: 'index', intersect: false, }, hover: { mode: 'nearest', intersect: true }, scales: { // 原坐标轴配置保持不变 x: { display: true, scaleLabel: { display: true, labelString: '{{ ind2 }}' } }, yAxes: [{ id: 'A', position: 'left', display: true, scaleLabel: { display: true, labelString: 'Estimated Marginal Means' } }, { id: 'B', position: 'right', display: true, scaleLabel: { display: false, labelString: 'Estimated Marginal Means' } }] } }
两种方式任选其一即可:方式一适合对单个数据集做精准控制,方式二更高效,适合数据集数量较多的场景。
内容的提问来源于stack exchange,提问作者user3288051
相关产品推荐
相关产品推荐

