Como criar um gráfico de barras horizontal no Chart JS. Neste post, vamos cobrir como criar um gráfico de barras horizontais. Criar um gráfico de barras horizontais no Chart JS não é muito diferente de criar um gráfico de barras padrão. Essencialmente, é um gráfico de barras com um ângulo de 90 graus. Assista a este vídeo:
Gráfico de Barras Horizontal no Chart JS
Para criar um gráfico de barras horizontais, você precisará entender o que realmente acontece. Vamos usar o namespace indexAxis para trocar os valores do eixo x para o eixo y e vice-versa. Ao trocá-los, o gráfico de barras basicamente muda em um ângulo de 90 graus. O eixo y recebe os rótulos e as barras começam à esquerda e se movem para a direita, dependendo de seus valores.
Portanto, essencialmente, é apenas um gráfico de barras onde as escalas ou eixos x e y foram trocados. Saber disso lhe dá uma imagem clara de como o Chart JS funciona por baixo dos panos.
2 respostas em “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.