This tutorial will help you get started with CanvasJS JavaScript Charting Library using basic JavaScript & HTML. Each section explains some Chart concept along with a live editor where you can practice by editing code. We encourage you to edit the code as described in the comments (inside editor) & familiarize yourself with the Charting API.
Ready to create your first chart locally on your system using CanvasJS ?
The above code template can be used to create various types of charts. Follow the steps below to get started.
So easy, right?!
Next Step: Go through the tutorial below to start building incredibly high performance charts easily using CanvasJS. It teaches you the basics of creating HTML5 Javascript Charts with the help of interactive samples.
Consider the following tabular data to be rendered in the form of column chart.
Fruit | Sales in first Quarter (thousand dollars) |
---|---|
Banana | 18 |
Orange | 29 |
Apple | 40 |
Mango | 34 |
Grape | 24 |
Below is how a minimal basic Column Chart would look like. Here are important things to remember
Chart “options” mainly contains 4 important elements.
Checkout the code below – experiment and make yourself familiar with the API.
NoteThough we are going to use Column Charts to learn various concepts, it is easy to change them into any kind of chart that you wish! Just change the type property of dataSeries to any chart type that you need – bar, area, line, scatter, stackedColum, etc.
Checkout all the supported chart types
Now, if you want to compare sales of various fruits in first and second quarter of the year, you need to add one more dataSeries (with second quarter values) to the data array. Below is how it can be done.
Fruit | Sales in first Quarter (thousand dollars) |
Sales in second Quarter (thousand dollars) |
---|---|---|
Banana | 58 | 63 |
Orange | 69 | 73 |
Apple | 80 | 88 |
Mango | 74 | 77 |
Grape | 64 | 60 |
In the above chart we can do couple of customization to improve the visualization of data like
Adding Prefix & Suffix to values is quite simple. You can do so by adding axisY object with prefix and suffix properties set.
Legend can be displayed by setting showInLegend property in dataSeries to true
Below is how it would look like with above properties set. Intentionally the Title has not been set in Axis X and Axis Y. You can do so by setting the title property of axisY or axisX objects.
CanvasJS comes with built in themes that change the look and feel of charts – like “light1”, “light2”, “dark1”, “dark2”.
You change theme by setting theme property of chart option to any of the available themes. Below is an example
Above examples show how you can pass data to the constructor while instantiating a chart object. But you can also set these options after creating the object – sometimes it is easier this way.
Options object that you pass to the constructor in the above method can be accessed via options property of chart. Using the same object you can set or update various properties of chart as below.
chart.options.title.text = "Chart Title"; chart.options.data = [array]; chart.options.data[0] = {object}; chart.options.data[0].dataPoints = [array];
In case you have to do any more customization, below is a table that lists important objects and properties that allow you to do so. Do try out all these options on the above chart.
Customization | Object | Property |
---|---|---|
Set Chart Title Size | title | fontSize – 12,13,14, etc. |
Set Chart Title Color | title | fontColor – red, blue, green, etc |
Show Axis Y line | axisY | lineThickness – 0, 1, 2, etc. |
Show value (indexLabels) on top of Column / Bar |
dataSeries | indexLabel – “{y}”, “${y}K”, “any text” |
Set Axis X label angle | axisX | labelAngle – 30, 45, 90, etc |
172 Comments
Hi Team,
Many congratulation on achieving this milestone. My query is, how can I load data or provide the input values for graph from a JSON object or a XML file because I will never like to create an array of data and when i speak about data I am referring to many many (dynamic) values generated on various calculation based on my metrics dashboard formulas.
Regards,
Rahul Khanna
Rahul,
Thank you very much… CanvasJS takes data in the form of JSON only. You basically need to transform your JSON data into a format supported by CanvasJS. Here is an example where we generate random data in a loop and assign it to the chart. Look at this example.
https://canvasjs.com/docs/charts/basics-of-creating-html5-chart/zooming-panning/
Pingback: Beautiful HTML5 Charts
There does not exist method able to modify the attributes
Boris,
You can modify the attributes by using chart’s options property as below:
chart.options.axisY.maximum = 150;
chart.options.data[0].color = “red”;
Thank you for your reply. Where I can see all the possible methods to use?
Chart Options section contains all the supported properties.
https://canvasjs.com/docs/charts/chart-options/
Hi, can I change labels on the donut into links?
It is not possible to change the label itself into links. But you can use click event of dataPoint to take user to the corresponding page when clicked.
In that case you might also want to use “cursor” property of dataSeries/dataPoint to change mouse pointer type.
My requirement is the same as Rahul Khanna, want to see an example that reads a JSON file and the values are plotted. thanks
As of now CanvasJS doesn’t have a way to directly plot from the data inside a file. As such you need to read those values and assign the same to the chart.
Is possible to connect them to an access database
CanvasJS is just a rendering library that draws charts on the client side. Hence you will have to write server side code to connect with any database and use CanvasJS on the client side and it’ll work fine.
In the code I attached the problem is that column 1 and column 3 is not plotted. As if the value of these variables are not considered numeric by CANVASJS. For that reason handle it like this:
stnetomax var = parseFloat (VPSs [6]);
but it did not work
I would appreciate your help.
MY CODE
window.onload = function() {
///////////////////////////////////////////////////
CODE……………………………………….
…………………………………………..
var psañomax = vpss[1];
var strecibomax = parseFloat(vpss[2]);
var stimportemax = parseFloat(vpss[3]);
var stimpmax = parseFloat(vpss[4]);
var stbonmax = 12385583;
var stnetomax = parseFloat(vpss[6]);
//////////////////////////////////////////////
var chart = new CanvasJS.Chart(“chartContainer”, {
title: {
text: “Concepto:” + psconnom + ” ” + psconnum // SHOW OK
},
data: [
{
type: “column”,
name: “Año Mayor ” + psañomax, // SHOW OK
showInLegend: true,
dataPoints: [
{ label: “Columna 1 “, y: stimpmax }, // NO SHOW << Here is the problem
{ label: "Columna 2 ", y: stbonmax }, // SHOW OK
{ label: "Columna 3 ", y: stnetomax },// NO SHOW << Here is the problem
{ label: "Columna 4 ", y: 101558923 } // SHOW OK
]
},
I discovered that I had an error.
In my code in the object chart I have several DataSeries and only the first DataSeries variables was turning to float with parseFloat. Replace all variables with parseFloat and work.
It works and looks good!!.
Chart requires x & y values to be numbers – enclosing them in quotes creates prolems while doing calculations internally. Glad you figured it out.
How this works in IE! do you have any documentation on that!
It uses excanvas as a fallback on IE8-
https://canvasjs.com/blog/08/22/canvasjs-javascript-chart-v1-3-is-retina-ready-and-supports-ie8/
hey sunil,
when is 1.3 release going to be out of beta?
It should be out of beta within a week.
Hi Sunil.
Newbie perspective here for an already great tutorial. The following sentences need to be described (also) in plain English:
“Above examples show how you can pass data to the constructor while instantiating a chart object. But you can also set these options after creating the object – sometimes it is easier this way. Options object that you pass to the constructor in the above method can be accessed via options property of chart. Using the same object you can set or update various properties of chart as below.”
What is a constructor?… What is the benefit of the one approach vs the other?… the “easier this way” part?… Easier in what regard?
Keep up the great work!
Bowo
can you please demonstrate an example of same chart by using dynamic data through .net, sql server?
Thanks in advance
Pingback: CanvasJS Charts v1.3 goes GA
Hi is possible change width of existing chart? Do you plan to add some option like conditionaly hide legend depending on width? Parent container follows resize event so i can simply set width/height option.
How do I show values INSIDE the bar charts or UNDER the labels?
You can use indexLabel property of dataPoints with indexLabelPlacement set to “inside”
https://canvasjs.com/docs/charts/basics-of-creating-html5-chart/labels-index-labels/
I pasted the HTML code and tried to open the file in my browser…But the chart is not displayed on the Browser.
Do I have to make any changes to the code to run in Chrome
Thanks
Manoj Shetty
The canvas.min.js path was wrong. Its working now
Thanks
Can i get different color each time i reload the chart
Sanjeev,
Your question has already been answered here.
the live control edit work brilliantly..
Thank you… :)
Hey – this looks great. Could you put the initial code somewhere else than in between the tags?
For example, if I wanted to create a chart within a blog post I may not have access to the , could I put all the code I need within the post itself?
Thanks!
Sorry, I meant head tags
Pingback: AngularJS Charts with CanvasJS | Matt Smith Blog
Mine is basic question how can i run file normally means where to save file with what extension and what libraries i’ll need for execution?
Prajakta,
Please refer to installation section for the same.
I was unable to give a json format like [{“label”:”First”,”y”:”12″},{“label”:”Second”,”y”:”1″}] in column chart is that a bug or anywere i made mistake in formatting the JSON. But with the same format i can plot pie and doughnut charts. Help me with the issue. Thanking you.
Vishnu,
y value should be a number and not a string. So your json should look like this [{“label”:”First”,”y”:12},{“label”:”Second”,”y”:1}].
Pingback: CanvasJS – jQuery Charts Plugin | Js Plugins
Hi, Do you have any plan to add mouse interaction feature?
I hope that callback function is called or event triggered with series name and y-axis value when user click on bar or line of chart.
Changkyun,
Please refer this example and for more please refer dataSeries, dataPoints and legend mouse interaction features.
Hi Sir,
We are Developing Our Project. we are Choose canvasjs. Some specification’s are very must for use canvasjs.We want to have using canvasjs spline type chart how to put dynamic data from sql server database on normal Asp.net C# and in display Mouse Cursor point will be shown in any area in the chart ist Possible to show?
We are waiting for more the 20 more days to database connectivity for Normal Asp.net C# Did not get any reference from any Site Please Help Us……
Hi,
we are trying to draw line graphs.They are working fine for Chrome and Safari But IE and Mozilla always render in lines in black color.
Can you please create a jsfiddle with your code so that we can have a look?
I am trying to have mutiple bar on a chart via database to JSON
$row[‘month’] , “y” => $row[‘2012’]);
array_push($data_points1, $point);
}
$result2 = mysqlI_query($con, “SELECT * FROM GRAPHA”);
while($row = mysqlI_fetch_array($result2))
{
$point = array(“label” => $row[‘month’] , “y” => $row[‘2013’]);
array_push($data_points2, $point);
}
$data_points=array();
array_push($data_points,$data_points2);
array_push($data_points,$data_points1);
echo json_encode($data_points, JSON_NUMERIC_CHECK);
}
mysqli_close($con);
?>
but it never shows two bars differently
$(document).ready(function () {
$.getJSON(“data.php”, function (result) {
var chart = new CanvasJS.Chart(“chartContainer”, {
title: { text: “GRAPH A” },
data: [
{
dataPoints: result
},
{
dataPoints: result
}
]
});
chart.render();
});
});
Pls advise.
This forum thread might be of help.
great, it is working. begin to understand how to have mutiple bar combo on one chart.
i am using this to retrieve data from plain csv.
$file=”data.csv”;
$csv= file_get_contents($file);
$array = array_map(“str_getcsv”, explode(“\n”, $csv));
print json_encode($array);
Noticed the output of JSON is correct. How do I have it imported / pass the info the
$(document).ready(function () {
$.getJSON(“data.php”, function (result) {
var chart = new CanvasJS.Chart(“chartContainer”, {
axisX: { suffix: ” mth”, },
axisY: { title: “Sales”, },
axisY2:{ suffix: ” %”, },
title: { text: “Test” },
data: [
{
type:”column”,
toolTipContent: “2013 : {y}”,
dataPoints: result[0],
},
{
type:”column”,
toolTipContent: “2014 : {y}”,
dataPoints: result[1],
},
{
axisYType: “secondary”,
type:”line”,
toolTipContent: “2013 calc : {y}”,
dataPoints: result[2],
},
{
axisYType: “secondary”,
type:”line”,
toolTipContent: “2014 calc : {y}”,
dataPoints: result[3],
}
]
});
chart.render();
});
});
Is there a simpler workaround ?
nracer,
Can you please post your JSON data.
[[1,329,793,1121],[2,378,712,787],[3,646,883,984],[4,800,821,878],[5,797,636,927],[6,836,702,902],[7,814,588,731],[8,850,522,782],[9,934,665,523],[10,1010,683,0],[11,863,1049,0],[12,439,657,0],[null]]
nracer,
You just need to parse the JSON data and convert it to the CanvasJS supported format. Below is how you can do it:
$(document).ready(function () {
var dataPoints = [];
var dataPoints1 = [];
var dataPoints2 = [];
$.getJSON(“jsonData.json”, function (data) {
for (var i = 0; i <= data.length - 1; i++) { for( var j = 0; j < data[i].length-1; j++){ dataPoints.push( { x: data[i][0], y: data[i][1]}); dataPoints1.push({ x: data[i][0], y: data[i][2]}); dataPoints2.push({ x: data[i][0], y: data[i][3]}); } } chart = new CanvasJS.Chart("chartContainer",{ axisX: { interval: 1 }, data: [ { type: "column", dataPoints : dataPoints }, { type: "column", dataPoints : dataPoints1 }, { type: "column", dataPoints : dataPoints2 } ] }); chart.render(); }); });
I want to set max level upto 100, The maximum line not below or more than 100 . eg I want to seen % of mark of an student. Which max level 100 and each level of 10 increase value.
100
90
80
70
60
..
..
0
If student have 100% then one more line add in graph which i dont want (150) ..Please help me on that .
purusottama,
Please use the maximum property and set it to 100 and by using interval property you can make every level increased by 10.
how can i resize the graph according to screen dimentions?
can we read a local file as our data? how?
daixtr,
Please refer to this article on reading local files. After reading the file, create option object for CanvasJS and assign the same.
I have been working with canvas js recently , its really good plugin , saves a lot of time ,
i wanted to know if in pie chart , when i place the index labels outside , can i change the length of those
line connectors that connects indexlabels to its equivalent area on the on the circle ?
keyur,
Length of indexLabelLine are automatically calculated and cannot be customized.
but there must be a way to fix them ,to give them static lengths ,isn’t it ?
Can u help me? I want to fetch data from database through ajax and want to set ajax response into dataPoints. and i get ajax response in json format but how i can set this respone into dataPonts?
devendra,
Please refer this thread.
Thank you so much Anjali :)
How to use for loop with in data or datapoints?
I am getting data dynamically from C# using json, how to push all values to datapoints?
I am using asp.net mvc 4.
mohan,
Please refer this thread.
How is it possible to swap the location of the axis?
chris,
It is possible only with bar chart.
Hi… I want to get the value from database and display it through graph, how can i do that using canvasjs?
umair,
Please refer this thread.
Pingback: Еще одна библиотека построения графиков на JavaScript | ENUT
how to make the realtime plot happen from left to right instead of right to left ?
Do you also want the x axis to be reversed? Also please create a jsfiddle with your data so that we can have a look.
how we add n rexords in datapoints in scatter chart..plz help
ranjan,
Please refer this example.
Can we provide datatable as in Excel using canvasJS?
pavan,
CanvasJS does not support importing or exporting data in excel format. You’ll have to do the conversion to and from CanvasJS format.
Hello, i am unable to get this property ‘animationEnabled: true’ for chart type= ‘
column’
To be specific, In IE, animationEnabled is working for column chart and not for dougnut chart, likewise, In Firefox, animationEnabled is working for doughnut chart but not for column chart.
yaseen,
We are not able to reproduce the issue. Can you please create a jsfiddle so that we can have a look? Also do mention your browser versions.
Hello Dear, Could you please let me know how to disable bubbles on the mousehover!? and also how to disable labels!? Thanks a lot
mahpari,
Do you mean to say toolTip(bubbles)? If yes, you can do the same by setting enabled property of toolTip to false. You can disable labels by setting valueFormatString to ” ” as shown in this example – make sure that dataPoints don’t have label property assigned.
Hello Dear, Thanks a lot for your response.
I tried these:
toolTip:false,
valueFormatString : “”,
but it didn’t solve it.
I want to disable those small rectangles that appear when we do mouseover on the chart.
Thanks for any quick response!
Can you please create a jsfiddle so that we can have a look ?
How can we dynamically change number of datapoint under data section. i want to add or remove based on JSON data i am passing.
Hi,
I have a csv file like below in my local directory.
Jan,20
feb,30
mar,40
apr,50
Please send me the working code for the displaying the above local file into a chart.
Thanks
MAnoj
manoj,
Please refer to this thread.
Hi Anjai, that did not work for me…. I have the sample.txt as per the thread and logg.csv in my linux /home/users/ directory… and this html i am just giving it int the browser….
Hi CanvasJSTeam!
I have a question, can I draw a line over a bar chart using canvasjs? I require this feature to implement a chart showing the Confidence Interval as shown in this diagram: https://ibis.health.state.nm.us/image/resources/BarGraphwithCIs.gif
Will really appreciate your guidance in this regard.
Hi guys,
I just struggled for few moments after which I was able to draw a line over a bar chart using canvasjs.
Here is the code:
//first I got the mean and confidence interval from a json file from php mysql
var upper_bound=mean+confidence_interval;
var lower_bound=mean-confidence_interval;
var chartConTS = new CanvasJS.Chart(“chartContainer”,
{
title:{
text: “Sample”
},
axisX:{
labelFontColor: “rgb(0,75,141)”,
},
axisY: {
title: “Seconds”
},
animationEnabled: true,
exportEnabled: true,
zoomEnabled: true,
data: [
{
type: “column”,
color: “#2a7b86”,
dataPoints: [
{x: 0, label: ‘test_name’, y: mean},
],
},
{
type: “line”,
dataPoints: [
{ x: 0, y: upper_bound },
{ x: 0, y: lower_bound},
]
}
]
});
HOW CONNECT WITH MS ACCESS DATABASE
Hi,
I have return on line with live update for every 10 sec and it is working fine. But the problem is when I have open the chart application as background tab and when I try to open that tab the browser getting hanged. Is their any solution for this.
Thanks
Sreekanth,
If you can reproduce the issue using jsfiddle, we can have look into the issue and suggest a solution.
Hi,
I have a question about “Multi Series Column Chart”. I don’t want to show the datapoint names in labels on axisX, instead I would like to show there a month and a year. How can I do that?
dataPointMaxWidth property is not working in the alternate way of setting:
chart.options.dataPointMaxWidth = 40;
Or am I doing it wrong?
Artyom,
It was a bug and we have just fixed the issue. Here is an internal build with the fix.
Thanks for reporting the issue.
I want to use canvasJS in my Android project,but finally I can’t change its data.is there have some examples for Android ?
Superb charts all are Working nicely
Hi
How can I render the chart with class attribute of element?
How to render using chartContainer class?
You can instantiate a new Chart object by sending the ID of div element where the chart is to be rendered. You can also pass DOM element instead of ID.
Here is the jsFiddle to render charts based on class name.
Hi,
I am using the column chart, but when there is more than 10 bars in the chart it does not show all the label. it shows all the bars but half of them with no labels. how can i force it to show all the labels.
Thanks.
Label are skipped automatically to avoid overlapping. But you can force to show all labels by setting interval to 1.
Perfect !!! Thank you. (Y)
i need multi series line chart ,i want to take datapoints from two different text files, and assign one file values for one line and another for second line, is it possible with canvas js?
Absolutely, it is possible with CanvasJS!!
First you take the values into two datapoints from the two files using Ajax, then you can pass the datapoints as elements in the data array for the chart. Simple.
Thank you very much. Your charts are really helped me today. the documentation with ‘try your self’ is awesome for practices. in overall 100/100.
How add “save as JPG” button for chart.
set exportEnabled to true to do the same.
Thanks naveen …
Hi , how can I render plot dynamically after reading from text file, I got the code to read from a file from the below path https://canvasjs.com/forums/topic/how-can-i-plot-values-from-txt-file/ , but I need to display same continuously. how can I do it ?
Any help will be highly appreciated!!!
Here is a jsfiddle to update chart continuously.
Hi guys! I have a problem “converting” json object to dataPoints. Here is my function
$scope.getDataPoints = function () {
angular.forEach($scope.risultati, function (ris) {
$scope.dataPoints += “{ label: \”” + ris.IDCommessa + “\”, y: ” + ris.Valore + ” },”;
})
$scope.dataPoints += “]”;
}
but i get this error:
HTML1300: È stata eseguita la navigazione.
Index.html
TypeError: Impossibile recuperare la proprietà ‘getTime’ di un riferimento nullo o non definito
at Chart.prototype._processMultiseriesPlotUnit (http://localhost:53937/Scripts/canvasjs.js:2817:5)
at Chart.prototype._processData (http://localhost:53937/Scripts/canvasjs.js:2769:6)
at Chart.prototype.render (http://localhost:53937/Scripts/canvasjs.js:2396:3)
at render (http://localhost:53937/Scripts/canvasjs.js:14385:5)
at $scope.toChart (http://localhost:53937/App/controllers/risultatiController.js:72:9)
at Anonymous function (http://localhost:53937/App/controllers/risultatiController.js:109:13)
at Anonymous function (http://localhost:53937/Scripts/angular.js:10250:13)
at processQueue (http://localhost:53937/Scripts/angular.js:14745:11)
at Anonymous function (http://localhost:53937/Scripts/angular.js:14761:27)
at Scope.prototype.$eval (http://localhost:53937/Scripts/angular.js:15989:9)
it says “Impossible to get the property getTime of a null or not defined object”
Could you help me please?
i need to get pie chart which having like 20% of dotted portion 40% lines and 40% grids is it possible with canvs js if so how to make it?
Shivu,
As of now it is not possible to have patterns like this inside dataPoints
hey, thanks for your script. its really very useful to me and easy customization. Thank you very much.
Hi, how to save the graph in a file after generating it ??
You can use exportEnabled for enable save option. Also it is possible to customize the name with exportFileName
Hi, I can’t find any information about this, sorry, I’ve looked for ages. I basically don’t want any lines on the graph, on the y axis, so I’ve set:
axisY: {
gridThickness: 0
}
but, I want it a line across 0, so you can see what is negative and positive by the number on 0. I basically want to remove all y axis lines, except the one at 0.
Is this possible?
Sam,
You can use axisY stripLines for this.
I have looked into this Vishwas, I think, I could use axisT stripLines as a final resort, but it’s tricky, we have dynamic charts, so we can range data from 0-100, to -40k to +40k, so to calculate the size of the stripLine would be really tricky.
So we could have a graph from -10 to 100, and have the stripline as start: -0.5, end: 0.5, then it looks fine, but on a large graph with big numbers, this line isn’t even noticeable. So then the stripLine would need to be like, -100, to 100.
Sam,
You can use stripLines with value=0 instead of using startValue and endValue, which will be visible irrespective of data-values. Here is an example.
Ahhhh nice, thank you!
Does the job.
I can’t put two different chart on the same page due to id conflict, can you throw more lights?
Ahmed,
You should use different container-id for different containers. Here is a working example for multiple-charts in same page.
simple solution :
window.onload = function () {
var cult = parseFloat(document.getElementById(”).value);
var json = { “tot1”: cult , “tot2”: 110, “tot3”: 7, “to42”: 110, “tot5”: 7 };
var dataPoints = [];
for (key in json) {
dataPoints.push({ label: key, y: json[key] });
}
var chart = new CanvasJS.Chart(“chartContainer”,
{
data: [
{
type: “column”,
dataPoints: dataPoints
}
]
});
chart.render();
}
I wanted to click on label. that is shows in bottom (x axis). i mean that i wants link on it.
Is it possible to do that ????
Scusa per il ritardo nella risposta
example:
http://jsfiddle.net/canvasjs/baxuvvvL/
Ciao
Tushar,
Sorry, click events are not supported on labels.
I’m interested in your graphs sir .. I would like to ask for some help on how to incorporate those graphs with a sql database .. i always had problems in fetching the json file and the graph wont show .. please help ..
1.
Using connectionRead As New SqlConnection(ConfigurationManager.ConnectionStrings(“StoreLocationsConnectionString”).ConnectionString)
Dim commandRead As New SqlCommand(queryString, connectionRead)
connectionRead.Open()
Dim reader As SqlDataReader = commandRead.ExecuteReader()
If reader.HasRows Then
Do While reader.Read
If reader IsNot Nothing Then
LabelCount_CulturaArte.Text = reader.GetInt32(1)
Else
LabelCount_CulturaArte.Text = “1”
End If
Loop
End If
reader.Close()
End Using
2.
var cult = parseFloat(document.getElementById(”).value);
3.
var json = { “Cultura…”: cult,……………………………….
Dear Implementation Team,
This application is simply awesome
I am using it to visualize throughput of web sockets. With CanvasJS I am able to show hundreds of data pints on primary and secondary axis in real time.
Whatever I touch in this application it never cease to amaze me.
Thank you for providing this masterpiece of application and great documentation!
Krzysztof
We are glad that you liked our Charts… Thanks for choosing CanvasJS… :-)
I tried above given code, it worked fine when inside .html file, but not displaying anything when I used it with my asp.net web page(VB 2005). Please help me I’m stuck…
Mahendra,
Thanks for your comment, we will get back to you soon with your query. Meanwhile you can check this link.
How can I generate graph from 2 arrays i.e. x-axis data and y-axis data?
Hi Harsh,
Here is an example for your query.
I saved on of the examples as a html file to run on my computer but it doesn’t seem to work. Could someone explain to me why? So that I can know how to run the graphs i create. The code I used is pasted below.
window.onload = function () {
var chart = new CanvasJS.Chart(“chartContainer”,
{
title:{
text: “Division of products Sold in Quarter.”
},
axisY:{
title: “percent”
},
animationEnabled: true,
toolTip:{
shared: true,
content: “{name}: {y} – #percent%“,
},
data:[
{
type: “stackedBar100”,
showInLegend: true,
name: “April”,
dataPoints: [
{y: 600, label: “Water Filter” },
{y: 400, label: “Modern Chair” },
{y: 120, label: “VOIP Phone” },
{y: 250, label: “Microwave” },
{y: 120, label: “Water Filter” },
{y: 374, label: “Expresso Machine” },
{y: 350, label: “Lobby Chair” }
]
},
{
type: “stackedBar100”,
showInLegend: true,
name: “May”,
dataPoints: [
{y: 400, label: “Water Filter” },
{y: 500, label: “Modern Chair” },
{y: 220, label: “VOIP Phone” },
{y: 350, label: “Microwave” },
{y: 220, label: “Water Filter” },
{y: 474, label: “Expresso Machine” },
{y: 450, label: “Lobby Chair” }
]
},
{
type: “stackedBar100”,
showInLegend: true,
name: “June”,
dataPoints: [
{y: 300, label: “Water Filter” },
{y: 610, label: “Modern Chair” },
{y: 215, label: “VOIP Phone” },
{y: 221, label: “Microwave” },
{y: 75, label: “Water Filter” },
{y: 310, label: “Expresso Machine” },
{y: 340, label: “Lobby Chair” }
]
}
]
});
chart.render();
}
thanks in advance
I would like to add that when I’ve saved and ran simpler graphs it has worked appropriately.
An example that worked fine:
window.onload = function () {
var chart = new CanvasJS.Chart(“chartContainer”, {
title:{
text: “My First Chart in CanvasJS”
},
data: [
{
// Change type to “doughnut”, “line”, “splineArea”, etc.
type: “doughnut”,
dataPoints: [
{ label: “apple”, y: 10 },
{ label: “orange”, y: 15 },
{ label: “banana”, y: 25 },
{ label: “mango”, y: 30 },
{ label: “grape”, y: 28 }
]
}
]
});
chart.render();
}
Samuel,
Here is the working example. Kindly replace all left and right quotes with double-quotes in your code to make it work.
hey,may i use canvas.js offline???
Yes, you can download from here.
i hav put js like a ” ” in my web application but its not working
my source/ /resources/DSSNew/jquery.canvasjs.min.js/
is there any need to put excanvas.js in project
hey…thank you..! Its working…!!!!
but still I have one question,can I pass parameter dynamically if yes pls give me a solution….!
Amar,
You can add or update dataPoints. Refer this page for more into.
yeah, datapoints is ok…bt i want to implement in Bar charts,please give me that solution if any u have
hi,I want custom the interval base on x axis value like if it is 12hr it should take interval=1 and more than that it should take 2 , data type of x axis is [new Date(2016, 04, 18, 5, 0), 18]
Ben,
If you are using dynamic chart, by comparing the new dataPoint being added with the last dataPoint, you can change interval and intervalType. Otherwise, you can change intervalType on rangeChanging, here is an example.
Hi , how can i pass data dynamically from sql i have json data in var but i am unable to pass it into datapoint anyone help me.
Hi,
You need to create a HTML page that does AJAX request and fetch the data. After getting the data, it will render a Chart. You can refer this thread.
Is there any property available to give some space between x axis line and first column line. Because in my column chart X-Axis is merged with the first column line.
Muralidharan,
You can set viewportMinimum of axis-Y to a negative value (Ex: -5 or -10) to give some space between axis-X line and the column.
Thanks, now its working
Hai Vishwas,
I have set viewportMinimum to give some space between axis-X line and the column and it works fine. But now i need to hide the negative value because it misleads the users. Is there any way to fix it. Thanks.
Using labelFormatter you can hide negative labels. Here is an example.
HI!!!
i want double column chart. it’s working if
dataPoints: [
{ label: “banana”, y: 18 },
{ label: “orange”, y: 29 },
{ label: “apple”, y: 40 },
{ label: “mango”, y: 34 },
{ label: “grape”, y: 24 }
]
},
{ //dataSeries – second quarter
type: “column”,
name: “Second Quarter”,
dataPoints: [
{ label: “banana”, y: 23 },
{ label: “orange”, y: 33 },
{ label: “apple”, y: 48 },
{ label: “mango”, y: 37 },
{ label: “grape”, y: 20 }
question>
when i remove one banana ->
dataPoints: [
{ label: “banana”, y: 18 },
{ label: “orange”, y: 29 },
{ label: “apple”, y: 40 },
{ label: “mango”, y: 34 },
{ label: “grape”, y: 24 }
]
},
{ //dataSeries – second quarter
type: “column”,
name: “Second Quarter”,
dataPoints: [
{ label: “orange”, y: 33 },
{ label: “apple”, y: 48 },
{ label: “mango”, y: 37 },
{ label: “grape”, y: 20 }
like this. Orange goes to banana’s column. Can I sort it by label.
is it possible take all datas in one dataPoint
SOmething like this
type: “column”,
name: “Second Quarter”,
dataPoints: [
{ label: “orange”, y: 33,name: “First Quarter”},
{ label: “apple”, y: 48,name: “First Quarter” },
{ label: “mango”, y: 37,name: “First Quarter” },
{ label: “grape”, y: 20, name: “First Quarter” },
{ label: “banana”, y: 18, name: “Second Quarter” },
{ label: “orange”, y: 29, name: “Second Quarter” },
{ label: “apple”, y: 40, name: “Second Quarter” },
{ label: “mango”, y: 34, name: “Second Quarter” },
{ label: “grape”, y: 24, name: “Second Quarter” }
Mansour,
In multiseries column chart the columns with same x values grouped together. So, you have to specify x values in each series to group the columns together.
hello..i want fetch data from database and use that as data points. I dont want to manually fill the data points! is that possible with CanvasJs ?
Hi there, I am trying to update the index label using option objects in the editor above but it doesn’t seem to be working. I’m using: chart.options.dataSeries = { indexLabel: “{y}”, };
Please let me know if I’ve done something wrong. Many thanks!
Never mind, the following works: chart.options.data[0].indexLabel = “{y},”;
on my laptop…these codes works on maxthon…but not on chrome and firefox…
any idea why is that happen…?
answer truly appreciated….
chaoz,
Can you please try using this latest build and let us know if it worked.
If not, can you send screenshot depicting the issue from both firefox and chrome.
Hi, Its a good js to create any type of graph.
I have a query about bar graph.
I am creating bar graph using to way.
1. number of bar is static.
2. number of bar is dynamic according to value in database
When I am creating by first way, strip lines are working correctly, but when i create graph using second way, and want to add strip line in my code, the code is not working..
Prasanna,
We were unable to reproduce the issue in dynamic charts. Can you kindly create a jsfiddle, so that we can look into the issue.
HI, I was wondering if it is possible to display the chart using the json response in ajax which has a spring mvc end point.
Answer is really appreciated.
Thanks in advance!
Saimeera,
Yes it is possible to draw a chart on ajax request if you send JSON data using spring mvc.
Here is an example to draw chart on JSON response
Hi,I want to use bar chart to show 200 peoples’ score with attribute ” type: ’stackedBar‘ ” , but there is a problem that 200 peoples’ name cannot show on axisY. I try to make “chartContainer” div more high,so i make the height = 10000px, but the name on axisY also changed to large fontsize . Can u plz help me?
Thanks very much~
Maoliangli,
Label font-size keeps changing based on the chart size. To keep it constant you can use labelFontSize.
I have problem creating dynamic graph .i have use ajax function which call php web service which give me response which required to pass as data to canvasjs .but it give me error that
Cannot use ‘in’ operator to search for ‘name’ in [
my function for calling graph is
function mychart(data)
{
alert(data);
data = data.replace(/\”/g, “”);
alert(data);
// remove non-printable and other non-valid JSON chars
/* var datap = data.replace(/[\u0000-\u0019]+/g,””);
var datapoint=eval(datap); //
alert(datapoint);*/
var chart = new CanvasJS.Chart(“chartContainer”,
{
title: {
text: “Growth of Gangnam Style on YouTube”
},
axisX:{
valueFormatString: “DD-MMM” ,
interval: 10,
intervalType: “day”,
labelAngle: -50,
labelFontColor: “rgb(0,75,141)”,
minimum: new Date(2012,06,10)
},
axisY: {
title: “Views on YouTube”,
interlacedColor: “azure”,
tickColor: “azure”,
titleFontColor: “rgb(0,75,141)”,
valueFormatString: “#M,,.”,
interval: 1000
},
data:data
});
chart.render();
}
and response of web service is
[{“x”:” new Date(2016,6,26)”,”y”:8060},{“x”:” new Date(2016,6,28)”,”y”:5760}]
and data should be like
dataPoints: [ { x: new Date(2012, 06, 15), y: 0}]
plz help me
Nayana,
Data should be formatted properly before passing it to CanvasJS. Please refer to this working fiddle.
plz any one help me
Please help me, on how to implement dashboard by using Canvas, if have any link for sample example, please share to me
Thanks
Ramesh