Creating JavaScript Bar Chart

October 25th, 2017 by Timothy Loginov

How to create a JavaScript bar chart: TutorialHow to create a JavaScript bar chart and why is this important? Every day, data visualization becomes all the more powerful and important area of the Web. The volume of information grows, and it must be made understandable as fast as possible. That’s when data visualization instruments like charts and dashboards become a great help.

Creating HTML5 charts might seem a complicated task, but this assumption is wrong. This article blows this prejudice to pieces and shows how to build an interactive bar chart using JavaScript.

The result will look like on the picture above. Then you’ll also learn how to quickly modify and customize such a JavaScript (HTML5) bar chart. All the JS chart examples used along the tutorial can be found on CodePen.

How to Build JavaScript Bar Chart

There are 4 basic steps you should take to create a simple bar chart for your application or website:

  • Create an HTML page.
  • Reference all necessary files.
  • Put together the data.
  • Write the code for a chart.

1. Create an HTML page

The very first thing you should do is to create an HTML page. It should look like the following:

<!DOCTYPE html>
<html>
  <head>
    <title>JavaScript Bar Chart</title>
  </head>
  <body>
    <div id="container" style="width: 100%; height: 100%"></div>
  </body>
</html>

The container we have created will be a container for a chart. You can set other values for the width and height parameters if you don’t want your chart to fill the whole page.

Let’s move to the next step.

2. Reference all necessary files

Reference the AnyChart JavaScript charting library in the <script> tag in the <head> section:

<!DOCTYPE html>
<html>
  <head>
      <title>JavaScript Bar Chart</title>
      <script src="https://cdn.anychart.com/releases/8.0.0/js/anychart-base.min.js"></script>
  </head>
  <body>
    <div id="container" style="width: 100%; height: 100%"></div>
  </body>
</html>

The whole code of the JS chart sample is written in the <script> tag too. Add two more lines:

<!DOCTYPE html>
<html>
  <head>
      <title>JavaScript Bar Chart</title>
      <script src="https://cdn.anychart.com/releases/8.0.0/js/anychart-base.min.js"></script>
  </head>
  <body>
    <div id="container" style="width: 100%; height: 100%"></div>
    <script>
        <!-- chart code will be here -->
    </script>
  </body>
</html>

The entire code of the JavaScript charting example will be put between those lines.

Now the preparations are over. It’s time to move to the next step.

3. Put together the data

The first thing you need when it comes to data visualization is the data itself. As we’re making a simple chart sample now, let’s arrange some simple data.

A simple data of a simple two-dimension chart can be presented as a table with two columns: X and Y. X is usually for timestamps or categories and Y holds the values according to the categories.

Our chart will show the 10 deadliest recorded earthquakes in the XXth century, data is obtained from Wikipedia: List of earthquakes.

Place (Year) Death toll
San-Francisco (1906) 1500
Messina (1908) 87000
Ashgabat (1948) 175000
Chile (1960) 10000
Tian Shan (1976) 242000
Armenia (1988) 25000
Iran (1990) 50000

 
The categories, which are spread among the X-axis, can be of one type or another, and it is not necessary for them to be numeric. Let’s set the values of the first column as categories of the X-axis. The number of victims will become the Y-axis values.

Convert this data into a special JavaScript object that contains data array and data header settings:

var data = {
  header: ["Name", "Death toll"],
  rows: [
    ["San-Francisco (1906)", 1500],
    ["Messina (1908)", 87000],
    ["Ashgabat (1948)", 175000],
    ["Chile (1960)", 10000],
    ["Tian Shan (1976)", 242000],
    ["Armenia (1988)", 25000],
    ["Iran (1990)", 50000]
]}

All goes well. Now let’s move to the next step.

4. Write the code for the chart

Finally, all preparations are made, it’s time to start coding!

As you should remember, we’ve specified above that all of the JavaScript charting sample code must be written inside of the <script></script> tags.

First, put the function that waits until the page is ready:

<script>
anychart.onDocumentReady(function() {
    // the code to create a chart will be here
});
</script>

Second, add the data into the sample:

anychart.onDocumentReady(function() {
    // the data 
    var data = {
      header: ["Name", "Death toll"],
      rows: [
        ["San-Francisco (1906)", 1500],
        ["Messina (1908)", 87000],
        ["Ashgabat (1948)", 175000],
        ["Chile (1960)", 10000],
        ["Tian Shan (1976)", 242000],
        ["Armenia (1988)", 25000],
        ["Iran (1990)", 50000]
    ]};
});

Now, specify the JavaScript chart type. You can find the whole list of the chart types AnyChart provides in the Supported Charts Types list. In our sample, we’ll choose the Bar Chart type with the data specified in the data variable.

// create the chart
var chart = anychart.bar();

// add the data
chart.data(data);

It’s better for a chart to have a title, to make it clear what it demonstrates from the very first look at it:

// set the chart title
chart.title("The deadliest earthquakes in the XXth century");

Now, the last thing we should do to finish our chart and run it, is to set the container for the chart and draw it:

chart.container('container');
chart.draw();

