如何增加 chartjs 中垂直网格线之间的间隙

How to increase gaps between vertical gridlines in chartjs

我使用Chartjs 绘制了大量数据集的图表。因此,默认情况下有许多垂直网格线,看起来很可怜​​。我想增加垂直线之间的距离。

任何帮助都会appriciated.Thanks

您可以使用 maxTicksLimit,这样只会渲染一定数量的刻度,从而使刻度之间的距离变大

代码:

options: {
  scales: {
    xAxes: [
      {
        ticks: {
          maxTicksLimit: 10
        }
      }
    ]
  }
}

来源:https://www.chartjs.org/docs/latest/axes/cartesian/linear.html

@LeeLenalee 的好回答

我想在 y 轴(水平网格线)的情况下添加一个额外的微调选项:

Chart.js v3.2.0

如果您想要实现极简设计,甚至 更少的网格线 (比如说只有 2 或 3 条网格线用于基本方向),图表往往不会利用完整的图表高度对于小的 maxTicksLimits(没有自动缩放,请参见 maxTicksLimit 的示例:3

这里有示例(y 轴)来演示:

  • 正常(无 ticks-costumization)

     options: {
        scales: {
          y: {
             ticks: {
                // no costumization
                }
             }
          }
       }
    

    (许多网格线和刻度线,但自动缩放有效)

  • maxTicksLimit: 10

     options: {
        scales: {
          y: {
             ticks: {
                maxTicksLimit: 10
                }
             }
          }
       }
    

    (更少的网格线和刻度,自动缩放仍然可以)

  • maxTicksLimit: 3

      options: {
         scales: {
           y: {
              ticks: {
                 maxTicksLimit: 3
                 }
              }
           }
        }
    

    (不利用完整图表高度,不自动缩放)

  • 回调

      options: {
         scales: {
           y: {
              ticks: {
                 callback: function(value, index, values) {
                    let step = 5;
    
                    //values[0].value is first tick (tick_min)
                    //values[values.length-1].value is last tick (tick_max)
    
                    //tick_max - tick_min is range of values at y-Axis
    
                    if (values[values.length-1].value - values[0].value > 15) {
                       //define condition (> 15) and
                       //step size (10) according to your estimated data range
                       step = 10;
                    } else {
                       step = 5;
                    };
                    if (Number.isInteger(value/step)) {
                       return value;
                    } else {
                       return '';
                    }
                   }
                 },
                 grid: {  //hide gridlines where there is no tick
                    z: 1,
                    color: function(context) {
                       if (context.tick.label != '')  {
                          return 'rgba(61,138,254,0.5)';
                       } else {
                          return 'rgba(61,138,254,0)'; //transparent
                       }
                    }
                 }
              }
           }
        }
    

    (几条网格线自动缩放OK)

    来源:https://www.chartjs.org/docs/latest/axes/labelling.html#creating-custom-tick-formats