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

如何使用Chart.js v3实现两个图表的侧边对齐?

解决Chart.js v3中两个柱状图侧边对齐的问题

要实现两个侧边排列的柱状图对齐(让柱子部分的起始位置一致),核心是让两个图表的**绘图区域(plot area)**保持相同的水平偏移,不受标签长度影响。以下是针对你的代码的修改方案:

步骤1:修正Chart.js v3的属性兼容

你的代码中使用了v1版本的fillColor、strokeColor等属性,在v3中需要替换为新的属性名:

  • fillColor → backgroundColor
  • strokeColor → borderColor
  • highlightFill → hoverBackgroundColor
  • highlightStroke → hoverBorderColor

步骤2:同步两个图表的布局偏移

在Chart.js v3中,可以通过获取第一个图表的x轴布局信息,手动设置第二个图表的左侧内边距,确保两者的绘图区域对齐。具体实现如下:

完整代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Aligned Charts</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.4.1/chart.js"></script>
    <style>
        #chart_a, #chart_b {
            width: 320px;
            height: 350px;
        }
        .label {
            text-align: center;
            width: 660px;
            font-size: 20px;
            font-weight: bold;
            margin: 20px;
        }
        .chart_container {
            float: left;
            margin-right: 10px;
        }
    </style>
</head>

<body>
    <div id="aligned">
        <div class="label">Aligned</div>
        <div class="chart_container">
            <canvas id="chart_a"></canvas>
        </div>
        <div class="chart_container">
            <canvas id="chart_b"></canvas>
        </div>
    </div>
    <script>
        // 初始化第一个图表(长标签)
        const longLabelsData = {
            labels: ["Dmitri.Ivanovich.Mendeleev", "Yuri.Alekseyevich.Gagarin", "Alexey.Arkhipovich.Leonov"],
            datasets: [{
                label: "My First dataset",
                backgroundColor: "rgba(220,220,220,0.5)",
                borderColor: "rgba(220,220,220,0.8)",
                hoverBackgroundColor: "rgba(220,220,220,0.75)",
                hoverBorderColor: "rgba(220,220,220,1)",
                data: [50, 88, 15]
            }]
        };

        const ctxB = document.getElementById("chart_b").getContext("2d");
        const myChart2 = new Chart(ctxB, {
            type: 'bar',
            data: longLabelsData,
            options: {
                animation: false,
                responsive: true,
                maintainAspectRatio: false
            }
        });

        // 初始化第二个图表(短标签),并同步布局
        const shortLabelsData = {
            labels: ["Iantojones", "Jackharkness", "Owenharper"],
            datasets: [{
                label: "My First dataset",
                backgroundColor: "rgba(220,220,220,0.5)",
                borderColor: "rgba(220,220,220,0.8)",
                hoverBackgroundColor: "rgba(220,220,220,0.75)",
                hoverBorderColor: "rgba(220,220,220,1)",
                data: [50, 88, 15]
            }]
        };

        const ctxA = document.getElementById("chart_a").getContext("2d");
        const myChart1 = new Chart(ctxA, {
            type: 'bar',
            data: shortLabelsData,
            options: {
                animation: false,
                responsive: true,
                maintainAspectRatio: false,
                layout: {
                    // 同步第一个图表的左侧内边距
                    padding: {
                        left: myChart2.scales.x.left
                    }
                }
            }
        });
    </script>
</body>
</html>

关键说明

  1. 获取布局信息:myChart2.scales.x.left表示第一个图表x轴的左侧偏移量(也就是标签占用的宽度),将这个值设置给第二个图表的layout.padding.left,就能让第二个图表的绘图区域和第一个对齐。
  2. 响应式配置:开启responsive: true和maintainAspectRatio: false,确保图表能正确应用自定义的内边距设置。
  3. 属性兼容:必须替换旧版本的样式属性,否则图表无法正常渲染。

如果需要支持窗口大小变化后的重新对齐,可以添加窗口 resize 事件监听,在事件中重新计算并设置内边距:

window.addEventListener('resize', () => {
    myChart1.options.layout.padding.left = myChart2.scales.x.left;
    myChart1.update();
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 12:47:11