How to create a horizontal bar in Chart JS. In this post we will cover how to create a horizontal bar chart. Creating a horizontal bar chart in Chart JS is not that much different compare to a bar chart. In essence it is a bar chart with a 90 degree angle. Watch this video:
Horizontal Bar Chart in Chart JS
To make a horizontal bar chart you will need to understand what actually happens. We will use the namespace indexAxis to swap the values from the x-axis to the y-axis and visa verse. By swapping them the bar chart basically changes at an angle of 90 degrees. The y-axis get the labels and the bars start a the left and move to the right depending on their values.
So in essence it is just a bar chart where the x and y scales or axis has been switched. Know this gives you a clear picture how Chart JS works under the hood.
2 replies on “Horizontal Bar Chart”
Hi, I’ve been following your videos on youtube for quite some time and I have to say they are quite helpful, thank you. I’m just wondering, is it possible to fix the bar size on a single horizontal stacked bar so long as the difference from i+1 and i is the same? Let’s say we have a dataset of 20 values from 10 to 200, obviously i+1 -i is a difference of 10 for all values. So plotting it on a stacked horizontal bar, I want it to maintain fixed bar size. What’s happening at the moment is the bars start out thinner and eventually increase in size despite being the difference.
Hi James, thank you for your kind words. Regarding to your question if I understand it correctly is as you add more bars the bars are becoming thinner. In essence they have to become narrow due to the fixed size in the canvas.
I’m not sure if you are familiar with how the chart js canvas calculates height and width. But in your case how it is build is working against to what you want to achieve. While might have some idea but not sure if it work. I will make a video about this.
But here is currently my speculation:
1. Disable the maintainAspectRatio settings in Chart JS. This is your core issue working against your desired result.
2. The height of your canvas should have a min height but also a dynamic height based on how many horizontal bars you have. This could be achieves with the JS arrays as we can read the JS objects of Chart JS. That needs to be a height formula that would work once the min-height would be surpassed.
For example: height = each bar * 20px.
I will explore this and once I have the answer post a video about this and notify you as well.