Skip to content Skip to sidebar Skip to footer

Reduce Space Between Ticks In Horizontal Bar-chart Chartjs

I am using the horizontal bar chart from chartjs. Right now my Chart seems to be very big, and the space between the ticks on the xAxis is very high. ( I attached picture of that),

Solution 1:

If you post your corresponding HTML then I can confirm this, but is #myChart the id of your canvas element or of a div that contains your canvas element?

Chart.js will render the chart such that it fully fills the parent of the canvas element. Even if you set a width property on a canvas element it will still not affect the chart size.

Checkout this codepen example that demonstrates the difference. At the top is a chart contained by a div whose width is set to 40%. At the bottom is the same chart but the canvas element's width is set to 40%. Notice that the second chart still fills the entire window.

So long story short, you should wrap your canvas element in a div and set the div's desired size accordingly to actually change the size of your chart.

Now, let me address your question about changing the space between ticks in your X axis. There is not really a way to truly do this like I think you are wanting to do, because chart.js determines the tick placement by dividing the width of the chart by the number of tick steps (e.g. it always uses the full width of the chart equally).

So one way to decrease the space between ticks is to simply add more ticks (by changing the tick stepSize using the stepSize and fixedStepSize properties). Obviously, in this case, the chart size has not changed. You are just showing more ticks, so the space between them has decreased.

If you want to truly change the distance between ticks, then the only way is to decrease the width of the chart. But by default, the height of the chart will decrease along with the width because the maintainAspectRatio property is defaulted to true.

So if you want a narrower chart (but still want the chart to be large) then I would advise you to set the maintainAspectRatio property to false and manually set the height and width of your chart's parent div.

Checkout this codepen that gives an example of each of the tick spacing concepts that I discussed.

The first chart is the baseline, the second chart adds more ticks (thus decreasing the tick spacing), and the third chart changes the aspect ratio so the chart is still large but narrower (therefore the distance between ticks is reduced).

Solution 2:

Try using chartArea: {width: '30%'}. Adjust percentage as per requirement. It will compress the width of the chart. Just a thought !!!! I used in horizontal bar graphs to adjust my graph size.

Post a Comment for "Reduce Space Between Ticks In Horizontal Bar-chart Chartjs"