Simple Javascript Pie Chart (Free Download)

Welcome to a tutorial on how to create a simple Javascript pie chart. So you need to display some “nice data” in your project, but don’t want to load an entire library to bloat the loading time? Well, let us walk through a very simple Javascript pie chart in this guide – Read on!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

TABLE OF CONTENTS

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

PIE CHART DEMO

<!-- (A) LOAD PIE CHART CSS + JS -->
<link rel="stylesheet" href="pie-chart.css">
<script src="pie-chart.js"></script>
 
<!-- (B) EMPTY DIV TO GENERATE PIE CHART -->
<div id="demo"></div>
 
<!-- (C) CREATE PIE CHART -->
<script>
pie({
  target : document.getElementById("demo"), // required, target container
  donut : false, // optional, "convert" to donut chart
  data : [ // required, ["name", quantity, color]
    ["First", 33, "#ff0000"],
    ["Second", 21, "green"],
    ["Third", 14]
  ]
});
</script>

For you guys who just want to use this as a “plugin”:

  1. Load the JS and CSS.
  2. Create an empty <div> container.
  3. Call pie() on window load.
    • target Required, where to generate the pie chart.
    • donut Optional, pretty much just adds a “hole” in the middle of the pie chart to “convert” it into a donut chart.
    • data Required. This is a nested array in the format of [[NAME, QUANTITY, COLOR], [NAME, QUANTITY, COLOR], ...]. If the color is omitted, a random color will be assigned.

 

 

JAVASCRIPT PIE CHART

All right, let us now get into more details about how the Javascript pie chart works.

 

PART 1) CHART DATA & TOTAL VALUE

pie-chart.js
function pie (instance) {
  // (A) RANDOM COLOR HELPER
  // credit : https://stackoverflow.com/questions/1484506/random-color-generator
  var rnd = () => {
    let letters = "0123456789ABCDEF", color = "#";
    for (let i=0; i<6; i++) { color += letters[Math.floor(Math.random() * 16)]; }
    return color;
  };
 
  // (B) TOTAL VALUE + RANDOM COLORS IF REQUIRED
  var total = 0;
  for (let i of instance.data) {
    total += i[1];
    if (i[2] == undefined) { i[2] = rnd(); }
  }
  // ...
}

Yes, there is only a single function pie() in the Javascript file. The first part of this script pretty much loops through the provided data:

  • Add the quantities to total.
  • Generate a random color for that segment if it is not defined.

 

 

PART 2) PIE CHART HTML

pie-chart.js
// (C) CREATE HTML
var chart = document.createElement("div"),
    legend = document.createElement("div");
chart.className = "pie";
legend.className = "legend";
instance.target.appendChild(chart);
instance.target.appendChild(legend);
if (instance.donut) {
  var donut = document.createElement("div");
  donut.className = "hole";
  chart.classList.add("donut")
  chart.appendChild(donut);
}

No need to panic, we are just creating the “pie chart wrapper and legend” here.

<div id="demo">
  <div class="pie donut"><div class="hole"></div></div>
  <div class="legend"></div>
</div>

 

 

PART 3) ADD PIE SEGMENTS

pie-chart.js
// (D) CREATE SEGMENTS
var css = "background: conic-gradient(",
from = 0, to = 0, slice;
for (let i of instance.data) {
  // (D1) PIE SLICE
  slice = Math.floor((i[1] / total) * 360);
  to += slice;
  css += `${i[2]} ${from}deg ${to}deg,`;
  from = to;
 
  // (D2) LEGEND
  legend.innerHTML += `<div style="background:${i[2]}"></div>
  <div>${i[0]}</div>`;
}
chart.style.cssText = css.slice(0, -1) + ")";
  • (D) The segments of the pie chart are actually created with CSS conic-gradient(COLOR START END, COLOR START END, ...).
  • (D1) A full circle is 360 degrees. Thus, we can calculate how much each slice occupies with (QUANTITY ÷ TOTAL) X 360.
  • (D2) Lastly, not forgetting to add the segment to the legend as well.

 

PART 4) PIE CHART CSS

pie-chart.js
/* (A) PIE + DONUT CHART */
.pie, .hole { border-radius: 50%; }
.pie { width: 300px; height: 300px; }
.hole { width: 150px; height: 150px; background: #fff; }
.donut {
  display: flex;
  justify-content: center;
  align-items: center;
}
 
/* (B) LEGEND */
.legend {
  display: grid;
  grid-template-columns: 50px auto;
  margin-top: 30px;
}
.legend div { padding: 10px; }

Not going to explain this line by line… This should be pretty self-explanatory.

  • .pie { width: 300px; height: 300px; } Set to the same width and height to create a square.
  • .pie { border-radius: 50%; } Effectively turns the square into a circle.

That’s pretty much all of it. As above, the segments are calculated and created by Javascript.

 

 

EXTRA BITS & LINKS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

COMPATIBILITY CHECKS

This example will work on all modern “Grade A” browsers.

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *