Chart.js:我如何更改任何尺寸的 x 轴刻度标签对齐方式?

Chart.js : How I change the x axes ticks labels alignment in any sizes?

如何在另一个 x 轴标签之间移动 x 轴上的标签。似乎没有任何效果,我在文档中找不到任何内容。有解决方法吗?我正在使用折线图时间序列。 https://www.chartjs.org/samples/latest/scales/time/financial.html

目前,我生成的代码如下图:

var cfg = {
            elements:{
                point: {
                    radius: 4
                }
            },
            data: {
                datasets: [
                    {
                        label: 'vsy',
                        backgroundColor: color(window.chartColors.red).alpha(0.5).rgbString(),
                        borderColor: window.chartColors.red,
                        data: firstData,
                        type: 'line',
                        pointRadius: 2,
                        fill: false,
                        lineTension: 0,
                        borderWidth: 2
                    },
                    {
                        label: 'de vsy',
                        backgroundColor: color(window.chartColors.blue).alpha(0.5).rgbString(),
                        borderColor: window.chartColors.blue,
                        data: dataMaker(15),
                        type: 'line',
                        pointRadius: 2,
                        fill: false,
                        lineTension: 0,
                        borderWidth: 2
                    }
                ],

            },
            options: {

                animation: {
                    duration: 0
                },
                scales: {
                    xAxes: [{
                        type: 'time',
                        distribution: 'series',
                        offset: true,

                        time: {
                            unit: 'month',
                            displayFormats: {                                
                                month: 'MMM'
                            }
                        },

                        ticks: {

                            autoSkip: true,
                            autoSkipPadding: 75,

                            sampleSize: 100
                        },

                    }],
                    yAxes: [{
                        gridLines: {
                            drawBorder: false
                        }

                    }]
                },
                tooltips: {
                    intersect: false,
                    mode: 'index',

                }
            }
        };

这是我现在拥有的:

我希望 x 轴上的标签位于中心而不是 y 轴网格线下方。

感谢 uminder,他的评论解决了问题,但现在我有一个位于同一网格上的冲突工具提示。当我悬停在 4 月线的第一个点时,它显示 3 月 30 日就在它的上方,反之亦然。

我通过将模式更改为 nearest 来修复它,但为什么它激活了另一个点?

您要找的选项是offsetGridLines

If true, grid lines will be shifted to be between labels.

xAxes: [{
  ... 
  gridLines: {
    offsetGridLines: true
  }

在大多数情况下,这会产生预期的结果。不幸的是,它不适用于 Chart.js issue #403. Thanks to Antti Hukkanen, there exists a workaround 中记录的时间轴。

请查看下面的可运行代码片段以了解其工作原理。

function generateData() {
  var unit = 'day';
  function randomNumber(min, max) {
    return Math.random() * (max - min) + min;
  }

  function randomPoint(date, lastClose) {
    var open = randomNumber(lastClose * 0.95, lastClose * 1.05).toFixed(2);
    var close = randomNumber(open * 0.95, open * 1.05).toFixed(2);
    return {
      t: date.valueOf(),
      y: close
    };
  }
    
  var date = moment().subtract(1, 'years');
  var now = moment();
  var data = [];
  for (; data.length < 600 && date.isBefore(now); date = date.clone().add(1, unit).startOf(unit)) {    
    data.push(randomPoint(date, data.length > 0 ? data[data.length - 1].y : 30));
  }
  return data;
}

var TimeCenterScale = Chart.scaleService.getScaleConstructor('time').extend({
  getPixelForTick: function(index) {
    var ticks = this.getTicks();
    if (index < 0 || index >= ticks.length) {
      return null;
    }
    // Get the pixel value for the current tick.
    var px = this.getPixelForOffset(ticks[index].value);

    // Get the next tick's pixel value.
    var nextPx = this.right;
    var nextTick = ticks[index + 1];
    if (nextTick) {
      nextPx = this.getPixelForOffset(nextTick.value);
    }

    // Align the labels in the middle of the current and next tick.
    return px + (nextPx - px) / 2;
  },
});
// Register the scale type
var defaults = Chart.scaleService.getScaleDefaults('time');
Chart.scaleService.registerScaleType('timecenter', TimeCenterScale, defaults);

var cfg = {
  data: {
    datasets: [{
      label: 'CHRT - Chart.js Corporation',
      backgroundColor: 'red',
      borderColor: 'red',
      data: generateData(),
      type: 'line',
      pointRadius: 0,
      fill: false,
      lineTension: 0,
      borderWidth: 2
    }]
  },
  options: {
    animation: {
      duration: 0
    },
    scales: {
      xAxes: [{
        type: 'timecenter',
        time: {
          unit: 'month',
          stepSize: 1,
          displayFormats: {
            month: 'MMM'
          }
        },
        gridLines: {
          offsetGridLines: true
        }
      }],
      yAxes: [{
        gridLines: {
          drawBorder: false
        }
      }]
    },
    tooltips: {
      intersect: false,
      mode: 'index'
    }
  }
};
var chart = new Chart('chart1', cfg);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="chart1" height="90"></canvas>

对于 chartJs v3 你可以使用 offset 属性:

scales: {
  x: {
    grid: {
        offset: true
    }
  },
...
}