Dynamic Barchart Height According to Amount of Data in eChart Menu

Introduction

This tutorial demonstrates how to dynamically adjust the bar chart height based on the amount of data using the Chart Menu (Chart Library = Apache ECharts).

Let's use the image below as an example. 

To make the bar chart height adjust dynamically as the data volume changes, instead of modifying the height directly in the eChart configuration, you can add custom code in the Custom Header of the eChart Menu.

Get started

Configure dynamic height properties

 Bar Chart before changing the height dynamically.

 

Before moving on to the coding part, you'll need to find the chart's ID. This is necessary to change the bar height via JavaScript. To do this, inspect the chart during runtime to locate its ID.

Implementation

Now that we understand our configuration let's write the JavaScript code that will dynamically alter the height of the bar according to the data. You can set this code in the eChart Menu > Advanced > Custom Header.

<script>
 
$(document).ready(function() {
  // Function to calculate the desired height dynamically
  function calculateChartHeight() {
    // Example: Calculate the height based on the window inner height
    return window.innerHeight * 0.8; // Adjust the multiplier as needed
  }
 
  // Dynamically set the height of the chart container div
  var chartContainer = document.getElementById('chart-084C515C911443A28B2579DB41D4BC20');
  if (chartContainer) {
    chartContainer.style.height = calculateChartHeight() + 'px'; // Set the height dynamically
  }
   
  // Optional: Adjust the height on window resize
  window.addEventListener('resize', function() {
    if (chartContainer) {
      chartContainer.style.height = calculateChartHeight() + 'px'; // Set the height dynamically on resize
    }
  });
});
</script>

Expected outcome

After implementing the code, the bar chart will dynamically adjust its height based on the data amount.

Troubleshoot

If you face, issues like the bars in the chart are overlapping due to a large dataset.

This occurs when the barWidth is set as an absolute value in the eChart config (eChart Menu → Properties → Additional Customization) causing bars to remain fixed regardless of the chart's dimensions. For example, the setting barWidth: 10 can cause overlap.

Adjust the barWidth to a percentage value will solve this issue. When using a percentage such as '70%', the width adapts to the chart's available space, preventing overlap.

barWidth:'70%',

Download sample app

Download the demo app for Dynamic Barchart Height According to the Amount of Data in eChart Menu:
 
Created by Julieth Last modified by Aadrian on Nov 22, 2024