【问题标题】:How to make chartjs chart with time y-axis?如何用时间y轴制作chartjs图表?
【发布时间】:2023-02-10 12:44:22
【问题描述】:

我有这样的数据:

{
"measurements": [
{
  "id": 10,
  "key": "Demoo",
  "value": "00:00:03.733;",
  "date": "2023-02-08",
  "time": "11:05",
  "value_time_formatted": "00:00:03.733"
},
{
  "id": 11,
  "key": "Demooo 2",
  "value": "00:00:05.191;",
  "date": "2023-02-08",
  "time": "11:31",
  "value_time_formatted": "00:00:05.191"
},
{
  "id": 12,
  "key": "Demo 22",
  "value": "00:00:03.002;",
  "date": "2023-02-08",
  "time": "11:31",
  "value_time_formatted": "00:00:03.002"
}
]}

当我尝试从日期作为标签和 value_time_formatted 作为值制作折线图时,我收到此错误:

ERROR TypeError: Cannot create property 'data' on string '00:00:03.733'

绑定图表值的代码如下所示:

 this.lineBarLabels = [];
      this.lineBarValue = [];
      res.measurements.forEach(element => {
        this.lineBarLabels.push(element.date);
        this.lineBarValue.push(element.value_time_formatted);
      });

      this.lineBar = new Chart(this.linePresents.nativeElement, {
  type: 'line',
  data: {
    labels: this.lineBarLabels,
    datasets: this.lineBarValue
  }
});
this.lineBar.update();

我试图将该时间转换为毫秒,但在屏幕上看起来很丑陋,用户需要将其转换回小时、分钟、秒和毫秒,这对客户来说太糟糕了:(

【问题讨论】:

    标签: javascript angular ionic-framework charts chart.js


    【解决方案1】:

    您的代码有一些问题,这里是我可以发现的两个问题:

    • 发生主要错误是因为 chartjs 需要属性 dataset 的对象数组,因此在您的情况下,您必须将代码更改为如下所示:

      this.lineBar = new Chart(this.linePresents.nativeElement, {
          type: 'line',
          data: {
              labels: this.lineBarLabels,
              datasets: [{data: this.lineBarValue}]
          }
      });
      
    • 永远不会设置数组 this.lineBarLabels(将是一个空数组),您必须将:this.lineBarLabels.includes(element.date); 更改为 this.lineBarLabels.push(element.date);

    这些是主要问题,我不明白你应该寻找什么输出,我不认为将值设置为字符串 value_time_formatted 会起作用,但如果你解决了上述问题,你将成为更接近工作图表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-02
      • 1970-01-01
      • 1970-01-01
      • 2016-06-24
      • 2015-06-16
      • 2016-11-30
      相关资源
      最近更新 更多