user7596515
user7596515

Reputation:

Show multiple data in a single data in chart.js

I have design a simple graph with chart.js, Which looking cool.

But now i want to show their data between one Month to another Month.

Means their are following data:

1th january, 2017 : 12

3rd January, 2017: 16

And so on..

now i want to show their January to February data as image,which is shown below:

enter image description here

Here is my simple code

    var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
    // The type of chart we want to create
    type: 'line',

    // The data for our dataset
    data: {
        labels: ["January 2017", "February 2017", "March 2017", "April 2017", "May 2017", "June 2017", "July 2017"],
        datasets: [{
            label: "My First dataset",
            backgroundColor: 'rgb(255, 99, 132,0.25)',
            borderColor: 'rgb(255, 99, 132)',
            data: [0, 10, 5, 2, 20, 30, 15],
            lineTension:0
        }]
    },

    // Configuration options go here
    options: {}
});

jsfiddle Here : https://jsfiddle.net/2qxj9t00/2/

I've google so many times but no any solution are their, so kindly suggest me. Thanks :)

Upvotes: 1

Views: 1258

Answers (1)

ɢʀᴜɴᴛ
ɢʀᴜɴᴛ

Reputation: 32879

You can accomplish this using the following x-axis ticks callback function ...

ticks: {
   callback: function(e) {
      var tick = e.match(/(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sept|Oct|Nov|Dec).*?\d+/g)[0];
      if (tick != aR) {
         aR = tick;
         return tick;
      }
   }
}

assuming your labels array would look somewhat like this.. ["1st January 2017", "3rd January 2017", "4th February 2017", ...]

ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ

var aR = null;	//store already returned tick
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
   type: 'line',
   data: {
      labels: ["1st January 2017", "3rd January 2017", "4th February 2017", "9th February 2017", "3rd March 2017", "15th March 2017"],
      datasets: [{
         label: "My First dataset",
         backgroundColor: 'rgba(255, 99, 132, 0.5)',
         borderColor: 'rgb(255, 99, 132)',
         data: [12, 16, 10, 11, 9, 15],
         lineTension: 0
      }]
   },
   options: {
      scales: {
         xAxes: [{
            ticks: {
               autoSkip: false,
               callback: function(e) {
                  var tick = e.match(/(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sept|Oct|Nov|Dec).*?\d+/g)[0];
                  if (tick != aR) {
                     aR = tick;
                     return tick;
                  }
               }
            }
         }],
         yAxes: [{
            ticks: {
               min: 0,
               max: 30
            }
         }]
      }
   }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="myChart" height="200"></canvas>

Upvotes: 1

Related Questions