How to Create a Pie Chart with JavaScript December 6th, 2017 by Timothy Loginov

Bulding an interactive JavaScript pie chartHave you ever wondered, how web developers create and integrate interactive JavaScript pie charts into HTML5 apps and web pages? If the answer is yes – keep on reading! This article explains how to create, change and integrate a pie chart into your web page. Beware! A hot-button political issue is present in this article. But we will not offend anyone!

Pie chart is one of the most popular chart types. Mathematically speaking it looks like a circle divided into sectors which represent a part of a whole. For the most of us, pie charts look like real pies or pizzas cut into several slices. In this article, you will find a detailed tutorial on how to build one, with JS chart code samples.

Creating a JavaScript Pie Chart

There are four basic steps you should do to make a chart of any type with a JavaScript charting library. Spend 5 minutes and you will learn to add an interactive JS (HTML5) pie chart that looks like this to your web page:

JavaScript pie chart being created along this JS chart tutorial

Step 1. Create an HTML page

The very first thing you need to do is to create a file in which you will put your chart later. Create a simple HTML page, set its title and create a container for the future chart:

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

The width and height parameters of the container can be set in percents or in pixels. They are responsible for the chart’s width and height. Setting them to “100%” will make the chart fill the whole page.

Step 2. Reference all necessary files

The second step is about adding links into the <head> section. It is necessary to load the JavaScript charting library and create a tag where the whole code of our future pie chart sample will be put in:

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

Step 3. Put the data together

The main purpose of creating a chart is to visualize data. So, it is clear that your data is the most important part of a chart and charting is only a way to present data in a graphical, visual manner.

If you choose a wrong chart type to visualize the data, you may mislead yourself or a chart viewer. So choose the chart type wisely! If you don’t know what’s the difference between chart types, check out the Choosing Chart Type series of articles on our blog. You are also welcome to use this nifty tool, Chartopedia; you’ll find Pie Chart there and see that this chart type is good to show Part Of The Whole.

Showing what some whole consists of is exactly what we are going to do now. We’ll see the composition of the whole American nation in terms of race. To find out, let’s check out U.S. Department of Commerce Economics and Statistics Overview of Race and Hispanic Origin: 2010 and take some data from there:

Population by Race for the United States: 2010 Census
Race Number
White 223,553,265
Black or African American 38,929,319
American Indian and Alaska Native 2,932,248
Asian 14,674,252
Native Hawaiian and Other Pacific Islander 540,013
Some Other Race 19,107,368
Two or More Races 9,009,073

If you looked at the original data table in the Census Brief, you may have noticed there is a separate column with percentages. The great thing about JavaScript charts is that you don’t need it, you can put in data, and the chart calculates everything:

// set the data
var data = [
    {x: "White", value: 223553265},
    {x: "Black or African American", value: 38929319},
    {x: "American Indian and Alaska Native", value: 2932248},
    {x: "Asian", value: 14674252},
    {x: "Native Hawaiian and Other Pacific Islander", value: 540013},
    {x: "Some Other Race", value: 19107368},
    {x: "Two or More Races", value: 9009073}
];

Step 4. Write the chart code

This is the finishing step in creating an interactive JavaScript pie chart. Add the anychart.onDocumentReady function. This function is executed when the page is ready. Create the chart entity, put it into the container and connect the data with the chart.

anychart.onDocumentReady(function() {

  // set the data
  var data = [
      {x: "White", value: 223553265},
      {x: "Black or African American", value: 38929319},
      {x: "American Indian and Alaska Native", value: 2932248},
      {x: "Asian", value: 14674252},
      {x: "Native Hawaiian and Other Pacific Islander", value: 540013},
      {x: "Some Other Race", value: 19107368},
      {x: "Two or More Races", value: 9009073}
  ];

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

  // set the chart title
  chart.title("Population by Race for the United States: 2010 Census");

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

  // display the chart in the container
  chart.container('container');
  chart.draw();

});

Here’s how it looks:

See the Pen Creating a JavaScript Pie Chart: Basic Example by AnyChart JS Charts (@AnyChart) on CodePen.

That’s it! A simple pie chart created with a JavaScript charting library is ready!

Change Chart Appearance

This section is optional. If you are not satisfied with the chart appearance and want it to be more remarkable and attractive, you can make the necessary changes.

JS pie charts have a lot of settings. You can learn about them in the Pie Chart Settings article and grab some ideas and code from the Pie Chart Gallery.

Let’s get our modifications started!

Legend

Pie charts have a special control element: legend. Also known as the chart’s key, the legend is linked to the data that’s displayed on the chart.

By default, the legend is placed at the bottom of the chart and it is not looking good in this particular case.

To move the legend to the right and make its elements stack vertically, add the following setting to the code:

// set legend position
chart.legend().position("right");
// set items layout
chart.legend().itemsLayout("vertical");

Look how these modifications changed the pie chart:

See the Pen Creating a JavaScript Pie Chart: Move Legend by AnyChart JS Charts (@AnyChart) on CodePen.

Much better, right?

Sort

Another thing we can change is the order of slices in a pie to facilitate the visual data analysis. Let’s sort things out:

// sort elements
chart.sort("desc");

And the picture becomes clearer:

See the Pen Creating a JavaScript Pie Chart: Sort Slices by AnyChart JS Charts (@AnyChart) on CodePen.

Explode

There is one last thing we can do to highlight the hot-button issue we mentioned in the beginning. Let’s make the majority group stand out visually. To do so, we change the data by mean of a special setting:

{x: "White", value: 223553265, exploded: true},

And the final JavaScript pie chart looks as follows:

See the Pen Creating a JavaScript Pie Chart: Explode by AnyChart JS Charts (@AnyChart) on CodePen.

This pie chart could be a good addendum to many articles on the state of racial relations in the USA. “America really is more divided than ever” is the name of a Washington Post article by Joel Achenbach and Scott Clement. “America is more racially divided than it has been in decades,” echoes Carol Anderson in the Financial Times. These are troubling times and everyone hopes that the society will remember Barack Obama’s words: “That’s the path out of moments like these. Not to withdraw, or shout each other down, but to reach out to each other — even if it’s difficult — and find some common ground.”

Conclusion

This small tutorial explains how to build a pie chart using the AnyChart JavaScript charting library. Go to the official AnyChart JS Charts website for more information and, in particular, visit the JavaScript Chart Gallery for more chart types illustrated. The AnyChart Charts Documentation and AnyChart JavaScript API will help you to build and adjust your HTML5 charts with ease.


No Comments Yet

*