Ensure that the bar width in react-chart-js-2 remains consistent regardless of the number of bars displayed

Currently, I am developing a React Chart JS component that displays a set of horizontal bars. My objective is to maintain the width of the bars at a consistent size regardless of the number of bars present (e.g., all bars at 30px).

However, when additional bars are added to the component, the overall bar width adjusts accordingly, which is not my intended outcome.

I attempted to use the "barThickness" option, but when too many bars are added, they end up taking up all the available space and get hidden behind one another (as depicted in this image). As a result, the canvas size shrinks too much, causing negative spacing between the bars when I actually want to keep it positive.

import React from "react";
import {HorizontalBar} from 'react-chartjs-2';
import 'chartjs-plugin-error-bars'
import {withTheme,ThemeProps} from "styled-components";
import { 
    Theme
  } from "@material-ui/core";

...
// The code continues as provided
...

One potential solution could be to adjust the canvas size dynamically based on the number of bars added, but I am unsure how to implement this feature.

Answer №1

If you want to adjust the height of your chart, you can enclose it in a div element and then set the height of that div accordingly:

let DATA_COUNT = Math.max(1, Math.round(Math.random() * 10));
const LABELS = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"];
const data = {
  labels: [],
  datasets: [{
    backgroundColor: "green",
    data: []
  }]
};

const chart = new Chart("chart", {
  type: "bar",
  data,
  options: {
    responsive: true,
    maintainAspectRatio: false,
    indexAxis: "y",
    plugins: {
      legend: false
    },
    layout: {
      padding: {
        top: 10
      }
    }
  }
});

const div = document.getElementById("container");

function update() {
  DATA_COUNT = Math.max(1, Math.round(Math.random() * 10));
  data.labels = [];
  data.datasets[0].data = [];
  for (let i = 0; i < DATA_COUNT; i++) {
    data.labels.push(LABELS[i]);
    data.datasets[0].data.push(i + 1);
  }
  chart.update();
  const scale = chart.scales.x.height;
  div.style.height = 10 + scale + DATA_COUNT * 20 + "px";
}

update();

