如何在 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
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 chartdata:
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!
相关文章