动态更新chartJs中的图表

时间:2016-05-04 01:15:32

标签: javascript chart.js

此问题将继续发布此帖Dynamically update values of a chartjs chart和示例http://jsbin.com/yitep/5/edit?html,js,output

我是chartJS的新手,在上面的示例中,它显示了如何动态更新图表数据。但是,任何人都可以帮助我开始使用空白图表,然后动态更新。

注意:在Highcharts中可能与chartJS中的相同。

2 个答案:

答案 0 :(得分:2)

修改 http://www.chartjs.org/docs/

Chartjs库现在是最新且最有用的。使用上面的链接。

我认为你需要做的是下载更新的Chart.Js库,ChartNew.js:https://github.com/FVANCOP/ChartNew.js/。这个更新的库在许多其他改进中具有更新功能,使事情变得更容易。您可以使用上面的链接下载zip文件,找到可以帮助您找出大多数问题的大量示例文件。还有一些非常好的文档:https://github.com/FVANCOP/ChartNew.js/wiki/100.Available_options

我将在上面的库中添加一个完整的示例,您可以将其复制并粘贴到html文件中,以便准确了解如何创建动态图表。只需看看并使用这些示例,直到您开始了解其运作方式。

     <!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>

提供的代码示例直接来自GitHub下载文件夹。它们提供了大量示例来帮助理解文档。

答案 1 :(得分:0)

查看我在jsfiddle中编写的this简单示例。我首先创建了一个条形图,然后使用chart.update()方法每秒对其进行更新。

//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.com/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>

希望这会有所帮助。