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

Chart.js 如何配置X轴刻度标签显示在图表顶部

解决方案

要实现X轴刻度标签显示在顶部,只需要在图表配置的options字段中新增scales配置项,指定X轴的position属性为top即可。

修改后的完整JS代码如下:

const ctx = document.getElementById('weather_chart');
const myChart = new Chart(ctx, {
    data: {
        datasets: [{
            type: 'bar',
            label: 'rainfall probability',
            data: [10, 20, 30, 40],
        }, {
            type: 'line',
            label: 'temperature',
            data: [50, 50, 50, 50],
            borderColor: '#EB6E4B',
            backgroundColor: '#EB6E4B',
        }],
        labels: ['now', '9am', '10am', '11am', '12pm'],
    },
    options: {
        plugins: {
            legend: {
                display: false,
            },
        },
        // 新增轴配置
        scales: {
            x: {
                position: 'top',
                // 可选配置:调整刻度标签与轴线的间距
                ticks: {
                    padding: 8
                }
            }
        }
    }
});

如果需要进一步自定义X轴的轴线样式、刻度线样式,都可以在scales.x配置项中添加对应属性调整。

内容的提问来源于stack exchange,提问作者chunzhi23

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 02:45:09