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

2023-11-01前端开发问题
59

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

问题描述

如何将我的 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>

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

The End

相关推荐

js删除数组中指定元素的5种方法
在JavaScript中,我们有多种方法可以删除数组中的指定元素。以下给出了5种常见的方法并提供了相应的代码示例: 1.使用splice()方法: let array = [0, 1, 2, 3, 4, 5];let index = array.indexOf(2);if (index -1) { array.splice(index, 1);}// array = [0,...
2024-11-22 前端开发问题
182

layui要如何改变时间日历布局大小?
问题描述 我想改变layui时间日历布局大小,这个要怎么操作呢? 解决办法 可以用css样式对时间日历进行重新布局,具体代码如下: !DOCTYPE htmlhtmlheadmeta charset="UTF-8"title/titlelink rel="stylesheet" href="../../layui/css/layui.css" /style#test-...
2024-10-24 前端开发问题
271

JavaScript小数运算出现多位的解决办法
在开发JS过程中,会经常遇到两个小数相运算的情况,但是运算结果却与预期不同,调试一下发现计算结果竟然有那么长一串尾巴。如下图所示: 产生原因: JavaScript对小数运算会先转成二进制,运算完毕再转回十进制,过程中会有丢失,不过不是所有的小数间运算会...
2024-10-18 前端开发问题
301

JavaScript(js)文件字符串中丢失"\"斜线的解决方法
问题描述: 在javascript中引用js代码,然后导致反斜杠丢失,发现字符串中的所有\信息丢失。比如在js中引用input type=text onkeyup=value=value.replace(/[^\d]/g,) ,结果导致正则表达式中的\丢失。 问题原因: 该字符串含有\,javascript对字符串进行了转...
2024-10-17 前端开发问题
437

layui中table列表 增加属性 edit="date",不生效怎么办?
如果你想在 layui 的 table 列表中增加 edit=date 属性但不生效,可能是以下问题导致的: 1. 缺少日期组件的初始化 如果想在表格中使用日期组件,需要在页面中引入 layui 的日期组件,并初始化: script type="text/javascript" src="/layui/layui.js"/scrip...
2024-06-11 前端开发问题
455

Rails/Javascript:如何将 rails 变量注入(非常)简单的 javascript
Rails/Javascript: How to inject rails variables into (very) simple javascript(Rails/Javascript:如何将 rails 变量注入(非常)简单的 javascript)...
2024-04-20 前端开发问题
5