首页 > 解决方案 > Chartjs:双x轴没有相同的网格线

问题描述

我将 Chart.js 版本 2.9.4 与 jQuery 版本 3.2.1 一起使用,并且我使用条形图类型。我想要实现的是在背景中显示一个数据栏(米色),在前景中显示两个数据栏(绿色和洋红色)。问题是,使用我的这个设置,它显示错误 - x 轴和网格线没有正确对齐(我只想显示一个,但为了调试,图片中显示了两个)。

链接到我的图表

我的数据和比例代码是:

var activityData = {
            datasets: [
                {
                    label: 'Monthly plan',
                    backgroundColor: '#a3b13a',
                    data: [14000, 12000, 14000, 15000, 15000, 16000, 12000, 10000, 15000, 16000, 17000, 20000],
                    xAxisID: 'x-axis-1',
                    barPercentage: 0.4
                }, {
                    label: 'Month sales',
                    backgroundColor: '#a51b4d',
                    data: [14200, 12800, 20100],
                    xAxisID: 'x-axis-1',
                    barPercentage: 0.4
                },{
                    label: 'Last year sales',
                    backgroundColor: '#f8f1e5',
                    data: [13250, 10965, 14520, 13789, 14085, 15796, 10367, 9513, 14302, 14985, 16997, 18622 ],
                    xAxisID: 'x-axis-2'
                }],
            labels: monthNames
        }

        var myScales = {
            xAxes: [{
                display: true,
                stacked: true,
                id: "x-axis-2",
                type: 'category',
                ticks: {
                    beginAtZero: true
                }
            }, {
                display: true,
                stacked: false,
                id: "x-axis-1",
                type: 'category',
                ticks: {
                    beginAtZero: true
                }
            }],
            yAxes: [{
                stacked: false,
                ticks: {
                    beginAtZero: true
                }
            }]
        }

如何解决这个问题以正确显示 - 背景中的一个栏和前景中的两个栏?

标签: javascriptchartschart.jsbar-chart

解决方案


我想通了,如果有人有同样的问题,我必须添加 offset: true。

    var myScales = {
        xAxes: [{
            display: true,
            stacked: true,
            id: "x-axis-2",
            type: 'category',
            offset: true,
            ticks: {
                beginAtZero: true
            }
        }, {
            display: false,
            stacked: false,
            id: "x-axis-1",
            type: 'category',
            offset: true,
            gridLines: {
                display:false
            },
            ticks: {
                beginAtZero: true
            }
        }],
        yAxes: [{
            stacked: false,
            ticks: {
                beginAtZero: true
            }
        }]
    }

推荐阅读