Share This:

If you like my work show support on my Patreon
A recent project I’m assigned to involves adding a pie chart to a website. I never needed to make a pie chart for a website before. So I found this to be a great challenge that if I overcame it I would have yet another tool in my toolkit. So I thought about it. I could use an image, however the site is dynamic, so if I went this route I would need to use 1000+ images just for the pie chart. This would slow down the site and not be very practical to do. A more logical route would be to draw the chart dynamically. After some research I came acrossed ChartJS. Which did just what I needed.

In order for me to use ChartJS I would install it using NPM. So on my Linux system I installed NodeJS knowing it would also install NPM.

sudo dnf install nodejs

After I installed NodeJS I would then use NPM to install ChartJS.

npm install chart.js --save

Now ChartJS is on my system. After examining the directory, I found the following.

  • chart.js
  • chartjs-color-string
  • color-name
  • chartjs-color
  • color-convert
  • moment

So the directory we are interested in is the chart.js directory. If navigate into the directory we see the samples->tooltips directory. From there we see our pie chart sample named custom-pie.html. If we open it up in our text editor we will see the code that makes up the chart. However we will only be interested in the following section.

var config = {
type: 'pie',
data: {
datasets: [{
data: [300, 50, 100, 40, 10],
backgroundColor: [
window.chartColors.red,
window.chartColors.orange,
window.chartColors.yellow,
window.chartColors.green,
window.chartColors.blue,
],
}],
labels: [
"Red",
"Orange",
"Yellow",
"Green",
"Blue"
]
},
options: {
responsive: true,
legend: {
display: false
},
tooltips: {
enabled: false,
}
}
};

In this example the chart has five different peaces.

 

The biggest pie slice is 300 the second biggest is 100 and so on. So we can change the data section of the code so it will look like the following.

data: [500, 150, 120, 40, 10],

Now that we have changed the data our chart will look different. Below are the before and after charts.

Because we changed this the pie slices change size. We can add as many slices as we want and give them the values we need. This is great since we can easily put this data into a MySQL Database and output it as JSON data to parse with jQuery.If you like my work show support on my Patreon