oceansmoving
oceansmoving

Reputation: 165

CanvasJs - Bar graph visibly not updating properly

I am trying to loop 3 different charts where the data is updated ever so often. The datapoints are updated, the charts are updated, but the bars shows the new and old results simultaneously. enter image description here

I have tried

But nothing works

Code (Have removed Chart 2 and 3 from draw function for readability): Edit: Have updated code to include the ajax and main functions as well. Still simplified and renamed due to confidentiality.

function ajx() {
  Promise.all([
    $.get({
      url: 'file.html',
      cache: false
    }),
     headers: {
        'Cache-Control': 'no-cache, no-store, must-revalidate', 
        'Pragma': 'no-cache', 
        'Expires': '0'
    }
}),
  ]).then(function(results) {
    main(results)
  }).catch(function(err) {
  });
}

var dateArr = [];
var day = {}

var count = 0;

  var dp = [], 
  target = [],
  colors = []

function main(results) {
  var count = 0;

    //Creating array of dates from the source file
  $(results[0]).find('tbody tr').each(function(i, e) {
    var d = $(this).find(':first-child').text();
    if ($.inArray(d, dateArr) == -1) dateArr.push(d);
  });

    // creating/resetting empty date keys
  for (i = 0; i < dateArr.length; i++) {
    day[i] = {
      date: 0,
      value1: 0,
      value2: 0,
      result: 0
    }
  }

  $(results[0]).find('tbody tr').each(function() {
    var d = $(this).find(':first-child').text();

    //Calculating the results and splitting them by date
    for (i = 0; i < dateArr.length; i++) {
      if (dateArr[i] == d) {
        day[i].date = d;
        day[i].value1 += parseInt($(this).find(':nth-child(3)').text());
        for (x = 4; x < 6; x++) {
          day[i].value2 += parseInt($(this).find(':nth-child(' + x + ')').text());
        }
      }
      day[i].result = parseInt(((day[i].value2 / day[i].value1) * 100).toFixed(2));
    }
  });

    //Populating the data points
    for (i = 0; i < dateArr.length; i++) {
    dp.push({
      x: new Date(day[i].date),
      y: day[i].result
    })

    //Targets
    target.push({
      x: new Date(day[i].date),
      y: 80
    })

    //Colors
    if (day[i].result < 80) {
      colors.push('red')
    } else {
      colors.push('green')
    }
  }

  CanvasJS.addColorSet("colors", colors);
    setTimeout(ajx, 30000)
}

function drawGraph(x, y) {

  if(y == 1) {
  var x = new CanvasJS.Chart("chartContainer", {
    colorSet: "colors",
    animationEnabled: true,
    backgroundColor: "rgba(163,121,143,0)",
    title: {
      text: ""
    },
    axisX: {
      interval: 1,
      intervalType: "day",
      valueFormatString: "MMM DD"
    },
    axisY: {
      stripLines: [{
        value: 80,
        showOnTop: true,
        lineDashType: "dash",
        color: "rgb(51,51,51)",
        thickness: 2
      }],
      includeZero: false,
      suffix: " %"
    },
    legend: {
      cursor: "pointer",
      fontSize: 16
    },
    toolTip: {
      shared: true
    },
    data: [{
      name: "",
      type: "column",
      percentFormatString: "#0.##",
      dataPoints: dp
    }]
  });
    x.render();
    x.destroy();
    x = null;
    }
}



  idx = {
    chartArr: ['chart1', 'chart2', 'chart3']
  }

    //To loop the 3 charts
  function countdown() {
      count++;
      if (count == 1) {
        drawGraph(idx.chartArr[0], count)
      }
      if (count == 2) {
        drawGraph(idx.chartArr[1], count)

      }
      if (count == 3) {
        drawGraph(idx.chartArr[2], count)
      }
      if (count == 3) {
        count = 0;
      }
        setTimeout(countdown, 10000)
  }


ajx();
countdown();

Upvotes: 0

Views: 195

Answers (1)

Sanjoy
Sanjoy

Reputation: 505

The code that you have shared seems to be working fine, after adding sample-data (dp). Please share sample-data along with the code, if you still have any issue!

  1. Initial data-points
  2. Updated data-points

var dp = [
  { x: new Date(2018, 0, 1), y: 71 },
  { x: new Date(2018, 0, 2), y: 55 },
  { x: new Date(2018, 0, 3), y: 50 },
  { x: new Date(2018, 0, 4), y: 65 },
  { x: new Date(2018, 0, 5), y: 95 },
  { x: new Date(2018, 0, 6), y: 68 },
  { x: new Date(2018, 0, 7), y: 28 },
  { x: new Date(2018, 0, 8), y: 34 },
  { x: new Date(2018, 0, 9), y: 14 }
];


function drawGraph(x, y) {

    $('#charts #chartContainer').remove();
    $('#charts').append('<div id="chartContainer" class="chrt" style="visibility: visible;"></div>');

  if(y == 1) {
  var x = new CanvasJS.Chart("chartContainer", {
    colorSet: "colors",
    animationEnabled: true,
    backgroundColor: "rgba(163,121,143,0)",
    title: {
      text: ""
    },
    axisX: {
      interval: 1,
      intervalType: "day",
      valueFormatString: "MMM DD"
    },
    axisY: {
      stripLines: [{
        value: 80,
        showOnTop: true,
        lineDashType: "dash",
        color: "rgb(51,51,51)",
        thickness: 2
      }],
      includeZero: false,
      suffix: " %"
    },
    legend: {
      cursor: "pointer",
      fontSize: 16
    },
    toolTip: {
      shared: true
    },
    data: [{
      name: "",
      type: "column",
      percentFormatString: "#0.##",
      dataPoints: dp
    }]
  });
    x.render();
    x.destroy();
    x = null;
    }
}

var idx = {
    chartArr: ['chart1', 'chart2', 'chart3']
  }
  
var count = 0;
countdown();

  function countdown() {
      count++;

      if (count == 1) {
        drawGraph(idx.chartArr[0], count)
      }
      if (count == 2) {
        drawGraph(idx.chartArr[1], count)

      }
      if (count == 3) {
        drawGraph(idx.chartArr[2], count)
      }

      if (count == 3) {
        count = 0;
      }
      
     for(var i = 0; i < dp.length; i++){
      dp[i]. y = Math.random() * 100;
     }
        setTimeout(countdown, 10000)
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>

<div id="charts"></div>

Upvotes: 2

Related Questions