0👍
✅
Your promise is OK (i.e. d3.text("temp.csv").then(makeChart);
) but your logic in makeChart
has a few issues:
- Remove the space between the
,
andy
in the header you add – otherwise it’s creating a object key like this" y"
instead of justy
- The
y
values need to be converted to float becausecsvParse
defaults to values as text without a conversion function datos.x
anddatos.y
do not refer to anything asdatos
has no specificx
andy
keys – it is an array of objects, each of which hasx
andy
keys. So, you can usemap
to extract the arrays of those keys
Working example below:
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>
Source:stackexchange.com