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

2022-01-22 00:00:00 charts javascript chart.js chartjs-2.6.0

如何将我的 x 轴上的标签移动到另一个 x 轴标签之间.似乎没有任何效果,我无法在文档中找到任何内容.有解决方法吗?我正在使用折线图时间序列.

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

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

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

解决方案

您正在寻找的选项是 offsetGridLines.

<块引用>

如果true,网格线将移动到标签之间.

xAxes: [{...网格线: {偏移网格线:真}

在大多数情况下,这会产生预期的结果.不幸的是,它不适用于 Chart.js 问题 #403 中记录的时间轴一个>.感谢 Antti Hukkanen,存在 解决方法.

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

function generateData() {var unit = '天';函数随机数(最小值,最大值){返回 Math.random() * (max - min) + min;}函数随机点(日期,最后关闭){var open = randomNumber(lastClose * 0.95, lastClose * 1.05).toFixed(2);var close = randomNumber(open * 0.95, open * 1.05).toFixed(2);返回 {t: date.valueOf(),y:关闭};}var date = moment().subtract(1, 'years');var now = moment();变量数据 = [];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));}返回数据;}var TimeCenterScale = Chart.scaleService.getScaleConstructor('time').extend({getPixelForTick:函数(索引){var ticks = this.getTicks();if (index < 0 || index >= ticks.length) {返回空值;}//获取当前刻度的像素值.var px = this.getPixelForOffset(ticks[index].value);//获取下一个刻度的像素值.var nextPx = this.right;var nextTick = ticks[index + 1];如果 (nextTick) {nextPx = this.getPixelForOffset(nextTick.value);}//在当前刻度和下一个刻度的中间对齐标签.返回 px + (nextPx - px)/2;},});//注册刻度类型var defaults = Chart.scaleService.getScaleDefaults('time');Chart.scaleService.registerScaleType('timecenter', TimeCenterScale, defaults);变量 cfg = {数据: {数据集:[{label: 'CHRT - Chart.js Corporation',背景颜色:'红色',边框颜色:'红色',数据:生成数据(),类型:'线',点半径:0,填充:假,线张力:0,边框宽度:2}]},选项: {动画片: {持续时间:0},秤:{x轴:[{类型:'时间中心',时间: {单位:'月',步长:1,显示格式:{月份:'MMM'}},网格线: {偏移网格线:真}}],y轴:[{网格线: {画框:假}}]},工具提示:{相交:假,模式:'索引'}}};var chart = new Chart('chart1', cfg);

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></脚本><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script><canvas id="chart1" height="90"></canvas>

How can I move my labels on my x axes in between another x axes label. Nothing seems to work and I was unable to find anything on the docs. Is there a workaround? I'm using line chart time series. https://www.chartjs.org/samples/latest/scales/time/financial.html

Currently, with the code I have its generating the figure below:

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',

                }
            }
        };

This is what I have now:

I want the labels on the x-axis to be on center instead of below the y axis grid line.

Thanks to uminder, with his comment it solves the issue but now I have a conflicting tooltip which lie on a same grid. When I hover to april line first point it shows me mar 30 which lies just above it and vice versa.

I fixed it by changing the mode to nearest but why is it activating the another point?

解决方案

The option you're looking for is offsetGridLines.

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

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

In most cases, this produces the expected result. Unfortunately it doesn't work for time axes as documented in Chart.js issue #403. Thanks to Antti Hukkanen, there exists a workaround.

Please have a look at below runnable code snippet to see how it works.

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>

相关文章