Bingo! Look at the result of our JavaScript charting below:

See the Pen Creating a JavaScript Bar Chart by AnyChart JavaScript Charts (@AnyChart) on CodePen.

The whole code of this interactive HTML5 bar chart example should look like this:

<!DOCTYPE html>
<html>
  <head>
    <title>JavaScript Bar Chart</title>
    <script src="https://cdn.anychart.com/releases/8.0.0/js/anychart-base.min.js">>/script>
  </head>
  <body>
    <div id="container" style="width: 100%; height: 100%"></div>
    <script>
      anychart.onDocumentReady(function() {

        // set the data
        var data = {
            header: ["Name", "Death toll"],
            rows: [
              ["San-Francisco (1906)", 1500],
              ["Messina (1908)", 87000],
              ["Ashgabat (1948)", 175000],
              ["Chile (1960)", 10000],
              ["Tian Shan (1976)", 242000],
              ["Armenia (1988)", 25000],
              ["Iran (1990)", 50000]
        ]};

        // create the chart
        var chart = anychart.bar();

        // add the data
        chart.data(data);

        // set the chart title
        chart.title("The deadliest earthquakes in the XXth century");

        // draw
        chart.container("container");
        chart.draw();
      });
    </script>
  </body>
</html>

Modify Chart Type

There are situations when you might doubt how to arrange it in the right way and which chart type would visualize this data best, you can get an idea what chart type you need from tools like Chartopedia.

To change the chart type, simply change the bar() method of the chart to the column() one:

// create the chart
chart = anychart.column();

That’s it, our JS bar chart is now a JS column chart:

See the Pen Creating a JavaScript Bar Chart: Modify to a JavaScript Column Chart by AnyChart JavaScript Charts (@AnyChart) on CodePen.

Tune Bar Chart

Charts can be tuned in many ways. One of the things that may be of interest is the ability to change general look and feel.

One of the easiest ways to do that is to change the chart theme. That can be done in the following two steps.

First, we need to link one of the predefined themes:

<script src="https://cdn.anychart.com/releases/8.0.0/themes/dark_earth.min.js" type="text/javascript"></script>

And then tell the chart to use it:

anychart.theme(anychart.themes.darkEarth);

That’s it, take a look at our JavaScript bar chart which looks completely different now:

See the Pen Creating a JavaScript Bar Chart: Tuning by AnyChart JavaScript Charts (@AnyChart) on CodePen.

Conclusion

As you can see, there is nothing difficult in creating JavaScript charts with the AnyChart JS library. Visit the AnyChart Docs and API to know everything about building and adjusting the interactive HTML5 charts for your projects and websites. Feel free to take the sample created above as the basis for your experiments and explore charting with AnyChart.


Comments (15)

*

Ali    20th Aug 22 10:36 pm

My html code is random value generator so how to put the chart in this code

  1. Reply
  2. Link
AnyChart Team    22nd Aug 22 6:55 am

Our support engineers will be glad to look into your situation and help you out. Please get in touch with them with all the appropriate details:

Thank you.

  1. Reply
  2. Link
Usha    16th Aug 22 10:47 am

I want to add two measures and two dimensions to this chart, can anyone tell how to do it?

  1. Reply
  2. Link
AnyChart Team    17th Aug 22 10:56 am

Please contact our Support Team with more details on what (and where, in Qlik Sense?) you are trying to create. Thanks.

  1. Reply
  2. Link
Shubham Sawant    10th Feb 22 5:48 am

I want to add Some Scroll Feature can I do that

  1. Reply
  2. Link
AnyChart Team    10th Feb 22 9:08 am

Absolutely! Сheck out the Scroller article in our JS chart documentation and feel free to contact our support engineers directly if you have further questions. Thanks.

  1. Reply
  2. Link
Ankit Saiyan    30th Nov 21 2:01 am

What if I want to write my own logic of creating the bar chart?

  1. Reply
  2. Link
AnyChart Team    1st Dec 21 6:09 pm

Feel free to share it right here or send your suggestions to our Support Team. Thanks.

  1. Reply
  2. Link
Jan    9th May 21 2:31 am

Hi,

How can I change the value to a percentage? Thanks!

  1. Reply
  2. Link
AnyChart Team    10th May 21 7:08 am

Hi Jan! Yes, you can, but what do you mean exactly? Are you looking for something like this?
https://docs.anychart.com/Basic_Charts/Stacked/Overview#percent_stacking

  1. Reply
  2. Link
Tammy    2nd Jul 20 6:59 pm

How can I style the chart to my own taste?

  1. Reply
  2. Link
AnyChart Team    3rd Jul 20 9:07 am

Easily! AnyChart is a very flexible JavaScript charting library.

For example, you can change the look in an instant by applying one of the pre-built themes as described in the “Tune the Chart” section of this tutorial. To learn about how to customize any other things, please visit our documentation which is extensive and detailed. In particular, here’s the bar chart docs. You might also want to check out several samples in our bar chart gallery for inspiration.

If you need further assistance, please contact our Support Team directly.

  1. Reply
  2. Link