【问题标题】:ChartJS 3+ x-axis only showing full moment object instead of just monthChartJS 3+ x 轴仅显示完整的时刻对象而不是仅显示月份
【发布时间】:2021-11-03 03:45:52
【问题描述】:

我试图使用 momentjs 在图表的 x 轴上仅显示月份和年份,但它只是将似乎是完整的时刻日期放在 x 轴上。

我一直在查看很多人这样做的例子,但似乎没有一个人在最新版本的 chartjs 中工作。 我知道我已经包含了与 momentjs 一起使用但无法知道它是否工作的“适配器”。

这是我正在使用的代码的 jsfiddle,将不胜感激。 https://jsfiddle.net/7z20jg68/

我也有错误告诉我Invalid scale configuration for scale: x,这令人困惑,因为我的 x 轴似乎是正确的顺序..谢谢!

【问题讨论】:

    标签: chart.js momentjs


    【解决方案1】:

    您的 X 轴刻度确实无效,您将其声明为 V2 语法的数组,在 V3 中,所有刻度都是它们自己的对象,其中对象的键是 scaleID。因此,移除 x 轴比例对象周围的数组括号将解决问题。

    还有你的图例和工具提示配置错误和错误的地方,还有 V2 语法。

    所有更改请阅读migration guide

    const gainedChart = document.getElementById('gained-chart').getContext('2d');
    
    const gain = [74.699997, 76.580002, 81.349998, 83.000000, 85.879997, 83.120003, 77.989998, 81.279999];
    const dates = ["Jan 2, 20", "Feb 3, 20", "Mar 4, 20", "Apr 5, 20", "May 6, 20", "Jun 9, 20", "Nov 10, 20", "Dec 11, 20"];
    
    let gainData = {
      datasets: [{
        label: "Gain (%)",
        data: gain,
        borderColor: 'rgba(255, 66, 66, 1)',
        backgroundColor: 'rgba(255, 66, 66, 1)',
        pointRadius: 1.2,
        pointBackgroundColor: 'rgba(255, 66, 66, 0.8)',
        pointHoverRadius: 6,
        pointHitRadius: 20,
        pointBorderWidth: 2,
    
      }]
    };
    let gainConfig = {
      plugins: {
        legend: {
          display: true,
          position: 'top',
          labels: {
            boxWidth: 80,
            color: 'black'
          },
        },
        tooltip: {
          callbacks: {
            label: function(tooltipItem, data) {
              return parseInt(tooltipItem.parsed.y)
            }
          }
        },
      },
      scales: {
        x: {
          type: 'time',
          time: {
            minUnit: 'month'
          }
        },
        y: {
          suggestedMax: 45,
          ticks: {
            stepSize: 5,
            //max: 100
          },
        },
      },
      maintainAspectRatio: false,
      responsive: true,
    };
    let lineGainChart = new Chart(gainedChart, {
      type: 'line',
      data: gainData,
      options: gainConfig,
      plugins: [{
        beforeInit: function(lineGainChart) {
          for (let c = 0; c < dates.length; c++) {
    
            let myMoment = moment(dates[c], 'MMM D, YYYY');
    
            lineGainChart.data.labels.push(myMoment);
          }
        }
      }]
    });
    <canvas class="graph-canvas" id="gained-chart" width="400" height="400"></canvas>
    
    <script src="https://cdn.jsdelivr.net/npm/moment@2.29.1/moment.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment@^1"></script>

    【讨论】:

    • 非常感谢你,你是救命稻草,我知道我怎么错过了这么小的一个细节
    猜你喜欢
    • 2020-01-03
    • 2020-07-26
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    • 2021-01-28
    • 1970-01-01
    • 2022-07-25
    相关资源
    最近更新 更多