React ChartJS 数据在 x 轴上不呈现日期

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

需要在 x 轴上显示日期的图表

这里是数据:

  const data = {
    datasets: [
      {
        label: "Fe",
        borderColor: "Red",
        backgroundColor: "Red",
        showLine: true,
        hidden: true,
        data: [
          {
            x: "2/1/2021",
            y: 1,
            elementHover: "Fe 1 26726 2/1/2021 12:00:00 AM 20210205100603",
          },
          {
            x: "5/27/2021",
            y: 2,
            elementHover: "Fe 2 27650 5/27/2021 12:00:00 PM 20210601100803",
          },
          {
            x: "4/3/2022",
            y: 4,
            elementHover: "Fe 4 24667 4/3/2022 12:00:00 PM 20220405101102",
          },
          {
            x: "6/5/2022",
            y: 4,
            elementHover: "Fe 4 25126 6/5/2022 12:00:00 PM 20220613101104",
          },
          {
            x: "7/28/2022",
            y: 3,
            elementHover: "Fe 3 25554 7/28/2022 12:00:00 PM 20220804100105",
          },
          {
            x: "9/14/2022",
            y: 3,
            elementHover: "Fe 3 25990 9/14/2022 12:00:00 PM 20220927100604",
          },
        ],
      },
    ],
  };

图表选项:

var timeFormat = "MM/dd/yyyy";
  const [options, setOptions] = useState({
    elements: {
      pointStyle: "cross",
    },
    scales: {
      xAxes: [
        {
          type: "time",
          time: {
            format: timeFormat,
            tooltipFormat: "ll",
          },
          displayFormats: {
            year: "MM/yy/ddd",
          },
          scaleLabel: {
            display: true,
            labelString: "Date",
          },
        },
      ],
    },
    plugins: {
      datalabels: {
        display: false,
        color: "black",
        align: "top",
        formatter: function (value, context) {
          return value.y;
        },
      },
      legend: {
        position: "right",
        align: "center",
        labels: {
          boxWidth: 10,
          pointStyle: "cross",
        },
      },
      tooltip: {
        callbacks: {
          label: function (context) {
            return context.raw.elementHover;
          },
          title: function (context) {
            return "";
          },
        },
      },
    },
  });

图表:

<Grid item xs={12}>
            {chartData && (
              <Scatter
                ref={chartReference}
                style={{ width: "60%", height: "60%" }}
                type="Scatter"
                data={data}
                options={options}
              />
            )}
          </Grid>

控制台:

Invalid configuration for scale: xAxis
reactjs chart.js react-chartjs react-chartjs-2
2个回答
0
投票

原来是少了“chartjs-adapter-moment”。将其添加到项目中并且有效。


-1
投票

你检查过你的控制台了吗?你有什么错误吗?

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