如何在 Chart.js 中将刻度线移动到 x 轴上方

问题描述 投票:0回答:3

我正在 Chart.js 中处理图表,我的 x 轴如下所示:

我已经查看了文档和 GitHub,似乎不可能将最左侧的标签重新调整到右侧,将最右侧的标签重新调整到左侧一点。但是,我想知道是否可以使刻度线从 x 轴向上而不是向下?

javascript html chart.js
3个回答
0
投票

您可以在刻度中使用

mirror
选项,如下所示:

const 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: {
      x: {
        ticks: {
          mirror: true
        }
      }
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.js"></script>

<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
</body>


0
投票

我认为目前在 Chart.js 中这是不可能的。


0
投票

事实上,这是可能的。您可以设置负数tickLength

const 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: {
      x: {
        grid: {
          display: true,
          lineWidth: 0,
          tickWidth: 2,
          tickLength: -10,
        },
        ticks: {
          padding: 10,
        }
      }
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.js"></script>

<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
</body>

© www.soinside.com 2019 - 2024. All rights reserved.