ChartJS 点击所有条形图标签只显示两天

mum43rcc  于 2023-10-18  发布在  Chart.js
关注(0)|答案(1)|浏览(127)

我创建了一个条形图,当我点击所有标签时,它会更新日期,只显示两天,我没有发现这种奇怪的行为,也许这是糟糕的实现,因为我使用解析,有人可以帮助吗?
我用最少的例子创建了一个stackblitz。https://stackblitz.com/edit/angular-13-lsvqov?file=src%2Fapp%2Fapp.component.ts

this.chart = new Chart('eventsChart', {
        type: 'bar',
        data: {
          datasets: this.generateChartData(mergedKeys)
        },
        options: {
          plugins: {
            tooltip: {
              callbacks: {
                title: context => {
                  const d = new Date(context[0].parsed.x);
                  return d.toLocaleString([], {
                    day: '2-digit',
                    month: 'short',
                    year: 'numeric'
                  });
                }
              }
            }
          },
          scales: {
            x: {
              type: 'time',
              time: {
                unit: 'day'
              }
            },
            y: {
              ticks: {
                stepSize: 1
              }
            }
          },
          aspectRatio: 2,
          maintainAspectRatio: false,
          responsive: true
        }
      });

  private generateChartData(keys: string[]) {
    return keys.map((key: string) => {
      return {
        label: key,
        data: this.dataSource,
        parsing: {
          xAxisKey: 'periodStartTime',
          yAxisKey: `keyStats.${key}`
        },
        backgroundColor: labelColor[key]
      };
    });
  }
xfyts7mz

xfyts7mz1#

为时间轴提供最小最大配置。这将允许您在x轴上显示最小和最大日期,即使所有标签都未选中。

let sortedDates = data.map(x => x.periodStartTime).sort();

let minDate = sortedDates[0];
let maxDate = sortedDates[sortedDates.length - 1];

const mergedKeys = this.getChartKeys(data);

const chartGenericDataSets = this.generateChartData(mergedKeys);

this.chart = new Chart('eventsChart', {
  ...,
  options: {
    scales: {
      x: {
        type: 'time',
        time: {
          unit: 'day',
        },
        min: minDate,
        max: maxDate
      },
    },
    aspectRatio: 2,
    maintainAspectRatio: false,
    responsive: true,
  },
});

Demo @ StackBlitz

相关问题