Decrease the gap between the ticks on a horizontal bar chart in ChartJS

Currently, I am utilizing the horizontal bar chart feature from chartjs and encountering an issue with the chart appearing too large. In addition, there is a notable gap between the ticks on the xAxis (as shown in the attached image). Does anyone know how I can adjust this spacing to better scale the chart overall?

Here are my CSS properties:

#myChart {
  width: 90% !important;
  height: 100% !important;
  padding-left: 0;
  padding-right: 0;
  margin-left: auto;
  margin-right: auto;
  display: block;
  padding-bottom: 5%;
}

And here are my chart options:

modelChart = new Chart(ctx, {
      type: 'horizontalBar',
      data: data,
      options: {
        scales: {
          yAxes: [{
            ticks: {
              suggestedMin: 0,
              fontSize: 18
            }
          }],
          xAxes: [{
            ticks: {
              autoSkip: false,
              fontSize: 18,
              beginAtZero: true
            }
          }]
        },
        legend: {
          display: false
        },
        tooltips: {
          footerFontSize: 22,
          bodyFontSize: 22,
          titleFontSize: 18
        },
        hover: {
          animationDuration: 0
        }
      }
    });

https://i.sstatic.net/2wC4J.png

Answer №1

Could you please provide the HTML corresponding to your post? I need to verify if #myChart is the ID of your canvas element or a parent div containing the canvas element.

When using Chart.js, the chart will be rendered to fill the entire area of the parent canvas element. Even if you specify a width for the canvas, it will not affect the size of the chart itself.

You can see a demonstration of this behavior in this codepen example. The first chart is within a div set to 40% width, while the second chart has the canvas element directly set to 40% width, yet both charts render at full window size.

To adjust the size of your chart, wrap the canvas element in a div and set the dimensions of the div accordingly.

Regarding decreasing the space between ticks on the X axis, Chart.js determines tick placement based on dividing the chart width by the number of ticks. You can add more ticks with the stepSize and fixedStepSize properties to reduce spacing, but this won't change the overall chart size.

If you want to truly alter tick spacing, you'd need to decrease the chart width; however, the height will also change unless you disable the maintainAspectRatio property and manually set dimensions on the parent div.

For examples of different tick spacing techniques, check out this codepen. The first chart is standard, the second increases ticks (reducing spacing), and the third adjusts the aspect ratio for a narrower chart with decreased tick distance.

Answer №2

Experiment with the chartArea property by setting width to '30%'. You can customize the percentage as needed to decrease the width of the chart. I found this useful when working with horizontal bar graphs to resize my graph. Just a helpful tip for you!!!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Trouble with Material-UI DataGrid: Column headers are being cut off

I am facing an issue where my column names are getting cut off even though they should fit in the available space. https://i.sstatic.net/kmKFi.png ...

The scrolling event on the div is not triggering

I'm struggling with this piece of code: const listElm = document.querySelector('#infinite-list'); listElm.addEventListener('scroll', e => { if(listElm.scrollTop + listElm.clientHeight >= listElm.scrollHeight) { th ...

Exploring your favorite Instagram photos using the Angular framework

Trying to access the JSON data of an Instagram user's liked media, the documentation suggests using this URL: More information can be found at: I have replaced the ACCESS-TOKEN with my own as instructed below: (function(){ var app = angular.m ...

Are JSON-Web Tokens (JWTs) used for both verifying identity and granting access privileges?

Currently, I am exploring the process of developing a blog website that permits users to log in and perform tasks such as editing or deleting their own blogs based on their user role. If a different user logs in and does not own a particular blog, they s ...

Angular does not support fetching JSON files

update: The code has been modified to include the latest suggestions provided by you all. I've got this data.json file: [{ "codigo": 21420, "desc": "itv orion 20 a", "prod_24_h_kg": 22 }, { "codigo": 21421, "desc": "itv orion 20 w", "prod_24_h_kg": ...

Having trouble figuring out the reason my JavaScript code isn't functioning properly. Any ideas?

