Learn how to create and customize a pie chart using Loader.js with this step-by-step guide. Perfect for data visualization in JavaScript.
Table of Contents
Creating visually appealing and informative pie charts is essential for effective data visualization. With Loader.js, a powerful JavaScript library, you can easily create and customize pie charts. This guide will walk you through the process, from setting up your environment to adding interactivity, ensuring you can present your data in a compelling way.
What is Loader.js?
Loader.js is a versatile JavaScript library designed to simplify the process of creating various types of charts. It offers a range of features that make it an excellent choice for data visualization. Whether you're creating pie charts, bar charts, or line graphs, Loader.js provides the tools you need. Its ease of use and extensive customization options make it popular among developers. With Loader.js, you can create interactive and dynamic charts that enhance your data presentations.
Source Code
Step 1 (HTML Code):
Begin by creating an HTML file and include the Loader.js library in it. Next, define a container for your pie chart using a <div>
element.
Here’s a breakdown of each part:
<!DOCTYPE html>
:
- Specifies that this document is an HTML5 document.
<html lang="en">
:
- Defines the root element of the document, with the language set to English (en).
<head>
:
- Contains meta-information about the HTML document, such as character set, viewport settings, and references to external resources.
<meta charset="UTF-8">
:
- Specifies the character encoding for the document as UTF-8, which includes most characters from the vast majority of human written languages.
<meta http-equiv="X-UA-Compatible" content="IE=edge">
:
- Instructs Internet Explorer to use the highest mode available to render the content.
<meta name="viewport" content="width=device-width, initial-scale=1.0">
:
- Sets the viewport to the width of the device's screen and sets the initial zoom level to 1.0. This is important for responsive web design.
<title>
Google Charts Advanced Pie Chart Example</title>
:
- Defines the title of the webpage, which appears in the browser's title bar or tab.
<link rel="stylesheet" href="styles.css">
:
- Links an external CSS file (styles.css) to style the HTML content. This file contains additional styling rules for the webpage.
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js">
</script>
:
- Loads the Google Charts library (loader.js) using a
<script>
tag. This script is necessary to load and initialize Google Charts on the webpage.
<script src="script.js">
</script>
:
- Links an external JavaScript file (script.js). This file contains JavaScript code to initialize and draw the Google Charts pie chart based on data.
<body>
:
- Contains the main content of the HTML document, including visible elements such as text, images, and in this case, a
<div>
for the pie chart.
<div id="piechart">
</div>
:
- Defines an empty
<div>
element with the ID attribute set to "piechart". This is where the Google Charts pie chart will be dynamically rendered by the JavaScript code defined in script.js.
Step 2 (CSS Code):
Next, we will create our CSS file. In this file, we will use some basic CSS rules to style our pie chart. Let's break down the CSS code and explain what each part does:
body Style
body { display: flex; justify-content: center; align-items: center; height: 100vh; }
display: flex;
- This sets the body element to use a flexbox layout. Flexbox is a layout model that allows items within a container to be automatically arranged in a flexible and predictable way.
justify-content: center;
- This centers the flex items horizontally within the body. Any direct children of the body will be centered along the main axis (horizontal axis for row direction).
align-items: center;
- This centers the flex items vertically within the body. It aligns items along the cross axis (vertical axis for row direction).
height: 100vh;
- This sets the height of the body to be 100% of the viewport height. vh stands for viewport height, so 100vh means the height is equal to the full height of the viewport.
#piechart Style
#piechart { width: 100%; height: 100%; max-width: 900px; max-height: 500px; margin: 0 auto; }
width: 100%;
- This sets the width of the #piechart element to 100% of its container's width.
height: 100%;
- This sets the height of the #piechart element to 100% of its container's height.
max-width: 900px;
- This restricts the maximum width of the #piechart element to 900 pixels. Even if the container is wider, the #piechart will not exceed this width.
max-height: 500px;
- This restricts the maximum height of the #piechart element to 500 pixels. Even if the container is taller, the #piechart will not exceed this height.
margin: 0 auto;
- This centers the #piechart element horizontally within its container. margin: 0 auto; sets the top and bottom margins to 0 and the left and right margins to auto, which centers the element horizontally.
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
#piechart {
width: 100%;
height: 100%;
max-width: 900px;
max-height: 500px;
margin: 0 auto;
}
Step 3 (JavaScript Code):
Finally, we need to create a function to display a pie chart of smartphone market share data in JavaScript. Here’s a detailed explanation of the code:
Loading the Google Charts Library
google.charts.load('current', { packages: ['corechart'] });
- This line loads the Google Charts library. The 'current' parameter specifies the current version, and the { packages: ['corechart'] } parameter specifies that we are loading the corechart package, which includes pie charts, among other types of charts.
Setting a Callback to Draw the Chart
google.charts.setOnLoadCallback(drawChart);
- This line sets a callback function (drawChart) that will be executed once the Google Charts library is loaded. This ensures that the chart drawing code runs only after the library is fully loaded.
Declaring Variables
var chart; var data; var options;
- These lines declare three variables that will be used to store the chart object, the data table, and the chart options, respectively.
Defining the drawChart Function
function drawChart() { data = google.visualization.arrayToDataTable([ [ 'Brand', 'Market Share', { role: 'tooltip', type: 'string', p: { html: true } }, ], ['Samsung', 31.2, 'Samsung: 31.2%'], ['Apple', 29.0, 'Apple: 29.0%'], ['Huawei', 12.4, 'Huawei: 12.4%'], ['Xiaomi', 10.3, 'Xiaomi: 10.3%'], ['Oppo', 8.6, 'Oppo: 8.6%'], ['Other', 8.5, 'Other: 8.5%'], ]);
- The drawChart function starts by creating a data table using google.visualization.arrayToDataTable. The data table is defined as an array of arrays.
- The first sub-array defines the column names and types. Here, 'Brand' and 'Market Share' are the column names, and the third column defines tooltips with role: 'tooltip', type: 'string', and p: { html: true } indicating that the tooltips support HTML content.
- The subsequent sub-arrays define the data for each brand, including the market share and the tooltip text.
options = { title: 'Smartphone Market Share - 2025', pieHole: 0.4, pieSliceText: 'label', slices: { 0: { offset: 0.1, color: '#3366CC' }, 1: { color: '#DC3912' }, 2: { color: '#FF9900' }, 3: { color: '#109618' }, 4: { color: '#990099' }, 5: { color: '#3B3EAC' }, }, tooltip: { isHtml: true }, legend: { position: 'labeled' }, is3D: true };
- The options object defines various options for the pie chart.
- title sets the title of the chart.
- pieHole specifies the size of the hole in the middle, creating a donut chart effect.
- pieSliceText specifies that the labels should be displayed on the slices.
- slices specify customization for each slice, including offsets and colors.
- tooltip enables HTML content in tooltips.
- legend positions the legend and labels.
- is3D makes the chart three-dimensional.
chart = new google.visualization.PieChart( document.getElementById('piechart') ); chart.draw(data, options); }
- A new pie chart object is created and assigned to the chart variable, targeting the HTML element with the ID 'piechart'.
- The draw method is called on the chart object, passing the data and options to render the chart.
Adding an Event Listener for Window Resize
window.addEventListener('resize', drawChart);
- This line adds an event listener to the window object, listening for resize events. When the window is resized, the drawChart function is called again to redraw the chart, ensuring it resizes appropriately.
google.charts.load('current', { packages: ['corechart'] });
google.charts.setOnLoadCallback(drawChart);
var chart;
var data;
var options;
function drawChart() {
data = google.visualization.arrayToDataTable([
[
'Brand',
'Market Share',
{ role: 'tooltip', type: 'string', p: { html: true } },
],
['Samsung', 31.2, 'Samsung: 31.2%'],
['Apple', 29.0, 'Apple: 29.0%'],
['Huawei', 12.4, 'Huawei: 12.4%'],
['Xiaomi', 10.3, 'Xiaomi: 10.3%'],
['Oppo', 8.6, 'Oppo: 8.6%'],
['Other', 8.5, 'Other: 8.5%'],
]);
options = {
title: 'Smartphone Market Share - 2025',
pieHole: 0.4,
pieSliceText: 'label',
slices: {
0: { offset: 0.1, color: '#3366CC' },
1: { color: '#DC3912' },
2: { color: '#FF9900' },
3: { color: '#109618' },
4: { color: '#990099' },
5: { color: '#3B3EAC' },
},
tooltip: { isHtml: true },
legend: { position: 'labeled' },
is3D: true
};
chart = new google.visualization.PieChart(
document.getElementById('piechart')
);
chart.draw(data, options);
}
// Add an event listener to redraw the chart when the window is resized
window.addEventListener('resize', drawChart);
Final Output:
See the Pen JavaScript Pie Chart by Faraz (@codewithfaraz) on CodePen.
Conclusion:
Creating pie charts with Loader.js is a straightforward process that offers extensive customization and interactivity. By following this guide, you can create and customize pie charts, and add interactive features. With Loader.js, you can enhance your data presentations and create compelling visualizations that captivate your audience.
That’s a wrap!
I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.
Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee
And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!
Thanks!
Faraz 😊