document.getElementById("update").addEventListener("click", update);
.chart {
  width: 512px;
  height: 256px;
  border: 1px solid black;
  border-radius: 4px;
  margin: 4px;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<button id="update">Update</Button>
<div class="chart" id="container"><canvas id="chart"></canvas></div>

This tip was found in a discussion on this Github issue: https://github.com/chartjs/Chart.js/issues/5409

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

Adjust the scrollbar color when hovering over a particular div

Is there a way to change the color of a div's scrollbar when hovering over the div without assigning an id to it? I've attempted the following methods so far: div:hover { ::-webkit-scrollbar {color: black} } and div:hover + ::-webkit-scroll ...

Preventing the copying and pasting of HTML ruby tags

I am currently using ruby tags to include pinyin in my text. For instance: <p> <ruby>与<rt>yǔ</rt></ruby><ruby>摩<rt>mó</rt></ruby><ruby>拜<rt>bài</rt></ruby><ruby& ...

chart.js version 3 does not display the correct date data on the time axis

Struggling to make chart.js work with a time axis is proving to be quite challenging for me. The code I have is as follows: <html> <head> <script src="https://cdn.jsdelivr.net/npm/moment"></script> <script src="https://cdnjs.clo ...

Moving object sideways in 100px intervals

I'm struggling to solve this issue. Currently, I have multiple div elements (each containing some content) that I need to drag and drop horizontally. However, I specifically want them to move in increments of 100px (meaning the left position should b ...

The CSS styles are failing to be applied to the submit button once it has been

When I have a form with a submit button that triggers a form submission on a PHP page, I want to have an onclick event on the submit button that changes its opacity using JavaScript. The issue I am facing is that after clicking the submit button, the opaci ...

Why Changing the Width of a Flexbox Container Doesn't Impact Its Children?

Attempting to use TweenLite to animate the width of the blue sidebar down to zero, however facing an issue where the content breaks outside the parent's bounds. https://i.stack.imgur.com/4rEVr.png It is unusual for this to happen with Flexbox, given ...

Construct this node project utilizing either gulp or webpack exclusively

In the structure of my project, you will find various folders like node, build, gulp, and src. These folders contain important files for the development process such as .gitignore, gulpfile.js, package.json, tsconfig.json, webpack.config.js, server.js, con ...

Issue with box-sizing border-box not applying to top and bottom borders

Currently, I am in the process of developing my own responsive website. However, I have encountered an issue with the box-sizing border-box on the top and bottom borders of one specific image. The layout consists of two columns with images of varying heigh ...

Create a navigation bar using CSS that is designed from an unordered list without any specific

Is it possible to create a multilevel menu using only CSS for the menu structure mentioned below? Websites like cssmenumaker.com showcase examples of menus with 2-3 level submenus by adding classes like has-submenu. Can we achieve this without adding any ...

Angular controller utilizing the `focusin` and `focusout` events from jQuery

Can anyone help me figure out why this piece of code is generating syntax errors in my AngularJS controller? $(".editRecur").focusin(function() { $(.recurBox).addClass("focus"); }).focusout(function() { $(.recurBox).removeClass("focus"); }); ...

How to Use Vue.js to Find the Nearest Div Element with a Specific

Below is the HTML code I am working with: <div id="app"> <div class="image"> <div class="overlay"> <p>Some overlay text</p> </div> <img src="https://placeimg.com/640/480/any" class="img-fluid"> ...

The PHP on server could not be loaded by Ajax

Trying to establish a PHP connection, encountering an error and seeking assistance. The error message displayed is as follows: { "readyState": 0, "status": 0, "statusText": "NetworkError: Failed to execute 'send' on 'XMLHttpReq ...

Steps to duplicate the package.json to the dist or build directory while executing the TypeScript compiler (tsc)

I am facing an issue with my TypeScript React component and the package.json file when transpiling it to es5 using tsc. The package.json file does not get copied automatically to the dist folder, as shown in the provided screenshot. I had to manually copy ...

When creating utility classes, is it beneficial to offer a non-mutable API to facilitate their integration with frameworks such as React?

Currently, I am working on enhancing the functionality of my DateWithoutTime class. As part of this process, private fields within the class need to be updated by public methods. this.state.dateWithoutTimeInstance.shiftBySpecificDaysCount({ daysCount: 5, ...

Issue with Bootstrap 4 Navbar overlapping content specifically on Apple mobile devices

My bootstrap 4 website () is experiencing an issue with the navbar on Apple mobile devices. On the home page, the navbar doesn't push all the content down, causing some menu items to overlap with the content below. On the "ponentes" page, the content ...

Customize CSS styling

When it comes to the styling of my first line, I have a specific style in mind: * { text-align:left; } This style works well across most parts of the site as they are predominantly left aligned. However, there are few areas where I need the text alig ...

MUI Alert: Encountered an Uncaught TypeError - Unable to access properties of undefined when trying to read 'light' value

After utilizing MUI to create a login form, I am now implementing a feature to notify the user in case of unsuccessful login using a MUI Alert component. import Alert from '@mui/material/Alert'; The code snippet is as follows: <CssVarsProvide ...

Issue with npm install in React cloned repository

I am encountering an issue with my important GitHub repository (tutorial) when I try to clone it and run npm install - npm start. The Terminal displays the following error message: react-scripts start sh: react-scripts: command not found npm ERR! file s ...

Do I have to additionally check the data type using typeof when implementing PropTypes in my code?

I have a custom method called onNotifyChange that is triggered in the onChange event of an input element. This method has been defined with a PropType of func. MyComponent.propTypes = { onNotifyChange: PropTypes.func, } When invoking the onNotifyCha ...

Utilize Bootstrap to display 8 columns side by side on Desktop screens, while on mobile, only display 3 columns

To display logos in 8 columns using Bootstrap 5, I implemented the following code: <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7f1d10100b0c0b0d1e0f3f4a514e514c">[email p ...