我正在嘗試從我的樹莓派加載一個由兩列(時間和溫度)組成的 csv 檔案,并使用 chartjs 制作圖表。在一些教程中,我發現我可以用 d3 做到這一點,但似乎我在承諾方面做錯了。
var csv = `
21:34:03,17.25
21:35:04,17.18
21:36:03,17.18
21:37:03,17.18
21:38:03,17.18
21:39:03,17.18
21:40:03,17.18
21:41:03,17.12
21:42:03,17.18
21:43:03,17.12
21:44:03,17.12
21:46:03,17.12
21:47:02,17.12
21:48:03,17.12
21:49:02,17.12
21:50:03,17.06
21:51:03,17.06
21:52:03,17.06
21:53:03,17.06
21:54:03,17.06
21:55:04,17.06
21:56:03,17.06
21:57:02,17.06
21:58:03,17.06
22:00:04,17.00
22:01:02,17.00`;
//couldn't find a way to embed the csv into the text function for the snippet
d3.text("temp.csv").then(makeChart);
function makeChart(temp) {
var result = "x, y\n" temp; //now you have the header
var datos = d3.csvParse(result);
var chart = new Chart('chart', {
type: 'line',
data: {
labels: datos.x,
datasets: [{
data: datos.y
}]
}
});
console.log(this.chart.data);
return this.chart;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.min.js"></script>
<canvas id="chart" width="400" height="400"></canvas>
樣本資料(這應該是 temp.csv):
21:34:03,17.25
21:35:04,17.18
21:36:03,17.18
21:37:03,17.18
21:38:03,17.18
21:39:03,17.18
21:40:03,17.18
21:41:03,17.12
21:42:03,17.18
21:43:03,17.12
21:44:03,17.12
21:46:03,17.12
21:47:02,17.12
21:48:03,17.12
21:49:02,17.12
21:50:03,17.06
21:51:03,17.06
21:52:03,17.06
21:53:03,17.06
21:54:03,17.06
21:55:04,17.06
21:56:03,17.06
21:57:02,17.06
21:58:03,17.06
22:00:04,17.00
22:01:02,17.00
我不知道還要添加什么,但我發現的唯一解決方法是完全擺脫 d3 雖然我想了解如何在這個例子中使用它的承諾。
uj5u.com熱心網友回復:
你的承諾是好的(即d3.text("temp.csv").then(makeChart);
),但你的邏輯makeChart
有一些問題:
- 洗掉您添加的標題中的
,
和之間的空格y
- 否則它會創建一個像這樣的物件鍵," y"
而不僅僅是y
- 這些
y
值需要轉換為浮點數,因為csvParse
默認值是沒有轉換函式的文本 datos.x
并且datos.y
不要參考任何datos
沒有特定x
和y
鍵的東西 - 它是一個物件陣列,每個物件都有x
和y
鍵。因此,您可以使用map
來提取這些鍵的陣列
下面的作業示例:
var url = "https://gist.githubusercontent.com/robinmackenzie/ff787ddb871cef050d7e6279991a0f07/raw/4ce35de3a9bef27363d83e7da2f3365ffa8d2345/data.csv";
d3.text(url)
.then(csv => makeChart(csv))
function makeChart(temp) {
// add the header (no space between , and y
var result = "x,y\n" temp; //now you have the header
// csv parse - need to convert y values to float
var datos = d3.csvParse(result, d => {
return {
x: d.x,
y: parseFloat(d.y)
}
});
// render chart
var chart = new Chart('chart', {
type: 'line',
data: {
labels: datos.map(d => d.x), // <-- just get x values
datasets: [{
data: datos.map(d => d.y) // <-- just get y values
}]
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.min.js"></script>
<canvas id="chart" width="400" height="100"></canvas>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/488304.html
標籤:javascript d3.js 图表 图表.js