score:8
Accepted answer
Basically, convert every single file-line string:
2020-02-15 18:37:39,-8.25
into an Object:
{x: "2020-02-15 18:37:39", y: -8.25}
to be stored inside the Chart.js data : []
Array.
Here's an example on how to create a function csvToChartData()
that returns such an Array (to be used like: ... data: csvToChartData(csv)
)
- Trim and split a file string by newline
\n
into alines
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('\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>
Fetch data dynamically:
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!
Source: stackoverflow.com
Related Query
- How can I create a time series line graph in chart.js?
- how can i use chart.js to create a chart that has one time series line and one linear line on it at the same time?
- How can I create a horizontal scrolling Chart.js line chart with a locked y axis?
- How to create multiple y-axis time series chart
- How can I remove extra whitespace from the bottom of a line chart in chart.js?
- How to create a gradient fill line chart in latest Chart JS version (3.3.2)?
- Chart.js: How can a line series (out of many) change line color and thickness upon mouse hover?
- How to start the line graph from the left Y axis in a line/bar mixed chart (Chart.js)?
- Time series line chart is not displayed
- Time Series Line chart js in react not working
- How can I make line on chart thinner?
- I have 10 points inn x-axis, ranging [-25,-20,,-15,-10,0,10,20,30,40,50]. But I want my line chart to start from -15 of x-axis. How we can achieve?
- How can I add a euro sign (€) to all tooltips in my chart js line chart
- How to create line graph use chartjs?
- How do you make a progressive line chart with time as the X axis?
- How to create a bar and a line in a same graph using chart.js in React?
- How to create a line chart indicating which month a user wrote more or less blogs?
- How create time line chat with selectable year dropdown
- How to use chart.js to plot line chart with x axis as time stamp in seconds
- How can I create a stacked bar chart with Charts.JS that displays relative rather than absolute values?
- How can I reduce the spacing between my legend and chart proper in my Chart.JS bar chart, and increase it in the graph area?
- How can I draw a line to the highest datapoint in chart js?
- How to zoom Y axis on time series or X-Y chartjs graph
- How to create a line on a chart using chartjs-plugin-annotation
- How can I create a bar chart that has multiple yAxes scales?
- How to Add X axis Padding in chart js Line Graph
- How to bind data from Controler to chartjs line chart to create it as dynamic?
- How can I create a vertical scrolling in Chart.js for line chart?
- how to create line chart using chart.js in angular 2+
- Chartjs: how can i create a graph with multiple jsons files?
More Query from same tag
- Dynamic chart codeigniter
- Pausing Javascript animation on minimize
- How can I hide tick marks on Chart.js?
- How do I display chart on my HTML page based on JSON data sent by Node JS
- Loop datasets into chart.js?
- ChartJS - Gradient color overlap
- hh:mm in chart.js on X-axis and text labels on the Y-axis
- How can I scale my dataset values as a percentage of the index in chart.js?
- Issue loading chart.js zoom plugin with require.js
- Multiple Chart JS percentage labels
- cannot read property 'yyyx' of undefined
- Responsive Chart.js Doughnut Chart with minimum height
- chart.js:4 Uncaught ReferenceError: require is not defined in ionic 2
- JavaScript implementation doesnt work (Chart.js)
- Chartjs: Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'HALF_PI')
- How do I make line charts overlay over bar charts in chartjs
- ReferenceError: Chart is not defined - chartjs
- pan on chart.js also zoom on line charts
- ng2-charts: How to set fixed range for y axis
- Charts js - How to make gridlines dash and How to make the gridlines stop at each point
- Vue.js: How to retrieve data from API for vue chart.js
- After form submit, function runs quickly and chart.js shows up for a second then goes away
- Chart.js - Increase spacing between legend and chart
- issue populating chart.js from entity framework in .Net Core 5
- Chartjs - pointColor to follow current color of gradient stroke
- Chart.js awkward label gaps before last x-axis label
- Horizontal Stacked Bar with Gaps
- Replace Chart.js Data during `onClick` causes _meta error
- Load data from a JSON object into an array
- Position Label under the Horizontal Bar