简体   繁体   中英

How to align Chart.JS line chart labels to the center

I'm using Chart.JS 1.0.2 to create a line chart: 我现在得到的图表

What I'm trying to do is move the labels that are on the bottom of the chart the center of each rectangle (instead of being aligned with the vertical grid lines):

我想要达到的目的

There is no documentation about this on chartjs.org but I believe that with a smart trick this problem can be easily solved. Any ideas on how this can be accomplished?

offsetGridLines (boolean) If true, labels are shifted to be between grid lines.

type: 'line',
data: data,
options: {
    ...
    scales: {
        xAxes: [{
            gridLines: {
                offsetGridLines: true
            }
        ]}
    }
}

Test this:

labelOffset:-5 //adjust number

In ChartJS Documentation , under "Grid line Configuration" there is the drawOnChartArea option:

Name: drawOnChartArea
Type: boolean
Description: If true, draw lines on the chart area inside the axis lines. This is useful when there are multiple axes and you need to control which grid lines are drawn

{
    type: 'line',
    data: data,
    options: {
        ...
        scales: {
            xAxes: [{
                gridLines: {
                    drawOnChartArea: true
                }
            ]}
        }
    }
}

A little late, but hopefully helps someone.

My issue was trying to force a chart with type: 'bubble' and an x axis with type: 'linear' to place the labels in the center of the grid lines. The "centering the label" functionality comes standard for an axis with type: 'category' , like on bar charts. You can get linear point placement with category style labels by having two xAxes defined and not displaying the linear one.

In this example, points are plotted across a full 365 days, with x axis ticks for each quarter and the quarter label centered within its section of the plot.

data: {
    xLabels: ['Q1', 'Q2', 'Q3', 'Q4'],
    ...
}, 
options: {
    scales: {
        xAxes: [
            {
                id: 'xAxis1',
                type: 'linear',
                display: false,
                ticks: {
                    min: 0,
                    max: 365,
                    stepSize: 365 / 4
                }
            },
            {
                id: 'xAxis2',
                type: 'category',
                gridLines: {
                    offsetGridLines: true
                },
                scaleLabel: {
                    display: true,
                    labelString: 'Day of Year'
                }
            }
        ],
        ...
    }
}

I've used this for chart.js 2.x.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM