caracal
caracal

Reputation: 53

Create chart using JSCharting and data from csv

I'm working on a home project to create a humidity and temperature chart. The project is hosted here: https://github.com/fossler/RPi-Berrybase-DHT22-Sensor

It's my first experience with JS, so I'm a little bit overwhelmed.

I have a csv with the following values:

Date,Time,Temperature,Humidity
05/31/21,17:44,22.6*C,33.3%
05/31/21,17:49,22.4*C,34.0%
05/31/21,17:54,22.2*C,34.4%
05/31/21,17:59,22.4*C,34.3%
05/31/21,18:04,22.5*C,33.7%
05/31/21,18:09,22.6*C,33.4%
05/31/21,18:14,22.7*C,33.3%
05/31/21,18:19,22.7*C,33.1%
05/31/21,18:24,22.7*C,33.0%

I would like to create two charts from type Line Spline Step , one for temperature and one for humidity using JSCharting: https://jscharting.com/tutorials/creating-js-charts/

unfortunately I can't make the code work, I tried something like this:

JSC.fetch("../humidity_and_temp.csv")
  .then(response => response.text())
  .then(text => {
    //Use csv text
  });

let data = JSC.csv2Json("Time,Temperature")

let points = data.map(d => {
  return { x: d.Time, y: d.Temperature };
});

const chart = new JSC.Chart("chartDiv", {
  // Pass points to the series
  series: [{ points: points }],
  // Set the x axis scale to time.
  xAxis_scale_type: "Auto",
  debug: true
});

Any help is valuable.

Upvotes: 0

Views: 425

Answers (1)

Arthur Puszynski
Arthur Puszynski

Reputation: 61

Here's how you can make the chart using your data:

var csv = `Date,Time,Temperature,Humidity
05/31/21,17:44,22.6*C,33.3%
05/31/21,17:49,22.4*C,34.0%
05/31/21,17:54,22.2*C,34.4%
05/31/21,17:59,22.4*C,34.3%
05/31/21,18:04,22.5*C,33.7%
05/31/21,18:09,22.6*C,33.4%
05/31/21,18:14,22.7*C,33.3%
05/31/21,18:19,22.7*C,33.1%
05/31/21,18:24,22.7*C,33.0%`

var jsonData = JSC.csv2Json(csv,{coerce:function(d){
  return {
    Date: new Date(d.Date+' '+d.Time).getTime(),
    Temperature: parseFloat(d.Temperature),
    Humidity: parseFloat(d.Humidity)
  }

}});


var tempPoints = JSC.nest()
  .key('Date')
  .rollup('Temperature')
  .points(jsonData);

var humidityPoints = JSC.nest()
  .key('Date')
  .rollup('Humidity')
  .points(jsonData);

// JS
var chart = JSC.chart("cc", {
  legend:{
    template:'%icon %name'
  },  
  xAxis_scale: {
    type: "time",
  },
  series: [
    {
      name:'Temperature',
      points: tempPoints
    },
     {
       name:'Humidity',
      points: humidityPoints
    }
  ]
});

Live example

Upvotes: 1

Related Questions