如何在 chart.js 中创建时间序列折线图?

How can I create a time series line graph in chart.js?(如何在 chart.js 中创建时间序列折线图?)
本文介绍了如何在 chart.js 中创建时间序列折线图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个 python 脚本,它从 API 获取数据以获取特定时间的天气温度

I created a python script that fetches data from an API to get weather temperature at a certain time

结果是一个如下所示的 CSV 文件:

The result is a CSV file that looks like this:

Time,Temperature
2020-02-15 18:37:39,-8.25
2020-02-15 19:07:39,-8.08
2020-02-15 19:37:39,-8.41
2020-02-15 20:07:39,-8.2

如何将 CSV 转换为 JavaScript 数组并从中制作 Chart.js 折线图?

How can transform the CSV into a JavaScript array and make a Chart.js line chart out of it?

现在,我有一个看起来像这样的 Chart.js 基本脚本(没有填充任何数据)

Right now, I have a Chart.js base script that looks like this (isn't filled with any data)

new Chart(document.getElementById("line-chart"), {
type: 'line',
 data: {
   labels: [],
   datasets: [{ 
       data: [],
       label: "Temperature",
       borderColor: "#3e95cd",
       fill: false
     } 
   ]
 },
 options: {
   scales: {
     xAxes: [{
       type: 'time',
       distribution: 'linear',
     }],
   title: {
     display: false,
   }
   }
 }
});


推荐答案

基本上,转换每一个文件行string:

Basically, convert every single file-line string:

2020-02-15 18:37:39,-8.25 

进入一个对象:

{x: "2020-02-15 18:37:39", y: -8.25}

存储在 Chart.js data : [] 数组中.

to be stored inside the Chart.js data : [] Array.

这是一个关于如何创建返回此类数组的函数 csvToChartData() 的示例(使用如下: ... data: csvToChartData(csv) )

Here's an example on how to create a function csvToChartData() that returns such an Array (to be used like: ... data: csvToChartData(csv) )

  • 通过newline 将文件字符串修剪和拆分lines 数组.
  • 删除标题(第一个数组键)使用 lines.shift();
  • 将每一行转换为一个对象 {x: date, y: temperature} 用逗号分隔每一行 .split(',')
  • 将新映射的数组(通过使用 .map())作为图表 data:
  • Trim and split a file string by newline into a lines array .
  • Remove titles (the first array key) by using lines.shift();
  • Convert every line to an object {x: date, y: temperature} by splitting each line by comma .split(',')
  • Pass that newly mapped Array (by using .map()) as your chart data:

const csv = `Time,Temperature
2020-02-15 18:37:39,-8.25
2020-02-15 19:07:39,-8.08
2020-02-15 19:37:39,-8.41
2020-02-15 20:07:39,-8.2`;

const csvToChartData = csv => {
  const lines = csv.trim().split('
');
  lines.shift(); // remove titles (first line)
  return lines.map(line => {
    const [date, temperature] = line.split(',');
    return {
      x: date,
      y: temperature
    }
  });
};

const ctx = document.querySelector("#line-chart").getContext('2d');
const config = {
  type: 'line',
  data: {
    labels: [],
    datasets: [{
      data: csvToChartData(csv),
      label: "Temperature",
      borderColor: "#3e95cd",
      fill: false
    }]
  },
  options: {
    scales: {
      xAxes: [{
        type: 'time',
        distribution: 'linear',
      }],
      title: {
        display: false,
      }
    }
  }
};
new Chart(ctx, config);

#line-chart {
  display: block;
  width: 100%;
}

<canvas id="line-chart"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>

要动态获取数据,比如每 5 秒,您可以使用 AJAX 和 Fetch API.
这是修改后的 JS 示例,因为您有一个名为 temperature.csv

To fetch the data dynamically, say every 5 seconds, you could use AJAX and the Fetch API.
Here's the modified JS example given you have a CSV file called temperature.csv

const config = {
  type: "line",
  data: {
    labels: [],
    datasets: [{
      data: [], // Set initially to empty data
      label: "Temperature",
      borderColor: "#3e95cd",
      fill: false
    }]
  },
  options: {
    scales: {
      xAxes: [{
        type: "time",
        distribution: "linear"
      }],
      title: {
        display: false
      }
    }
  }
};

const ctx = document.querySelector("#line-chart").getContext("2d");
const temperatureChart = new Chart(ctx, config);

const csvToChartData = csv => {
  const lines = csv.trim().split("
");
  lines.shift(); // remove titles (first line)
  return lines.map(line => {
    const [date, temperature] = line.split(",");
    return {
      x: date,
      y: temperature
    };
  });
};

const fetchCSV = () => fetch("temperature.csv")
  .then(data => data.text())
  .then(csv => {
    temperatureChart.data.datasets[0].data = csvToChartData(csv);
    temperatureChart.update();
    setTimeout(fetchCSV, 5000); // Repeat every 5 sec
  });

fetchCSV(); // First fetch!

这篇关于如何在 chart.js 中创建时间序列折线图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)