如何使用时间轴创建Chart.js图表?

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

How to make chartjs chart with time y-axis?

问题

以下是翻译好的代码部分:

{
  "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"
    }
  ]
}
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();

希望这对您有所帮助。如有其他问题,请随时提出。

英文:

I have data something like this:

{
"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"
}
]}

And when I try out to make a line chart from the date as labels and value_time_formatted as values I get this error:

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

The code for bind chart values looks like this:

 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();

I tried to convert that time into milliseconds but looks so ugly on-screen and the user needs to convert it back to hours, minutes, seconds, and milliseconds which is so bad from customer side 如何使用时间轴创建Chart.js图表?

答案1

得分: 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 会起作用,但如果你修复上述提到的问题,你将更接近一个可用的图表。

更新:

看起来你在问题中修复了一个错误,如果你想改进你的代码,这里有一个有关时间转换的提示(相关文档链接):

const date = new Date();

// 更简洁的解决方案
let aShortWay = date.toISOString().substring(11, 23);

// 你的代码:不太可读,而且相当冗长
let yourCode = (date.getUTCHours() ? (date.getUTCHours() > 9 ? date.getUTCHours() : '0' + date.getUTCHours()) : '00') + ':' +
               (date.getUTCMinutes() ? (date.getUTCMinutes() > 9 ? date.getUTCMinutes() : '0' + date.getUTCMinutes()) : '00') + ':' +
               (date.getUTCSeconds() ? (date.getUTCSeconds() > 9 ? date.getUTCSeconds() : '00' + date.getUTCSeconds()) : '00') + '.' +
               (date.getUTCMilliseconds() > 99 ? date.getUTCMilliseconds() : date.getUTCMilliseconds() > 9 ? '0' + date.getUTCMilliseconds() : '00' + date.getUTCMilliseconds());

console.info(`aShortWay 时间:${aShortWay}`)
console.info(`yourCode 时间:${yourCode}`)
英文:

Your code has a few issues, here the two I could spot:

  • the Main error ocurres because chartjs expects a object array for the property dataset, so in your case you would have to change your code to something like this:

    this.lineBar = new Chart(this.linePresents.nativeElement, {
        type: 'line',
        data: {
            labels: this.lineBarLabels,
            datasets: [{data: this.lineBarValue}]
        }
    });
    
  • The array this.lineBarLabels is never set (will be a empty array), you would have to change: this.lineBarLabels.includes(element.date); to this.lineBarLabels.push(element.date);

These are the main issues, I don't understand what output should you are looking for, and I don't think that setting the values to strings value_time_formatted will work, but if you fix the above mentioned points, you will be a step closer to a working chart.

Update:

It seems you fixed on mistake in your question, if you want to improve your code here is a tip for you time convertion (link to relevant documentation):

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const date = new Date();

// A cleaner solution
let aShortWay = date.toISOString().substring(11,23);

// Your Sode: Not really readable, and pretty long
let yourCode = (date.getUTCHours() ? (date.getUTCHours() &gt; 9 ? date.getUTCHours() : &#39;0&#39; + date.getUTCHours()) : &#39;00&#39;) + &#39;:&#39; +
                (date.getUTCMinutes() ? (date.getUTCMinutes() &gt; 9 ? date.getUTCMinutes() : &#39;0&#39; + date.getUTCMinutes()) : &#39;00&#39;) + &#39;:&#39; +
                (date.getUTCSeconds() ? (date.getUTCSeconds() &gt; 9 ? date.getUTCSeconds() : &#39;0&#39; + date.getUTCSeconds()) : &#39;00&#39;) + &#39;.&#39; +
                (date.getUTCMilliseconds() &gt; 99 ? date.getUTCMilliseconds() : date.getUTCMilliseconds() &gt; 9 ? &#39;0&#39; + date.getUTCMilliseconds() : &#39;00&#39; + date.getUTCMilliseconds());


console.info(`aShortWay Time:${aShortWay}`)
console.info(`yourCode Time:${yourCode}`)

<!-- end snippet -->

答案2

得分: 0

I finally find a solution, hope that someone will use it in the right way 如何使用时间轴创建Chart.js图表?

After this part of the code:

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

I made this createLineChart() method to parse and render the chart:

public createLineChart() {
    this.lineBar = new Chart(this.linePresents.nativeElement, {
        type: 'line',
        data: {
            labels: this.lineBarLabels,
            datasets: [{label: this.translate.instant('time'), data: this.lineBarValue, fill: false}]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    ticks: {
                        callback: function (value) {
                            const date = new Date(Number(value) * 1000);
                            return date.toISOString().substring(11,23);
                        }
                    }
                }
            },
            plugins: {
                tooltip: {
                    callbacks: {
                        label: function (context) {
                            const date = new Date(Number(context.formattedValue) * 1000);
                            return date.toISOString().substring(11,23);
                        }
                    }
                }
            }
        }
    });
    this.lineBar.update();
}
英文:

I finally find a solution, hope that someone will use it in the right way 如何使用时间轴创建Chart.js图表?

After this part of the code:

res.measurements.forEach(element =&gt; {
this.lineBarLabels.push(element.date);
this.lineBarValue.push(element.value_time_formatted);
});
this.createLineChart();

I made this createLineChart() method to parse and render the chart:

public createLineChart() {
this.lineBar = new Chart(this.linePresents.nativeElement, {
    type: &#39;line&#39;,
    data: {
      labels: this.lineBarLabels,
      datasets: [{label: this.translate.instant(&#39;time&#39;), data: this.lineBarValue, fill: false}]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      scales: {
        y: {
          ticks: {
            callback: function (value) {
              const date = new Date(Number(value) * 1000);
              return date.toISOString().substring(11,23);
            }
          }
        }
      },
      plugins: {
        tooltip: {
          callbacks: {
            label: function (context) {
              const date = new Date(Number(context.formattedValue) * 1000);
              return date.toISOString().substring(11,23);
            }
          }
        }
      }
    }
  }
);
this.lineBar.update();
}

huangapple
  • 本文由 发表于 2023年2月8日 18:39:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/75384570.html
匿名

发表评论

匿名网友

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

确定