You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Chart.js传入对象数组生成图表并解决自定义标签不生效问题

问题原因与解决方案

核心问题1:自定义标签不生效

你给dataset.data传入的是timers对象,Chart.js处理分类轴图表时,若传入对象作为数据会优先读取对象的键作为分类标签,直接覆盖data.labels中定义的内容。

核心问题2:x轴标签字号配置错误

你之前的字号配置写在了plugins.legend.labels下,该配置仅对图例生效,x轴标签的样式需要在options.scales.x下配置。

修改后完整代码

let timers = {neutral: 0, happy: 0, sad: 0, angry: 0, surprised: 0, disgust: 0};
// 按labels的顺序提取timers的数值,生成数组格式的数据源
const timerValues = [timers.neutral, timers.happy, timers.sad, timers.angry, timers.surprised, timers.disgust];
var detection = new Chart(c, {
    type: 'bar',
    data: {
        labels: ["Neutral", "Happy", "Sad", "Angry", "Surprised", "Disgust"],
        datasets: [{
            fill: false,
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)', // neutral
                'rgba(54, 162, 235, 0.2)', // happy
                'rgba(255, 206, 86, 0.2)', // sad
                'rgba(75, 192, 192, 0.2)', // angry
                'rgba(153, 102, 255, 0.2)', // surprised
                'rgba(255, 159, 64, 0.2)'   // disgust
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'                        
            ],
            borderWidth: 2,
            data: timerValues, // 替换为数组格式的数据源
        }]
    },
    options: {
        indexAxis: 'x',
        responsive: true,
        // 新增x轴配置
        scales: {
            x: {
                ticks: {
                    font: {
                        size: 50 // 此处设置x轴标签字号
                    }
                }
            }
        },
        plugins: {
            legend: {
                display: false,
                labels: {
                    font: {
                        size: 50
                    }
                }
            },
            title: {
                display: true,
                text: "Emotion timers"
            }
        }
    }
});

内容的提问来源于stack exchange,提问作者Νικόλαος Καλαμπόκας

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 18:45:00