Creating Dynamic Charts

CanvasJS allows you to create dynamic charts that update at a given interval. Dynamic charts are required when you are displaying data that changes with time like stock price, temperature, etc. Technically, dynamic charts are created the same way as any other chart type except that dataPoints are added/removed at a predefined interval.

All available charts in CanvasJS support dynamic updates including Line Chart, Area Chart, Column Chart etc.

Here are the steps for creating Dynamic Chart.

Step1:

Create a basic chart as usual. But, assign dataPoints to a pre-defined variable (dps in this example)

var dps = [{x: 1, y: 10}, {x: 2, y: 10}, {x: 3, y: 10}, {x: 4, y: 10}, {x: 5, y: 10}];   //dataPoints. 

var chart = new CanvasJS.Chart("chartContainer",{
	title :{
		text: "Live Data"
	},
	axisX: {						
		title: "Axis X Title"
	},
	axisY: {						
		title: "Units"
	},
	data: [{
		type: "line",
		dataPoints : dps
	}]
});

chart.render();

Step2:

Now, we see that values inside dps are being rendered. Now, in order to make the chart dynamic, we just need to change dps array as required and then call chart.render() again.

var xVal = dps.length + 1;
var yVal = 100;	
var updateInterval = 1000;

var updateChart = function () {
	
	
		yVal = yVal +  Math.round(5 + Math.random() *(-5-5));
		dps.push({x: xVal,y: yVal,});
		
		xVal++;
	
	chart.render();		

	// update chart after specified time. 

};
setInterval(function(){updateChart()}, updateInterval); 

In the above code, we are calling updateChart method every second. Each time updateChart adds a new dataPoint and calls chart.render().

Step3:

If you don’t want the dataPoints to keep getting accumulated, you can remove old values from the beginning of the Array as shown below.

if (dps.length >  10 )
{
	dps.shift();				
}

Finalising

To summarize, in order to create live charts, you should update the array containing the dataPoints and call chart.render()
Below is the compilation of final code.

Try it Yourself by Editing the Code below.


If you have any questions, please feel free to ask in our forums.Ask Question

