如何为 react-chartjs-2 图表获取多个 x 轴标签

how to get multiple x-axis labels for a react-chartjs-2 chart

有谁知道如何在 react-chartjs-2 图表中获取多个 x 轴标签?我看到几个示例,其中人们使用 chart.js 而不是 react-chartjs-2。我怀疑 react-chartjs-2 在涉及 options.scales.xAxes.

时可能表现略有不同

我正在使用 chart.js v3.6.1 & react-chartjs-2 v4.0.0

我发现 example 使用 chart.js,但不是 react-chartjs-2,它代表了我想要的。下面的代码我改编为使用 react-chartjs-2。即使我没有更改原始工作示例中的“选项”或“数据集”,标签也无法正确显示。

import React from 'react'
import { Bar } from 'react-chartjs-2';
import 'chart.js/auto';
import { Chart } from 'react-chartjs-2';

const TaskProgress3 = () => {
    const data = {
      labels: ["January;2015", "February;2015", "March;2015", "January;2016", "February;2016", "March;2016"],
      datasets: [{
        id: 1,
        label: '# of Votes',
        xAxisID:'xAxis1',
        data: [12, 19, 3, 5, 2, 3]
      }]
    };

    const options = {
      scales:{
        xAxes:[
          {
            id:'xAxis1',
            type:"category",
            ticks:{
              callback:function(label){
                var month = label.split(";")[0];
                return month;
              }
            }
          },
          {
            id:'xAxis2',
            type:"category",
            gridLines: {
              drawOnChartArea: false,
            },
            ticks:{
              callback:function(label){
                var month = label.split(";")[0];
                var year = label.split(";")[1];
                if(month === "February"){
                  return year;
                }else{
                  return "";
                }
              }
            }
          }],
        yAxes:[{
          ticks:{
            beginAtZero:true
          }
        }]
      }
    };

    return (
        <>
        <div>Bar Chart</div>
        <Bar
          datasetIdKey='id'
          data={data}
          options={options}
          height="100px"
          width="600px"
          />
        </>
    )
}

export default TaskProgress3;

这是因为您在 V3 中使用了 V2 语法,V3 有一些重大的重大变化。请阅读所有的 migration guide

在 v3 中,所有比例尺都是它们自己的对象,其中对象键是比例尺 ID

var options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderColor: 'orange'
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderColor: 'pink'
      }
    ]
  },
  options: {
    scales: {
      x: {
        ticks: {
          callback: function(label) {
            return `$${this.getLabelForValue(label)}`
          }
        }
      },
      secondXAxis: {
        axis: 'x',
        labels: ['V2', 'syntax', 'in', 'v3'],
        grid: {
          drawOnChartArea: 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/3.6.0/chart.js"></script>
</body>

你需要给每个数据集一个xAxisID在数据集中,这样你就可以定义它的位置和显示方式。

这是一个例子

import React from 'react';
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
} from 'chart.js';
import { Line } from 'react-chartjs-2';
import faker from 'faker';

ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend
);

export const options = {
  responsive: true,
  plugins: {
    legend: {
      position: 'top' as const,
    },
    title: {
      display: true,
      text: 'Chart.js Line Chart - Multiple X Axes',
    },
  },
  scales: {
    x1: {
      position: 'top',
      ticks: {
        callback: function(value, index, values) {
          return this.getLabelForValue(value).split(';')[1];
        }
      }
    },
    x2: {
      position: 'bottom',
      ticks: {
        callback: function(value, index, values) {
          return this.getLabelForValue(value).split(';')[0];
        }
      }
    }
  }
};

const labels = ["January;2015", "February;2015", "March;2015", "January;2016", "February;2016", "March;2016"];

export const data = {
  labels,
  datasets: [
    {
      label: 'Red Dataset',
      data: labels.map(() => faker.datatype.number({ min: -1000, max: 1000 })),
      borderColor: 'rgb(255, 99, 132)',
      backgroundColor: 'rgba(255, 99, 132, 0.5)',
      xAxisID: 'x1'
    },
    {
      label: 'Blue Dataset',
      data: labels.map(() => faker.datatype.number({ min: -1000, max: 1000 })),
      borderColor: 'rgb(53, 162, 235)',
      backgroundColor: 'rgba(53, 162, 235, 0.5)',
      xAxisID: 'x2'
    },
  ],
};

export function App() {
  return <Line options={options} data={data} />;
}