【问题标题】:ChartJS 2 How to globally remove xAxis gridLines?ChartJS 2 如何全局删除 xAxis 网格线?
【发布时间】:2023-03-21 06:08:01
【问题描述】:

我正在使用 chartjs 2,我正在尝试禁用 xAxis 上的网格线并启用 yAxis 上的网格线并将它们设为虚线。

我已通过将其添加到我的折线图配置中来实现此功能;

scales: {
    xAxes: [{
        display: true,
        gridLines: {
            display: false,
        }
    }],
    yAxes: [{
        display: true,
        gridLines: {
            display: true,
            borderDash: [2],
            borderDashOffset: [2],
            color: 'rgba(0, 0, 0, 0.04)',
            drawBorder: false,
            drawTicks: false,
        }
    }]
}

但是,当我这样做时,它会在我的图表中随机添加另一个轴,其中包含完全虚假的值。我想删除这个轴并保留原来的,但也要保留 gridLines 配置。

【问题讨论】:

    标签: chart.js chart.js2


    【解决方案1】:

    您可以为此设置默认值。您可以将其设置为 scale 默认值,以便它适用于所有图表类型和比例。如果您特别想隐藏 X 轴 gridLines,只需在图表类型级别进行设置。

    Chart.defaults.scale.gridLines.display = false // hides all the gridLines in all charts for all axes
    Chart.defaults.line.scales.xAxes[0].gridLines = {
      display: false
    } // Hides only the X axes gridLines in all line charts
    
    var options = {
      type: 'line',
      data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            borderWidth: 1
          },
          {
            label: '# of Points',
            data: [7, 11, 5, 8, 3, 7],
            borderWidth: 1
          }
        ]
      },
      options: {
        scales: {
          yAxes: [{
            ticks: {
              reverse: false
            }
          }]
        }
      }
    }
    
    var ctx = document.getElementById('chartJSContainer').getContext('2d');
    new Chart(ctx, options);
    <body>
      <canvas id="chartJSContainer" width="600" height="400"></canvas>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
    </body>

    【讨论】:

    • Chart.defaults.line.scales.xAxes[0] 对我来说只有变量“id”和“type”。没有“gridLines”,因此无法设置该默认值。任何想法为什么这些对我不可用?
    • 它在我的堆栈 sn-p 中也不可用,这就是为什么我将 gridLines 设置为一个对象,因为如果我尝试像这样设置它:Chart.defaults.line.scales.xAxes[0].gridLines.display = false 它不能这样做,因为 gridLines 是未定义的。这就是为什么我这样做.gridLines = {} 所以它使对象上的属性
    猜你喜欢
    • 1970-01-01
    • 2017-12-04
    • 1970-01-01
    • 2021-10-07
    • 1970-01-01
    • 2021-11-05
    • 2019-01-25
    • 1970-01-01
    • 2022-12-01
    相关资源
    最近更新 更多