Last Updated on August 12, 2024 by E. Scott
Over the years I’ve built numerous Chartjs bar charts. Used in analytics, data driven UIs, displaying server status’, and many other use cases. This time however I decided to build one just for fun.
This Chartjs bar chart shows mock quarterly data powered via JSON. Each button loads new data indicative of a payload. Data is accessible by hovering over each bar and displayed in the table below. Touch is enabled on mobile.
Table of Contents
My Data Visualization Experience
I wasn’t able to build this custom line chart until I had experience building and customizing rudimentary Chartjs bar charts. Upon which I rapidly discovered data visualization is a very complex sub category of frontend development.
Isn’t it wild there’s so many sub categories inbuilt to frontend development?
Responsive UIs with React, Angular, and Vue. Data visualization. Speed and performance. Mobile apps with Flutter, etc. Email development. Rich media development. The list goes on.
I developed this mock simply for more practice passing around realtime data streams to multiple components. Clicking on a row in the table below updates the chart data. See it in action right here. This was a great exercise in data visualization working with numerous components in TypeScript.
This next sample below is a home page of an absolutely massive single page app I developed. And it was loaded with a wide array of data visualizations. Area charts, bar and line charts, scatter and bubble charts. Making things more complex was customizing the design, updating a tremendous amount of data on click (regardless of how fast clicks were), and reloading the chart on window resize.
The next one was made with D3. This too was a mock I created for more experience before the need arose. Similar case for this multi element drag and drop. Built many of the features as I knew I’d be given the job.
D3 is an entirely different ball game than a Chartjs bar chart. It’s exceptionally complex and none of the principles from other libraries carry over.
There’s undoubtedly others I’ve developed, but you get the idea. I’ve created an abundance of these. They can tedious and require a specialized set of knowledge.
ChartJS Bar Chart
The code isn’t too bad if you’re equipped from a JavaScript background. The data interface mocks each bar as shown below. Interfaces or models are used throughout languages and frameworks. They’re blueprints of the data. It’s the “type” in TypeScript.
export interface BarInterface {
lable: string;
data: Array<number>;
backgroundColor: string;
}
Data is not complex whatsoever. Take a look at this sample shown below. You can even make changes and see the results take effect immediately of course.
[
{
"label": "IT",
"data": [62, 145, 95],
"backgroundColor": "#34568B"
},
{
"label": "CR",
"data": [70, 60, 20],
"backgroundColor": "#FF6F61"
},
{
"label": "PR",
"data": [714, 695, 972],
"backgroundColor": "#6B5B95"
},
{
"label": "ROI",
"data": [200, 90, 150],
"backgroundColor": "#88B04B"
}
]
In the actual class, I declare the variables. Then in OnInit, initialize the canvas, load the data, and let ChartJS work its magic. This is accomplished by configuring the options. Responsiveness, legend, padding, axes, and type.
The loadData function on line 66 populates the data array with the appropriate values.
Then there’s a render method on line 82 that rerenders the graph when it’s resized. I believe the only other thing that was done was changing a setting in tsconfig.json (“resolveJsonModule”: true). Something which I don’t believe is necessary in later versions. But just an FYI.
export class AppComponent implements OnInit {
dataArray: BarInterface[] = [];
data: any;
chart: any;
quarter: string = 'Q1';
q1: any = chartData;
q2: any = q2;
q3: any = q3;
q4: any = q4;
ngOnInit() {
let options: any,
ctx: any = document.getElementById('areaChart') as HTMLElement;
ctx.style.backgroundColor = '#FFFFFF';
this.loadData(null, this.quarter);
this.data = {
labels: ['Chicago', 'London', 'Frankfurt'],
datasets: this.dataArray,
};
options = {
responsive: false,
legend: {
display: false,
},
layout: {
padding: 15,
},
scales: {
xAxes: [
{
stacked: true,
gridLines: {
display: true,
},
ticks: {
display: true,
fontSize: 12,
},
},
],
yAxes: [
{
stacked: true,
gridLines: {
display: true,
},
ticks: {
display: true,
fontSize: 12,
},
},
],
},
};
this.chart = new Chart(ctx, {
type: 'bar',
data: this.data,
options: options,
});
}
loadData(arr: any, span: any) {
this.dataArray = [];
this.quarter = span;
arr === null ? (arr = chartData) : '';
for (let key in arr) {
if (arr.hasOwnProperty(key)) {
this.dataArray.push(arr[key]);
}
}
if (arr != null && this.data != undefined) {
this.data.datasets = this.dataArray;
this.chart.update();
}
}
// Refresh canvas dimensions
onResize(event: any) {
this.chart.render();
}
}
Note however. This has not been updated to version 3.0 and will not work in later versions of Angular. I work with native TypeScript so library versions don’t apply. But of course updates often involve security patches vs solely features. I have not looked at the updates though.
My posts are meant for learning and ideation vs copy-paste. Though I welcome either. V2 or V3—Chartjs is an amazing library and one in which I’ve really enjoyed using. Once you wrap your head around the concepts, it’s a pleasure to use in a most applications. I’ve used this in both Angular, vanilla JS, and React. For a more interactive project sample, check out this one.
To see more fully developed projects similar to this one, visit my projects page. Anywho. I hope you find this useful, can implement it, or simply think it’s educational. Regardless, please see a working version of Chartjs Bar Chart UI on Stackblitz here.
Leave a Reply