当只有1个项目时,Chart.js条形图不居中

时间:2018-06-12 18:39:33

标签: javascript charts

当条形图中只有一个项目时,条形图不居中:

https://codepen.io/anon/pen/rKmrpX?editors=1010

HTML:

<canvas id="myChart" width="400" height="400"></canvas>

JS:

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        "labels": ["2018-06-01T04:00:00.000Z"],
        "datasets": [{
            "type": "bar",
            "label": "Earnings",
            "yAxisID": "left-y-axis",
            "borderColor": "rgba(107, 165, 57, 1)",
            "backgroundColor": "rgba(107, 165, 57, 0.4)",
            "data": [25.77]
        }, {
            "type": "line",
            "label": "Pageviews",
            "yAxisID": "right-y-axis",
            "backgroundColor": "rgba(70, 152, 203, 0.4)",
            "borderColor": "rgba(70, 152, 203, 1)",
            "pointBackgroundColor": "rgba(70, 152, 203, 1)",
            "pointRadius": 0,
            "data": [3426]
        }]
    },
    options: {
        "scales": {
            "xAxes": [{
                "maxBarThickness": 100,
                "type": "time",
                "offset": true,
                "time": {
                    "unit": "day",
                    "tooltipFormat": "MMM-D",
                    "displayFormats": {
                        "day": "MMM-D",
                        "month": "MMM"
                    }
                },
                "ticks": {
                    "maxRotation": 0,
                    "maxTicksLimit": 7,
                    "autoSkip": true
                },
                "gridLines": {
                    "display": false,
                    "offsetGridLines": true
                }
            }],
            "yAxes": [{
                "id": "left-y-axis",
                "type": "linear",
                "position": "left",
                "ticks": {
                    "beginAtZero": true
                },
                "scaleLabel": {
                    "display": true,
                    "labelString": "Earnings"
                }
            }, {
                "id": "right-y-axis",
                "type": "linear",
                "position": "right",
                "ticks": {
                    "beginAtZero": true
                },
                "gridLines": false,
                "scaleLabel": {
                    "display": true,
                    "labelString": "Pageviews"
                }
            }]
        },
        "tooltips": {
            "callbacks": {}
        }
    }
});

有解决方法吗?也许我错过了一个应该传递的选项?

在这里使用最新版本的Chart.js(2.7.2)。

1 个答案:

答案 0 :(得分:0)

删除大多数xAxes配置接缝以提供您正在寻找的结果

https://codepen.io/tryggvigy/pen/rKmQpX?editors=1010

    "scales": {
        "xAxes": [{
            "maxBarThickness": 100,
        }],