如何在坐标轴和工具提示中格式化Chart.js的日期。

huangapple go评论86阅读模式
英文:

How to format Chart.js dates in the axes and tooltip

问题

以下是您要翻译的内容:

我有以下使用chart.js生成折线图的代码。
Y轴表示价格值,而X轴表示日期值。
我希望X轴上的日期只显示年份,但仍然希望在悬停在数据点上时在工具提示中显示完整日期。

  const datesArray = ["2023年5月1日", "2023年5月2日", "2023年5月3日", "2023年5月4日", "2023年5月5日"];
  const valuesArray = [107.71, 105.98, 106.12, 105.21, 106.215];

  const Chart = ({ width }) =>  (
    <ChartDiv style={{ width }} className='cursor-auto'>
      <PriceGraph 
         chartData={{ data: valuesArray, labels: datesArray }} 
         chartColour='#218B82' 
         chartFillColour='#F2FFFF' 
      />
    </ChartDiv>
  );
import React from 'react';
import { Line } from 'react-chartjs-2';
import { Chart, registerables } from 'chart.js';
import 'chartjs-adapter-date-fns';
Chart.register(...registerables);

const PriceGraph = ({ chartData, chartColour, chartFillColour }) => {
  const options = {
    scales: {
      x: {
        ticks: {
          display: true,
          callback: (value, index, values) => {
            const tickDate = new Date(value);
            return tickDate.getFullYear().toString();
          }
        }
      },
      y: {
        beginAtZero: true,
        ticks: {
          display: true,
        }
      }
    }
  }

  const data = {
    labels: chartData.labels,
    datasets: [
      {
        data: chartData.data,
        backgroundColor: chartFillColour,
        borderColor: chartColour,
        fill: true,
      }
    ]
  }

  return <Line data={chartData.labels ? data : null} options={options}/>;  
}

export default PriceGraph

当我运行我的代码时,工具提示反映了正确的日期,但X轴上的每个刻度都显示"1970年"。我认为这可能是由于在我的回调函数中输入了不适当的数据或不适当使用回调函数引起的问题。

在查看了chart.js文档后,有迹象表明我应该使用type: time,并应用格式化。当我按照以下方式修改我的代码时,我得到了一个空白图表。

scales: {
      x: {
        type: 'time',
        time: {
          unit: 'year',
          tooltipFormat: 'yyyy年MM月dd日'
        },
        ticks: {
          display: true,
        }
      },

您对如何格式化X轴有何建议吗?

英文:

I have the following code that uses chart.js to generate a line graph.
The Y axis represents price values, while the X axis represents date values.
I want the dates on the X axis to display only the year, but I still want the full date to appear in the tooltip when hovering over a data point.

  const datesArray = [&quot;1 May 2023&quot;, &quot;2 May 2023&quot;, &quot;3 May 2023&quot;, &quot;4 May 2023&quot;, &quot;5 May 2023&quot;];
  const valuesArray = [107.71, 105.98, 106.12, 105.21, 106.215];

  const Chart = ({ width }) =&gt;  (
    &lt;ChartDiv style={{ width }} className=&#39;cursor-auto&#39;&gt;
      &lt;PriceGraph 
         chartData={{ data: valuesArray, labels: datesArray }} 
         chartColour={&#39;#218B82&#39;} 
         chartFillColour={&#39;#F2FFFF&#39;} 
      /&gt;
    &lt;/ChartDiv&gt;
  );
import React from &#39;react&#39;;
import { Line } from &#39;react-chartjs-2&#39;;
import { Chart, registerables } from &#39;chart.js&#39;;
import &#39;chartjs-adapter-date-fns&#39;;
Chart.register(...registerables);

const PriceGraph = ({ chartData, chartColour, chartFillColour }) =&gt; {
  const options = {
    scales: {
      x: {
        ticks: {
          display: true,
          callback: (value, index, values) =&gt; {
            const tickDate = new Date(value);
            return tickDate.getFullYear().toString();
          }
        }
      },
      y: {
        beginAtZero: true,
        ticks: {
          display: true,
        }
      }
    }
  }

  const data = {
    labels: chartData.labels,
    datasets: [
      {
        data: chartData.data,
        backgroundColor: chartFillColour,
        borderColor: chartColour,
        fill: true,
      }
    ]
  }

  return &lt;Line data={chartData.labels ? data : null} options={options}/&gt;;  
}

export default PriceGraph

When I run my code the tool tip reflects the correct date, however each tick on the X Axis displays "1970". I expect this is an issue with the data being input input in my callback function or the inappropriate use of a callback function.

Reviewing the chart.js documentation, there is an indication that I should use the type: time, and apply formatting. When I modify my code as follows I get a blank chart.

scales: {
      x: {
        type: &#39;time&#39;,
        time: {
          unit: &#39;year&#39;,
          tooltipFormat: &#39;dd MMM yyyy&#39;
        },
        ticks: {
          display: true,
        }
      },

Any suggestions on how I should go about formatting my X axis?

答案1

得分: 1

由于某些原因,回调函数内的参数未按预期填充。理想情况下,第一个参数的值应该是要打印的值。

解决此问题的方法是使用现有的数据和回调参数中的索引。您可以尝试以下代码。

callback: function(value, index, ticks) {
  const tickDate = new Date(chartData.labels[index]);
  return tickDate.getFullYear().toString();
}
英文:

For some reasons the parameters inside callback function are not populated as expected. Ideally first parameter value should be the value which is going to be print.

The workaround for this would be to use your existing data and the index from the callback parameter. You can try the below code.

callback: function(value, index, ticks) {
  const tickDate = new Date(chartData.labels[index]);
  return tickDate.getFullYear().toString();
}

huangapple
  • 本文由 发表于 2023年5月30日 10:51:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76361329.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定