Comments 62

  1. Pingback: CanvasJS Version 1.0.1 GA - CanvasJS

  2. Hi Sunil,

    Using this same technique of:
    var dps = [{x: 1, y: 10}, {x: 2, y: 10}, {x: 3, y: 10}, {x: 4, y: 10}, {x: 5, y: 10}];

    Could you please show where you have 2 data samples?

    For example:
    var dps2 = [{x: 1, y: 12}, {x: 2, y: 22}, {x: 3, y: 34}, {x: 4, y: 45}, {x: 5, y: 60}];

    Even if this static data is merely placed on a line chart as is?

    Thanks,
    Jim

  3. is there any “how-to-sample” that shows how to fetch data from a database to populate a real time chart? These are cool charts application…

  4. can anyone say me how to change height and width canvas (since am using ‘Canvasmin.js’ ) i don know how to change,.. is any know with it .

    • For charts it really doesn’t matter if you are getting data via Ajax or some other method. It just renders the assigned data. So if there is any problem it should be with the data. If you can create a jsfiddle that demonstrates the issue, I can help you with the same.

    • I’ve identified the problem. You are adding array of dataPoints (via push) instead of adding individual dataPoints. Here is a working example http://jsfiddle.net/tPfU3/5/

      I’ve also disabled the animation because there is no time for it to complete the same.

  5. But its adding same data again and again,our list of items are fixed an we only need to update the data…..please see to it as we have to give the project to our client as soon as possible…Or we go for some other source…

    • The previous example that I gave was only meant to demonstrate that the chart can update dynamically. Hence I was adding the same data repeatedly. Here is another jsfiddle that updates a given array. http://jsfiddle.net/tPfU3/8/

      Please use the latest version at your end – v1.3 Beta.

    • Taylor,

      We would like to see the code that you have written so that we can find out what is going wrong. Can you please create a jsfiddle of your code and post it in the forum so that we can have a look?

  6. why is dps.shift() not working? i initialized the chart in window.onload function, and called a generateNewData where new points are generated then after the loop in the function of generate I am calling chart.render() but by adjusting the variables, the generateNewData fetches the right data but the chart is OVERWRITTEN. old values are still in the chart.. :( what do i do?

  7. There is a serious bug that leads to fatal consequences. If the chart, updated over time, add the export menu enabled, then every time you update the chart content, an additional pair of two buttons created. You can check this here: http://jsfiddle.net/MichaelGui/j8yfvpep/1/
    Explanation: see line number 1823 inside Chart.prototype._updateOptions in “canvasjs.js” Here you check the variable: this._exportMenu, but never initialize it after button creation!

  8. Potential memory leak for canvasjs render() function

    tested browser: chrome version: 7.0.2062.120

    When I run following simple code I findd memory usage constantly increased up to 1449712 KB.

    It seems has memory leak in canvasjs_chart.render() because only this function is called repeatedly

    I use following code to do performance test:

    var canvasjs_chart = null;
    var dps = [{x: 1, y: 10}, {x: 2, y: 10}, {x: 3, y: 10}, {x: 4, y: 10}, {x: 5, y: 10}];
    var xVal = dps.length + 1;
    var yVal = 100;

    $(document).ready(function() {
    function test_canvasjs() {
    if(canvasjs_chart == null) {
    //console.log(“create CanvasJS.Chart”);
    canvasjs_chart = new CanvasJS.Chart(“chartContainer”,{
    title :{
    text: “Live Data”
    },
    axisX: {
    title: “Axis X Title”
    },
    axisY: {
    title: “Units”
    },
    data: [{
    type: “line”,
    dataPoints : dps
    }]
    });
    }else {
    //console.log(“update canvasjs chart”);
    while(dps.length > 1200) {
    dps.shift();
    }
    for(var idx = 0;idx < 100; idx++) {
    yVal = yVal + Math.round(5 + Math.random() *(-5-5));
    dps.push({x: xVal,y: yVal,});
    xVal++;
    }
    }
    canvasjs_chart.render();
    }
    var intervalId = setInterval(function() {
    test_canvasjs();
    }, 50);
    }
    });

    • I found when mouse pointer moved to chart a tooltip shown. The memory usage starts increasing after tooltip shown.

  9. I have a question, can I move around the div that contains the chart?

    how can I do this?

    I’ve been trying to move it, the whole chart, and for some reason I´m unable to.

    • Given that chart is rendered inside the its container, moving the container should also move the chart. Please refer to this example.

  10. how can i pause/resume dynamic charts with a button click? I need help :(
    Thank you

  11. is there any example for display the charts on jsp page using database values. same example as you explain in php how I can use it in jsp?

  12. I’m attempting to use a dynamic line graph and I want a time stamp instead of the numbers that appear on the x-axis. However, I would the graph to populate many multiple points per second and only display the time stamp on a per second basis. Is that possible to do?

  13. Hey, I am trying to get the sensor data plotted. The sensor value will the shown on the Y-axis, and on teh X-axis I want to show the time. I get time using the getDateString() function:

    function getDateString() {
    var time = new Date().getTime();
    // 32400000 is (GMT+9 Japan)
    // for your timezone just multiply +/-GMT by 36000000
    var datestr = new Date(time + 19800000).toISOString().replace(/T/, ‘ ‘).replace(/Z/, ”);
    return datestr;
    }

    But, this gives a date string, and I think, not an allowed value of X. What can I do here ?

  14. Hello,

    I would like to know how to use an slider control to change the value of the data showed in the dynamic linechart. Example calculate (yVal = random number), and I try to do (yVal = slider control value), so when I move slider I see change the value in the chart.

    Can anyone explain how to do that?

    Thanks in advance for the answers.

  15. Hi I would like to read the y-axis values from a text file and render chart dynamically (type=”line”), at the end of the y-axis values , it should read from the beginning. Is there any sample for it ??

  16. if i want to give my own dynamic data for example some movies are there i want to rate the movies 10 out of some numbers. for 5 movies i gave rating and get the grand total and draw a chart for this what is the code.

  17. Hi , i have two JS files , one contains ajax call that is fetching data from rabbitmq queue (flask response subsribes to rabbitmq) ,and i need to update canvasjs time-series , the problem is i cannot push data from another file , how this could be solved ? thanks

    • If you change value of sd to number instead of string it should work…

      var sd = 15;

      But updating sd later won’t updated the dataPoint because numbers are passed as value and not as reference.

  18. Hello Canvas Team,

    I am creating a dynamic spline chart, refreshing every 1 sec or 500msec.
    Charts are great, easy to use, & everything works fine so far, except for a little hitch, the chart with refresh, feels like a bit jerky and not smooth.
    Even the chart shown in this page above, gives the same impression.

    CanvasJS charts does everything for us that we need, but this chart refresh smoothness a bit of concern.

    As an example, something like this we want to achieve as end result:
    http://jsfiddle.net/m1erickson/4xMtc/

    I am hoping its possible, but don’t know how?
    So let us know, a) if this is possible & b) how(preferrably an example)

    Thanks,
    Deepak

  19. I have implemented a dynamic chart in my practice project. The issue is with the change of data, the range of Y axis and X axis changes but the graph line remains constant with time. I want to seethe graph line varying with as demonstrated in example.

    X axis represent the current time and it changes every second.
    Y axis represents the CPU Usage, which it receives by the response of the GET request send to the server using JavaScript.

  20. Is there a way to pull data continuously from a database and making a dynamic chart ?
    I am working on something like this and need support for that

    • KANDARP GANDHI,

      For continuously pulling data

      1) You have to use server side technology (like PHP) to keep passing JSON response from database
      2) In the client side apply ajax request in certain interval to receive the JSON
      3) On success update CanvasJS chart data and by calling render chart with show updated result.

      Here is an example to render chart from external JSON via ajax call. And also refer this thread.

  21. I have used this in my app while i get data pushed from server using web sockets, i continuously push data but this some how making the browser freez and slow by pushing CPU usage high

    Can you please suggest if there is something with Canvas which ensure CPU usage is not very high due to frequent chart.render

    • Basavaraj,

      It’s hard to guess the issue without looking into the code. Can you please create a jsfiddle with your client side code and sample JSON, so that we can look into it.

If you have any questions, please feel free to ask in our forums. Ask Question