如何在chart.js中创建时间线折线图? [英] How can I create a time series line graph in chart.js?

查看:70
本文介绍了如何在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,
   }
   }
 }
});



推荐答案

基本上,转换每个文件行字符串

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

放入 Object

{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) )


  • 修剪并通过换行符 \n 将文件字符串拆分数组。

  • 使用 lines.shift(); (第一个数组键) >
  • 将每条行转换为对象 {x:日期,y:温度} 通过用逗号分隔每行 .split(',')

  • 传递新映射的数组(通过使用 .map())作为图表 数据:

  • Trim and split a file string by newline \n 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('\n');
  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和获取API

这是经过修改的JS示例,假设您有一个名为CSV的文件 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("\n");
  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中创建时间线折线图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