Search code examples
javascriptchart.jsecharts

Apache eCharts - custom width in bar chart


I'm migrating from chartjs to apache echarts.

Previously, I had this bar chart, where two datasets are present for each year. The requirement asked by our client is that, whenever a value is zero, the remaining bar should have all the space in the bin.

bar chart done with chartjs

How can I achieve this with echarts? Is using a custom dataset the only option?


Solution

  • You could split your data into 4 series:

    1. Only data of dataset 1 present
    2. Only data of dataset 2 present
    3. Dataset 1 data when both are present
    4. Dataset 2 data when both are present

    Now you define a second xAxis with show: false such that series 1,2 and series 3,4 share one xAxis and make use of barGap to overlap bars on the same axis.

    Example:

    option = {
      xAxis: [
        {
          type: 'category',
          data: ['2012', '2013', '2014', '2015', '2016']
        },
        {
          type: 'category',
          show: false,
          data: ['2012', '2013', '2014', '2015', '2016']
        }
      ],
      yAxis: [
        {
          type: 'value'
        }
      ],
      series: [
        {
          name: '1',
          type: 'bar',
          barGap: '-100%',
          data: [120, 0, 0, 0, 0]
        },
        {
          name: '2',
          type: 'bar',
          data: [0, 0, 0, 330, 370]
        },
        {
          name: '1',
          type: 'bar',
          xAxisIndex: 1,
          barGap: 0,
          data: [0, 232, 270, 0, 0]
        },
        {
          name: '2',
          type: 'bar',
          xAxisIndex: 1,
          data: [0, 180, 270, 0, 0]
        }
      ]
    }