首页 > 解决方案 > Chart.js 的 y 轴步长从 20 到 1(而不是 1 到 20)

问题描述

我正在使用 chart.js 尝试在此处重新创建此图表:https ://www.transfermarkt.us/fc-liverpool/platzierungen/verein/31

我遇到的问题是让 y 轴从 20 步进到 1。这可能吗?

  barChartOptions: ChartOptions = {
   responsive: true,
   maintainAspectRatio: false,
    scales: {
     yAxes: [{
      ticks: {
       reverse: true,
       min: 1,
       max: 20
      }
    }]

  }
};

不幸的是, reverse: true 属性并不能解决这个问题,因为它也会翻转整个数据。

标签: chart.js

解决方案


确保不在第一个上显示刻度,yAxis并添加第二个yAxis以相反顺序显示生成的刻度。

{
  ticks: {
    reverse: true,
    autoSkip: false,
    max: 1,
    min: 20
  },
  afterBuildTicks: (axis, ticks) => Array(20).fill().map((v,i) => i + 1).reverse()
}

此外,您必须定义一个tooltips.callback.label函数以在工具提示中显示正确的值。

请查看下面的可运行代码片段。

const labels = ['A', 'B', 'C', 'D'];
const data = [12, 1, 8, 17];
const yTop = 1;
const yBottom = 20;

new Chart('myChart', {
  type: 'bar',
  data: {
    labels: labels,
    datasets: [{
      label: "My Dataset",
      data: data.map(v => yBottom + 1 - v),
      borderWidth: 3
    }]
  },
  options: {
    legend: {
      display: false
    },
    tooltips: {
      callbacks: {
        label: tooltipItem => data[tooltipItem.index]
      }
    },
    scales: {
      yAxes: [{
          ticks: {
            display: false,
            min: yTop,
            max: yBottom
          },
          gridLines: {
            drawTicks: false
          }
        },
        {
          ticks: {
            reverse: true,
            autoSkip: false,
            max: yTop,
            min: yBottom
          },
          afterBuildTicks: (axis, ticks) => Array(yBottom).fill().map((v, i) => i + 1).reverse()
        }
      ],
      xAxes: [{
        gridLines: {
          display: false
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="120"></canvas>


推荐阅读