Create line chart with chart js - Javascript Chart.js

Javascript examples for Chart.js:Line Chart

Description

Create line chart with chart js

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <title>chart.js time serie</title> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script> 
      <script type="text/javascript">
    window.onload=function(){//  w  w  w .j  ava  2 s . c  o  m
var d = [{
  "price": "49",
  "date": "21\/01\/2018"
}, {
  "price": "30",
  "date": "01\/01\/2018"
}, {
  "price": "32",
  "date": "15\/11\/2017"
}];
function getPreviousMonths() {
    var months = [];
    for (i = 0; i < 12; i++) {
        var month = moment().subtract(i, 'months').format('MMMM Y');
        months.push(month);
    }
    return months.reverse();
}
var dateFormat = 'DD\/MM\/YYYY';
var data = [];
for (var i in d) {
     date = moment(d[i].date, dateFormat);
    data.push({
      t: date.valueOf(),
      y: d[i].price
    });
}
console.log(data)
var ctx = document.getElementById("myChart").getContext("2d");
ctx.canvas.width = 1000;
ctx.canvas.height = 300;
var cfg = {
  type: 'bar',
  data: {
    labels: getPreviousMonths(),
    datasets: [{
      label: "Price trend",
      data: data,
      type: 'line',
      pointRadius: 0,
      fill: false,
      borderColor: 'red',
      lineTension: 0,
      borderWidth: 2
    }]
  },
  options: {
    scales: {
      xAxes: [{
        type: 'time',
        distribution: 'linear',
        ticks: {
          source: 'labels'
        },
        time: {
        unit: 'month',
        unitStepSize: 1,
        displayFormats: {
           'month': 'MMM'
           }
        }
      }],
      yAxes: [{
        scaleLabel: {
          display: true,
          labelString: 'price'
        }
      }]
    }
  }
};
var chart = new Chart(ctx, cfg);
    }

      </script> 
   </head> 
   <body> 
      <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script> 
      <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script> 
      <canvas id="myChart" width="400" height="200"></canvas>  
   </body>
</html>

Related Tutorials