Chartjs-ChartJS: problem with height when data size is too small

0👍

You set the property maxBarThickness in your dataset, this prohibits the bar from becoming wider.

You either need to remove this property or change the size of the canvas so your bars are getting closer to eachother.

0👍

try barPercentage: 1
for setting the gap of bars

0👍

Okay, I finally bit this. Maybe, this solution isn’t good and, of course, you can improve it, but it works for my case:

 <Box>
  <Box className={classes.chartBoxWrapper}>
    <Box className={classes.chartBox}>
      {barChartData && options && dataSize > 0 && (
        <Bar options={options} data={barChartData} />
      )}
    </Box>
  </Box>
  {dataSize > 10 && (
    <Box position="relative">
      <Box className={classes.shadowBox}></Box>
    </Box>
  )}
</Box>

and CSS:

chartBox: {
  borderRadius: '9px',
  height: ({ dataSize }: { dataSize: number }) => {
    if (dataSize === 0) {
      return '40px';
    } else {
      return `${dataSize * (40 - dataSize / 3)}px`;
    }
  },
},

chartBoxWrapper: {
  height: ({ dataSize }: { dataSize: number }) => {
    if (dataSize === 0) {
      return '40px';
    } else if (dataSize > 10) {
      return '315px';
    } else {
      return `${dataSize * (40 - dataSize / 4)}px`;
    }
  },
  overflowY: ({ dataSize }: { dataSize: number }) =>
    dataSize > 10 ? 'scroll' : 'initial',
},

shadowBox: {
  position: 'absolute',
  bottom: -3,
  left: 0,
  right: 0,
  background: 'linear-gradient(0deg, #232323 0%, rgba(35, 35, 35, 0) 100%)',
  height: '35px',
},

I just dynamically increase chart height and when size is greater than 10, simply add overflow and set fixed height = 315px.

Leave a comment