MTBthePRO
MTBthePRO

Reputation: 520

Chart js animating a line while changing x-axis labels


I achieved animating a plot using Jukka Kurkela example here.
Now I am having trouble customizing this plot further.

Logic of the custom plot
The plot starts animating with the x-axis labels being 0-20. When the plot reaches 20 then update the x-axis to be 20-40. Increment i or 20 until the x-axis reach its limit.

How to apply the logic above to the Example below?

    // Generating data
    var data = [];
    var prev = 100;
    for (var i=0;i<200;i++) {
      prev += 5 - Math.random()*10;
      data.push({x: i, y: prev});
    }

    var delayBetweenPoints = 100;
    var started = {};
    var ctx2 = document.getElementById("chart2").getContext("2d");
    var chart2 = new Chart(ctx2, {
      type: "line",
      data: {
        datasets: [
          {
            backgroundColor: "transparent",
            borderColor: "rgb(255, 99, 132)",
            borderWidth: 1,
            pointRadius: 0,
            data: data,
            fill: true,
            animation: (context) => {
              var delay = 0;
              var index = context.dataIndex;
              if (!started[index]) {
                delay = index * delayBetweenPoints;
                started[index] = true;
              }
              var {x,y} = index > 0 ? context.chart.getDatasetMeta(0).data[index-1].getProps(['x','y'], 
               true) : {x: 0, y: 100};
              
              return {
                x: {
                  easing: "linear",
                  duration: delayBetweenPoints,
                  from: x,
                  delay
                },
                y: {
                  easing: "linear",
                  duration: delayBetweenPoints * 500,
                  from: y,
                  delay
                },
                skip: {
                  type: 'boolean',
                  duration: delayBetweenPoints,
                  from: true,
                  to: false,
                  delay: delay
                }
              };
            }
          }
        ]
      },
      options: {
        scales: {
          x: {
            type: 'linear'
          }
        }
      }
    });
    <div class="chart">
      <canvas id="chart2"></canvas>
    </div>
    <script src="https://www.chartjs.org/dist/master/Chart.js"></script>

Upvotes: 1

Views: 795

Answers (1)

MTBthePRO
MTBthePRO

Reputation: 520

Solved it! Instead of incrementing 20 seconds, it is incrementing every 5 seconds ahead of time. Definitely a better experience for the user.

Got help from Rowf Abd's post.

 
  var myData = [];
  var prev = 100;
  for (var i=0;i<60;i++) {
    prev += 5 - Math.random()*10;
    myData.push({x: i, y: prev});
  }

  var ctx = document.getElementById('myChart').getContext('2d');

  var chart = new Chart(ctx, {
    type: 'line',
    data: {
      datasets: [{
        data: [myData[0]],
        pointRadius: 0,
        fill: false,
        borderColor: "black",
        lineTension: 0
      }]
    },
    options: {
      legend: {
        onClick: (e) => e.stopPropagation() 
      },
      title:{
        fontColor: 'Black'
      },
      layout: {
        padding: {
            right: 10
        }
      },
      scales: {
        xAxes: [{
          type: 'linear',
          ticks: {
          }
        }],
        yAxes: [{
          scaleLabel: {
            // fontFamily: 'Lato',
            fontSize: 19,
            fontColor: "Black"
          }
        }]
       }
    }
  });
  

  var next = function() {
    var data = chart.data.datasets[0].data;
    var count = data.length;
    var xabsmin = 20;
    var xabsmax = 60;
    var incVar = 5;

    data[count] = data[count - 1];
    chart.update({duration: 0});
    data[count] = myData[count];
    chart.update();

    if (count < myData.length - 1) {
      setTimeout(next, 500);
    }
    
    if (data[count].x < xabsmin) {
      
      chart.config.options.scales.xAxes[0].ticks.min = xabsmin - xabsmin;
      chart.config.options.scales.xAxes[0].ticks.max = xabsmin;
      chart.update();

    }
    
    if(data[count].x >= xabsmin && data[count].x < (xabsmax)){
      
      var currentT = parseFloat(data[count].x);
      var modDiv = (currentT % incVar);
      var tempXMax = (currentT) + (incVar - modDiv);

      chart.config.options.scales.xAxes[0].ticks.max = tempXMax;
      chart.config.options.scales.xAxes[0].ticks.min = tempXMax - xabsmin;
      chart.update();

    }
  }

  setTimeout(next, 500);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>

<canvas id="myChart"></canvas>

Upvotes: 3

Related Questions