最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Dynamically update chart in chartJs - Stack Overflow

programmeradmin0浏览0评论

This question is in continuation of this post Dynamically update values of a chartjs chart and the example ,js,output

I am new to chartJS, in the above example it is shown how to update dynamically chart data. But, can any one help me with how to start with a blank chart and then update dynamically.

Note: It is possible in Highcharts, is the same possible in chartJS.

This question is in continuation of this post Dynamically update values of a chartjs chart and the example http://jsbin./yitep/5/edit?html,js,output

I am new to chartJS, in the above example it is shown how to update dynamically chart data. But, can any one help me with how to start with a blank chart and then update dynamically.

Note: It is possible in Highcharts, is the same possible in chartJS.

Share Improve this question edited May 23, 2017 at 11:53 CommunityBot 11 silver badge asked May 4, 2016 at 1:15 RoyRoy 5332 gold badges8 silver badges21 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

EDIT http://www.chartjs/docs/

The chartjs library is now the most updated and useful. Use the link above.

I think what you need to do is download the updated Chart.Js library, ChartNew.js at: https://github./FVANCOP/ChartNew.js/ . This updated library has an update function among many other improvements that make things much easier. You can download the zip file using the link above and find tons great example files that will help you figure out most issues. There is also some pretty good documentation at: https://github./FVANCOP/ChartNew.js/wiki/100.Available_options .

I will add a full example from the above library that you can copy and paste into an html file in order to see exactly how you can create a dynamic chart. Just take a look and play around with the examples until you start to see how things work.

     <!doctype html>

<!--[if lte IE 8]><SCRIPT src='source/excanvas.js'></script><![endif]--><SCRIPT src='../ChartNew.js'></script>
<SCRIPT src='../Add-ins/format.js'></script>

<SCRIPT>

function setColor(area,data,config,i,j,animPct,value)
{
  if(value > 35)return("rgba(220,0,0,"+animPct);
  else return("rgba(0,220,0,"+animPct);

}

var charJSPersonnalDefaultOptions = { decimalSeparator : "," , thousandSeparator : ".", roundNumber : "none", graphTitleFontSize: 2 };

defCanvasWidth=600;
defCanvasHeight=300;





var mydata = {
    labels : [],
    datasets : [
        {
            fillColor : "rgba(220,220,220,0.5)",
            strokeColor : "rgba(220,220,220,1)",
            pointColor : "rgba(220,220,220,1)",
            pointstrokeColor : "yellow",
            xPos : [],
            data : [],
                title : "2014"
        }
    ]
}               

var startWithDataset =1;
var startWithData =1;

var opt = {
      animationStartWithDataset : startWithDataset,
      animationStartWithData : startWithData,
      animation : true,
      animationLeftToRight : true,
      animationSteps : 20,
      animationEasing: "linear",
      canvasBorders : true,
      canvasBordersWidth : 3,
      canvasBordersColor : "black",
      graphTitle : "animation With Update",
      legend : true,
//      inGraphDataShow : true,
      annotateDisplay : true,
      onAnimationComplete : startUpdate,
      graphTitleFontSize: 18, 
    responsive : true,
    scaleOverride: true,
    scaleSteps: 10,
    scaleStepWidth: 10,
    scaleStartValue: 0,
    fmtXLabel : "fmttime hh:mm:ss",
    animationCount: 1,
    animationPauseTime : 0,
    animationBackward: true


};


function startUpdate(ctx, config, data, tp, count) {
    setTimeout(function (){updt(ctx,data,config);}, 1000+Math.random()*500);
//  setTimeout(function (){updt(ctx,data,config);}, 1000);
};


function updt(ctx,data,config) {
    updtData(data);
        config.animationSteps = 50*data.datasets[0].xPos.length;
    config.animationStartValue=1-(2/data.datasets[0].xPos.length);
    deleteHighLight(ctx,data);
    updateChart(ctx,data,config,true,true);
}

function updtData(data) {
    var i;

    var t=new Date();

    var coeff = 1000 ;
    var rounded = new Date(Math.round(t.getTime() / coeff) * coeff + coeff);

    for(i=0;i<10;i++)
    {
        var t2 = new Date(rounded - (18-2*i) * 1000);
        data.labels[i]=t2;
    } 

    data.xBegin=data.labels[0];
    data.xEnd=data.labels[9];


    data.datasets[0].xPos[data.datasets[0].xPos.length]=t;
    vl=Math.random()*100;
    data.datasets[0].data[data.datasets[0].data.length]=vl;



    // remove data outside first time;
    while(data.datasets[0].xPos[0]<data.labels[0]) {
        data.datasets[0].xPos.splice(0,1);
        data.datasets[0].data.splice(0,1);
    }


}

updtData(mydata);
updtData(mydata);
updtData(mydata);
mydata.datasets[0].xPos[0]=new Date(mydata.datasets[0].xPos[0]-2000);
mydata.datasets[0].xPos[1]=new Date(mydata.datasets[0].xPos[1]-1000);

</SCRIPT>


<html>
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
    <head>
        <title>Demo ChartNew.js</title>
    </head>
    <body>

  <center>
    <FONT SIZE=6><B>Demo of ChartNew.js !</B></FONT>    <BR>

    <script>

    document.write("<canvas id=\"canvas_Line\" height=\""+defCanvasHeight+"\" width=\""+defCanvasWidth+"\"></canvas>");
window.onload = function() {
    var myLine = new Chart(document.getElementById("canvas_Line").getContext("2d")).Line(mydata,opt);

 }
    </script>
  </body>
</html>

The provided code example is taken directly from the GitHub download folder. They provide a great deal of examples to help make sense of the the documentation.

Check out this simple example I wrote in jsfiddle. I first created a bar chart and then used chart.update()method to update it in every second.

//value for x-axis
var emotions = ["calm", "happy", "angry", "disgust"];

//colours for each bar
var colouarray = ['red', 'green', 'yellow', 'blue'];

//Let's initialData[] be the initial data set
var initialData = [0.1, 0.4, 0.3, 0.6];

//Let's updatedDataSet[] be the array to hold the upadted data set with every update call
var updatedDataSet;

/*Creating the bar chart*/
var ctx = document.getElementById("barChart");
var barChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: emotions,
    datasets: [{
      backgroundColor: colouarray,
      label: 'Prediction',
      data: initialData
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true,
          min: 0,
          max: 1,
          stepSize: 0.5,
        }
      }]
    }
  }
});

/*Function to update the bar chart*/
function updateBarGraph(chart, label, color, data) {
  chart.data.datasets.pop();
  chart.data.datasets.push({
    label: label,
    backgroundColor: color,
    data: data
  });
  chart.update();
}

/*Updating the bar chart with updated data in every second. */
setInterval(function() {
  updatedDataSet = [Math.random(), Math.random(), Math.random(), Math.random()];
  updateBarGraph(barChart, 'Prediction', colouarray, updatedDataSet);
}, 1000);
<html>

<head>
  <script src="https://cdnjs.cloudflare./ajax/libs/Chart.js/2.3.0/Chart.min.js"></script>

  <body>
    <div>
      <h1>Update Bar Chart</h1>
      <canvas id="barChart" width="800" height="450"></canvas>
    </div>
    <script src="barchart.js"></script>
  </body>
</head>

</html>

Hope this helps.

发布评论

评论列表(0)

  1. 暂无评论