Biểu đồ cột ngang

Cách tạo biểu đồ cột ngang trong Chart JS. Trong bài viết này, chúng tôi sẽ hướng dẫn cách tạo biểu đồ cột ngang trong Chart JS. Việc tạo biểu đồ cột ngang trong Chart JS không khác biệt nhiều so với biểu đồ cột thông thường. Cơ bản, đó là một biểu đồ cột với góc 90 độ. Xem video này:

Biểu đồ cột ngang trong Chart JS

Biểu đồ cột ngang trong Chart JS

Để tạo một biểu đồ cột ngang, bạn cần hiểu thực sự điều gì xảy ra. Chúng ta sẽ sử dụng không gian tên để đổi giá trị từ trục x sang trục y và ngược lại. Bằng cách đổi chúng, biểu đồ cột thay đổi góc 90 độ. Trục y lấy các nhãn và các cột bắt đầu từ bên trái và di chuyển sang phải tùy thuộc vào giá trị của chúng.

Về cơ bản, đó chỉ là một biểu đồ cột, trong đó các thang đo hoặc trục x và y đã được đổi chỗ. Hiểu điều này sẽ giúp bạn hiểu rõ cách Chart JS hoạt động bên trong.

Trang này có hữu ích không?

2 trả lời trong “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.

Trả lời