Just starting out with javascript and running into an issue, This snippet of code seems to be working as expected: function test(args){ return "12345 - "+args; } console.log(test("678910")); However, this other piece of code is ...

To enable the standard PayPal 'donate' button functionality, you can remove the submitHandler from jQuery Validate dynamically

I need to insert a PayPal donate button into the middle of an AngularJS donation form, specifically by nesting the PayPal generated form tags within the donation form tags. This donation form is utilizing an older version (1.12) of jQuery Validate, which ...

Are there any functions that work with an array of objects?

Is there a way to use includes function to check if an object is inside the array, as shown below: arr=[{name:'Dan',id:2}] When trying to check with includes like this: arr.includes({name:'Dan',id:2}) The result returned is false. I ...

Issues with radio buttons not functioning or being able to be selected in Internet Explorer

My radio buttons are functioning perfectly in Chrome, Firefox, and Safari, but for some reason, they are not selectable in Internet Explorer (Version 7). Any suggestions on how I can resolve this issue? HTML: <label> <input type="radio" name ...

How come my uploaded Excel Javascript add-on opens in an external browser instead of the task pane?

Note: It has come to my attention that I must save the taskpane.html file on my local drive before it opens in an external browser. This detail slipped my notice last week. I am currently developing a Javascript, or rather Typescript, API add-in for Excel ...

Cease the execution of processes once a Promise has been rejected

My current code is functioning correctly, but I am facing an issue where if an error occurs, I want it to halt all other promises in the chain. Specifically, when chi.getCommand(val1, val2) returns a reject and triggers the exception catch block, I need to ...

Shifting an item to a specific location using three.js

I'm attempting to fire bullets or projectiles utilizing three.js: let renderer, camera, scene, light, plane, cube, spheres; initialize(); animate(); function initialize() { renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true }); ...

Console log is not displaying the JSON output

I am currently working on implementing a notification button feature for inactive articles on my blog. I want to ensure that the admin does not have to reload the page to see any new submitted inactive articles. To achieve this, I am looking to use Ajax, a ...

AngularJS function orderBy reverses the array instead of sorting it

I encountered an issue where, after clicking the 'order button', the table does not order as expected. Instead, it reverses all the td elements. For example, 'A', 'C', 'B' becomes 'B', 'C', "A". I ...

The element is implicitly assigned an 'any' type due to the fact that an expression of type 'any' cannot be used to index types in nodejs and solidity

I am in need of setting networks in my contract using NodeJS and TypeScript. Below is the code I have written: let networkId: any = await global.web3.eth.net.getId(); let tetherData = await Tether.networks[networkId]; Unfortunately, I encountered ...

Deleting an item in Vue.js with the removal feature

After deleting items from my list, they remain visible until I manually refresh the page. How can I fix this issue? List <tbody> <tr v-for="school in schools" v-bind:key="school.id"> <td>{{ school.id }}</td> &l ...

Utilizing jQuery to update dropdown selection based on JSON object values

In my JSON value, I have the following roles: var roles = { "roles":[ {"role_id":2,"role_name":"admin"}, {"role_id":4,"role_name":"QA"}, {"role_id":3,"role_name":"TL"}, {"role_id":5,"role_name":"user"}, {"role_id":1,"role_name":"r ...

jQuery struggles to locate the active class within the Bootstrap slider

Want to make some changes to the Bootstrap slider? Here is the HTML Code and jQuery: <div id="carousel-slider2" class="carousel slide bs-docs-carousel-example"> <ol class="carousel-indicators"> & ...

Is it possible to implement a feature in Angular and Bootstrap where the toggle menu can be closed by clicking anywhere on the page, rather than just the toggle button

I'm working on an Angular project where I've implemented a navbar component. The navbar is responsive and includes a toggle button that appears when the browser window is resized. This button allows users to hide or display the menus. One issue ...

What is the process for obtaining Style.css, additional CSS, and JavaScript files from a live single page website?

I am currently facing a challenge with a live single page website where I need to make some fixes. Unfortunately, I am unable to access the Style.css file, along with other css and javascript files. Although I managed to save the html file by using Ctrl+s, ...