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!

 

 

TABLE OF CONTENTS

 

JAVASCRIPT PIE CHART

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

 

PIE CHART DEMO

1-pie-chart.html
<!-- (A) LOAD PIE CHART CSS + JS -->
<script src="2-pie-chart.js"></script>
<link rel="stylesheet" href="3-pie-chart.css">
 
<!-- (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.

 

 

PART 1) CHART DATA & TOTAL VALUE

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

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

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

3-pie-chart.css
/* (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.

 

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

EXAMPLE CODE DOWNLOAD

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

 

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 *