Chart.js:如何更改任何尺寸的X轴刻度标签对齐方式? [英] Chart.js : How I change the x axes ticks labels alignment in any sizes?

查看:223
本文介绍了Chart.js:如何更改任何尺寸的X轴刻度标签对齐方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

解决方案

您要查找的选项是 Chart.js问题#403 .多亏了Antti Hukkanen,存在一个解决方法.

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

  function generateData(){var unit ='day';函数randomNumber(min,max){返回Math.random()*(max-min)+ min;}函数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);返回 {t:date.valueOf(),y:关闭};}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));}返回数据;}var TimeCenterScale = Chart.scaleService.getScaleConstructor('time').extend({getPixelForTick:函数(索引){var ticks = this.getTicks();if(index< 0 || index> = ticks.length){返回null;}//获取当前刻度的像素值.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,默认值);var cfg = {数据: {数据集:[{标签:"CHRT-Chart.js Corporation",backgroundColor:红色",borderColor:'红色',数据:generateData(),类型:行",pointRadius:0,填写:假,lineTension:0,borderWidth:2}]},选项: {动画片: {持续时间:0},比例尺:{x轴:[{类型:时间中心",时间: {单位:月",stepSize:1displayFormats:{月:"MMM"}},网格线: {offsetGridLines:正确}}],y轴:[{网格线: {drawBorder:否}}]},工具提示:{相交:假,模式:索引"}}};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>  

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>

这篇关于Chart.js:如何更改任何尺寸的X轴刻度标签对齐方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