Your First Chart using JavaScript in under 5 minutes

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.


Try Editing The Code

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.

  1. Copy the code template above and save it locally as HTML file
  2. Run the saved HTML file.
    You will see the above chart running on your machine.
  3. Now change the type parameter to “doughnut”.
  4. Save the changes and run it again.
    Voilà! You just created a doughnut chart.
  5. Now, try changing the type to various other chart types like “splineArea”, “bar”, etc… and let CanvasJS do its magic.

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.


Basic Column Chart

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

  1. 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
  2. Pass all the Chart related “options” to the constructor as the second parameter.
  3. Call chart.render() method to render the chart

Chart “options” mainly contains 4 important elements.

  1. title object with its text property set.
  2. dataPoints – which is an array of all data items to be rendered
  3. dataSeries – parent of dataPoints that also defines type of chart and other series wide options
  4. data – array element which is a collection of one or more dataSeries objects. Here we have only one dataSeries.

Checkout the code below – experiment and make yourself familiar with the API.

Note

Though 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.

Try Editing The Code

Checkout all the supported chart types


Multi Series Column Chart

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
Try Editing The Code

Customizing Chart

In the above chart we can do couple of customization to improve the visualization of data like

  1. Show values on y axis with $ as prefix and “K” as suffix. Same on toolTips
  2. Display Legend indicating Q1 and Q2

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.

Try Editing The Code

Changing Chart Theme

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

Try Editing The Code

Alternate way of setting / updating data

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];
Try Editing The Code
Note
  • You should remember to call chart.render() after setting/updating the options – try to batch all updates before calling chart.render()
  • We’ve got the performance part covered! So you can even update the chart every 100 milliseconds (or less if you wish!!) – though such an update rate will not be required in most cases

More Customization

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

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

172 Comments

  1. Rahul Khanna says:

    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

  2. Pingback: Beautiful HTML5 Charts

    • Sunil Urs says:

      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.

  3. GABO57 says:

    My requirement is the same as Rahul Khanna, want to see an example that reads a JSON file and the values ​​are plotted. thanks

    • Sunil Urs says:

      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.

    • Sunil Urs says:

      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.

  4. GABO57 says:

    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
    ]
    },

    • GABO57 says:

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

    • Sunil Urs says:

      Chart requires x & y values to be numbers – enclosing them in quotes creates prolems while doing calculations internally. Glad you figured it out.

  5. Bowo says:

    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

  6. CanvasJs_User says:

    can you please demonstrate an example of same chart by using dynamic data through .net, sql server?
    Thanks in advance

  7. Pingback: CanvasJS Charts v1.3 goes GA

  8. Zdeno says:

    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.

  9. Manoj Shetty says:

    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

  10. johnharrison823737926 says:

    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!

  11. Pingback: AngularJS Charts with CanvasJS | Matt Smith Blog

  12. Prajakta says:

    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?

  13. Vishnu says:

    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.

    • Sunil Urs says:

      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}].

  14. Pingback: CanvasJS – jQuery Charts Plugin | Js Plugins

  15. Changkyun says:

    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.

  16. Dinesh says:

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

  17. Ankit says:

    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.

  18. nracer says:

    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.

  19. nracer says:

    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 ?

  20. nracer says:

    [[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]]

    • Anjali says:

      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(); }); });

  21. purusottama sahoo says:

    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 .

  22. keyur chauhan says:

    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 ?

  23. devendra says:

    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?

  24. mohan says:

    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.

  25. umair sayed says:

    Hi… I want to get the value from database and display it through graph, how can i do that using canvasjs?

  26. Pingback: Еще одна библиотека построения графиков на JavaScript | ENUT

    • Anjali says:

      pavan,

      CanvasJS does not support importing or exporting data in excel format. You’ll have to do the conversion to and from CanvasJS format.

  27. Yaseen Ahmed says:

    Hello, i am unable to get this property ‘animationEnabled: true’ for chart type= ‘
    column’

    • Yaseen Ahmed says:

      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.

      • Anjali says:

        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.

  28. MahPari says:

    Hello Dear, Could you please let me know how to disable bubbles on the mousehover!? and also how to disable labels!? Thanks a lot

  29. MahPari says:

    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!

  30. nikhil says:

    How can we dynamically change number of datapoint under data section. i want to add or remove based on JSON data i am passing.

  31. manoj says:

    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

    • sandeep kumar sarma says:

      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},
      ]
      }
      ]
      });

  32. Sreekanth says:

    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

  33. Artyom says:

    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?

  34. Artyom says:

    dataPointMaxWidth property is not working in the alternate way of setting:

    chart.options.dataPointMaxWidth = 40;

    Or am I doing it wrong?

  35. LeeShuqing says:

    I want to use canvasJS in my Android project,but finally I can’t change its data.is there have some examples for Android ?

  36. sandhya says:

    Hi

    How can I render the chart with class attribute of element?

    How to render using chartContainer class?

    • Naveen Venugopal says:

      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.

  37. Ali Sbeiti says:

    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.

  38. shivu says:

    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?

    • sandeep kumar sarma says:

      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.

  39. zamaan says:

    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.

  40. Giuseppe says:

    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?

  41. shivu says:

    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?

  42. vishnu says:

    hey, thanks for your script. its really very useful to me and easy customization. Thank you very much.

  43. Sam says:

    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 says:

        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.

  44. vittorio pietralunga says:

    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();
    }

  45. Tushar Balar says:

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

  46. jhe_24 says:

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

    • vittorio pietralunga says:

      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,……………………………….

  47. Krzysztof says:

    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

  48. mahendra says:

    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…

  49. essbee says:

    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

    • essbee says:

      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();
      }

  50. ben says:

    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]

  51. dove sound says:

    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.

    • Sanjoy says:

      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.

  52. Muralidharan says:

    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.

  53. Mansour says:

    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.

    • Mansour says:

      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” }

    • Sanjoy says:

      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.

  54. Nag says:

    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 ?

  55. Dean says:

    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!

  56. chaoz says:

    on my laptop…these codes works on maxthon…but not on chrome and firefox…

    any idea why is that happen…?

    answer truly appreciated….

    • Sanjoy says:

      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.

  57. Prasanna Wagh says:

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

  58. Saimeera says:

    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!

    • Sanjoy says:

      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

  59. maoliangli says:

    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~

  60. Nayana says:

    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

  61. Ramesh says:

    Please help me, on how to implement dashboard by using Canvas, if have any link for sample example, please share to me

    Thanks
    Ramesh

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