Galya Ts.
Galya Ts.

Reputation: 21

Echarts bar chart is filling from 0 when the x-axis data changes

I'm using echarts 5.4.0 I want to use echarts bar chart as a historical chart, meaning the x-axis data should change on every 5 seconds. The x-axis data consists of dates

The issue I'm facing is that every time when the x-axis data is changing the bars are getting filled from the beginning. What I would expect is their filled part to be changed, not starting from zero every time, but from the value it's been before the change. I've checked how it's been working on v4 and it seemed to not have this problem. Please see the attached gif, paying attention on the changing x-axis data and the way the bars are drawn from 0. enter image description here

I'm using the very basic echarts bar chart example:

option = {
  xAxis: {
    type: 'category',
    data: ['14:57:51', '17:57:51', '20:57:51', '23:57:51', '02:57:51', '05:57:51', '08:57:51', '11:57:51']
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      data: [120, 200, 150, 80, 70, 110, 130, 90],
      type: 'bar'
    }
  ]
};

I will be very thankful for any suggestions or advise on how I can achieve the behavior I want and the bars values are not reset from zero every time.

Upvotes: 0

Views: 1400

Answers (1)

kikon
kikon

Reputation: 8890

The full redraw with animation from zero is due to the change of the x axis labels. If only the series data values are updated, not the labels, it animates only the difference.

So a possible solution is to update the x axis labels separately, with no animation, and then update the data values in another call to setOption, this time with animation enabled.

const data = [120, 200, 150, 80, 70, 110, 130],
    newXData = () => Array.from({length: data.length},
        ()=> '' + Math.floor(1000*Math.random()));
const chartDom = document.getElementById('chart');
const myChart = echarts.init(chartDom);
const option = {
    xAxis: {
        type: 'category',
        data: newXData()
    },
    yAxis: {
        type: 'value'
    },
    series: [
        {
            data,
            type: 'bar'
        }
    ]
};
myChart.setOption(option);

setInterval(function(){
    const newData = Array.from(
        {length: data.length},
        () => Math.floor(Math.random()*25) * 10
    );
    myChart.setOption({ // update x labels, no animation
        xAxis: {data: newXData()},
        animation: false
    });
    myChart.setOption({ // update series, animation
        series:[{data:newData}],
        animation: true
    });

}, 2000);
<div id="chart" style="min-width: 300px;height: 80vh"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/5.4.1/echarts.min.js"></script>

Upvotes: 0

Related Questions