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.
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();
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().
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(); }
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.
62 Comments
Pingback: CanvasJS Version 1.0.1 GA - CanvasJS
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
Multi-Series Charts are explained in the Getting Started Section
https://canvasjs.com/docs/charts/basics-of-creating-html5-chart/
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…
jun,
Here is a sample available in the forum:
https://canvasjs.com/forums/topic/how-can-i-use-php-mysql-dynamic-data/
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 .
Pie is not working with ajax
https://canvasjs.com/docs/charts/chart-types/html5-pie-chart/
showing Uncaught TypeError: Cannot read property ‘currentlyExploded’ of undefined
in the browser console
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.
In beta it is creating data points like them
http://jsfiddle.net/tPfU3/4/
in v2.0
it is not rendering anything, only it is give me the above error
We are waiting for you reply, so tll me as soon as possible…Karamjeet
thanx for your reply..
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.
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.
Hi,
I dont want the x-axis and y-axis points to be displayed….only just the graph itself.
how can i do that?
You can do so by setting valueFormatString to empty string. Here is an example.
How do we get this to work with bar charts?
I can’t get chart.render90 to rerender anything with variables that are updating
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?
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?
Hi,
Can you please create a jsFiddle so that we can look into your code. Its hard to guess the issue without seeing your code.
I’ll rephrase my question. What if the updateChart function is outside the window.onload? how can i implement that? Thank you
Vianece,
In that case you can keep a reference to the chart outside onload method.
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!
Here you can see, what I mean: http://funkyimg.com/i/RBmb.png
Michael,
Thank you very much reporting. I’ve just fixed the issue. Please download the latest version from here and confirm if it is working fine at your end.
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.
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.
how can i pause/resume dynamic charts with a button click? I need help :(
Thank you
Use clearInterval(var) –> http://www.w3schools.com/jsref/met_win_clearinterval.asp
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?
Hola quiero mostrar datos desde mi base de datos mysql, ya que estoy trabajando con LARAVEL ?? TIENEN ALGUN EJM
Please refer to this thread.
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?
I figured out my own problem
how can i use dynamic chart with database ? if i use chart with doughnut chart ? please answer
Please refer to the following links which might be of help.
– To get chart data from Database.
– To update chart dynamically.
Can I use String values in X axis??.
You can use label for the same.
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 ?
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.
Can you query a MySQL database and get your values??
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 ??
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.
Here is an example for dynamic realtime chart.
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
how insert var in this data
var sd = “15”;
var dps = [{x: +sd+ , y: 15}, {x: 2, y: 10}, {x: 3, y: 10}, {x: 4, y: 10}, {x: 5, y: 10}];
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.
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
Any samples to include 2 charts in a page ?
Durai,
Here is an example.
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.
Prakash,
It would help us to check the issue if you can create a fiddle.
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.
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.
What shift() function do in the canvas?
JavaScript shift() method removes the first element from an array and returns that element. Please refer this documentation.
Hello,
I’d like to give the possibility to choose time period (Like show the graph since 1 year, since 2 years…). But I can’t figure how can I do to do that..
Is there any method ?
Are you looking for viewportMinimum