1

I have an Echarts line chart that has multiple series/lines across a timespan and would like to add options to include an average and/or total lines. I don't see anything built-in that would do that but figured I'd ask before I reinvent the wheel and do the calculations myself and just add them as another series.

Echart's line series has a markLine option that can show the average for that singular series but that would lead to multiple flat lines for each data line. That's not what I want, I want the average across all series.

Bryan Dam
  • 23
  • 5

1 Answers1

1

In general it's not possible because markLine exists on series context only but you can make hidden addition series consist of average values from the all another series and result will be the same as you want.

For example:

var data = {
  series01: [7, 7, 4, 5, 8, 2, 3, 5, 5, 9, 4, 3, 5, 9],
  series02: [4, 9, 4, 5, 8, 4, 1, 2, 2, 6, 5, 4, 8, 3],
  series03: [9, 6, 2, 4, 8, 3, 5, 4, 3, 7, 1, 2, 3, 9],
}

var seriesData = function(data) {
  return Object.keys(data).map(key => {
    return {
      id: key,
      data: data[key],
      type: 'bar'
    }
  })
};

var option = {
  xAxis: {
    data: ["c01", "c02", "c03", "c04", "c05", "c06", "c07", "c08", "c09", "c10", "c11", "c12", "c13"],
    type: 'category',
  },
  yAxis: {
    type: 'value'
  },
  tooltip: {},
  series: seriesData(data),
};

var myChart = echarts.init(document.getElementById('main'));
myChart.setOption(option);

/* Calculate average series data */
var avrSeriesData = function(data) {
  values = Object.values(data);
  transposed = values[0].map((r, i) => values.map(c => c[i]));
  avrByRow = transposed.map(row => {
    var rowSum = row.reduce((a, b) => a + b);
    return Math.round(rowSum / row.length);
  });
  return avrByRow
};

var avrSeries = {
  id: 'avrSeries',
  type: 'bar',
  data: avrSeriesData(data),
  barWidth: 0.1,
  barGap: 0.1,
  barCategoryGap: 0.1,
  color: 'transparent',
  markLine: {
    show: true,
    data: [{
      name: 'average line',
      type: 'average'
    }],
    lineStyle: {
      color: 'red'
    },
  }
};

myChart.setOption({
  series: avrSeries
});
<div id="main" style="width: 600px;height:400px;"></div>
<script src="https://cdn.jsdelivr.net/npm/echarts@5.0.0/dist/echarts.min.js"></script>
Sergey Fedorov
  • 3,696
  • 2
  • 17
  • 21
  • 1
    Thanks for confirming @Sergey. There's a lot of docs for echarts and just wanted to make sure I wasn't missing something and didn't have to calculate the series myself. Thanks for the PoC as well, that's good stuff. – Bryan Dam Dec 04 '20 at 01:00