Search code examples
javascripthighchartsheatmapreact-highcharts

How to prevent the columns to stretch up to the size of the whole chart if less data is provided?


I dont display static data and as such the size of the data varies. I show data for each month (xAxis) and year (yAxis). When the data only fills one row (lets say I have January-December) for only 2024, then the colums stretch up to the end of the chart. How can I prevent that, so the cells stay same size?

An example of what I mean: https://jsfiddle.net/J_Code_2025/du97b4ka/2/

The code:

$(function () {
    $('#container').highcharts({
        chart: {
            type: 'heatmap',
            marginTop: 40,
            marginBottom: 80,
            plotBorderWidth: 1
        },
        title: {
            text: 'Sales per employee per weekday'
        },
        xAxis: {
            categories: ['Alexander', 'Marie', 'Maximilian', 'Sophia', 'Lukas', 'Maria', 'Leon', 'Anna', 'Tim', 'Laura']
        },
        yAxis: {
         tickWidth: 1,
        tickLength: 0,
            categories: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'],
            title: null
        },
        colorAxis: {
            min: 0,
            minColor: '#FFFFFF',
            maxColor: Highcharts.getOptions().colors[0]
        },
        series: [{
            name: 'Sales per employee',
            borderWidth: 4,
            data: [
                [0, 0, 10],
                ...
            ],
            dataLabels: {
                enabled: true,
                color: '#000000'
            }
        }]

    });
});

Solution

  • Based on your data, you can use dynamically calculated yAxis.height yAxis.top. For example:

      const rowsAmount = new Set(data.map(dataEl => dataEl[1])).size;
      const plotHeight = 280;
      const rowHeight = 58;
      const axisHeight = rowHeight * rowsAmount;
    
      Highcharts.chart('container', {
        yAxis: {
          ...,
          height: rowHeight * rowsAmount,
          top: ((plotHeight - axisHeight) / 2 * 100 / plotHeight) + '%'
        },
        ...
      });
    

    Live demo: https://jsfiddle.net/BlackLabel/5jomLca8/

    API Reference: https://api.highcharts.com/highcharts/yAxis.height