Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a time series line graph in chart.js?

I created a python script that fetches data from an API to get weather temperature at a certain time

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

How can transform the CSV into a JavaScript array and make a Chart.js line chart out of it?

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,
   }
   }
 }
});


like image 233
Power_Lemming Avatar asked Feb 16 '20 02:02

Power_Lemming


People also ask

How to plot time series data with chart JS?

Plotting time series data with Chart.js is easy. We can plot time series data with a line chart, which is a chart type that’s built into Chart.js To use Chart.js, we first include it with a script tag by writing:

How to create a line chart in JavaScript?

The normal order of visualizing data in JavaScript charts can be broken down into four basic steps, and building a JS line chart follows the same pattern: 1 Creating a basic HTML page to speay the chart. 2 Including all the JS scripts we need. 3 Adding the data for the chart. 4 Writing the JS charting code. More ...

How do I create a time series chart in tableau?

To build a time series chart in Tableau, we will use the built-in Sample Superstore data that comes with the Tableau installation. Please follow the steps outlined below to create a time series chart. Drag the Order Date field to the Columns shelf and the Sales variable to the Rows shelf. The default chart will give us a yearly trend line chart.

What is a a line chart?

A line chart is one of the basic and most commonly used techniques of data visualization. Such graphics are known to provide an informative look at the change of one or several variables over time.


Video Answer


1 Answers

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 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/[email protected]"></script>

Fetch data dynamically:

enter image description here

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!
like image 81
Roko C. Buljan Avatar answered Sep 20 '22 21:09

Roko C. Buljan