Have series label displaying only once per series in eCharts

落爺英雄遲暮 提交于 2021-01-29 19:21:33

问题


I'd like to show a label per series in my echarts chart, to make it a little easier to read than if I had a separate legend and color-coded the series. However it's not obvious to me how to achieve that - if I set series.label.show = true, then I get a label per data point:

Is there a way to just have a single label, at the very right of these series? I have been tweaking around with the series-line.label but it is not obvious to me how to achieve this.

Thanks for any help!


回答1:


You can try to limit the number of labels with formatter (change divider in the labelFilter) and fix the overlap with textBorderWidth. See example below.

P.S. Also you can fine-grained control the labels but it's not quite simple.

var myChart = echarts.init(document.getElementById('main'));
var sequence = () => Array(Math.round(Math.random() * (10 - 5) + 5)).fill().map(() => Math.sqrt(Math.random() * 100));
var labelFilter = (obj) => obj.dataIndex % 3 === 0 ? obj.data : '';

var option = {
  tooltip: {},
  legend: {
    data: ['Label']
  },
  xAxis: {
    data: ["Category1", "Category2", "Category3", "Category4", "Category5", "Category6"]
  },
  yAxis: {},
  series: [{
      name: 'Series1',
      stack: 'y',
      type: 'line',
      data: sequence(),
      step: true,
      color: 'green',
      label: {
        show: true,
        formatter: labelFilter,
        position: [10, 30],
        distance: -30,
        textBorderWidth: 2,
        textBorderColor: 'white',
      },
    },
    {
      name: 'Series2',
      stack: 'y',
      type: 'line',
      data: sequence(),
      step: true,
      color: 'blue',
      label: {
        show: true,
        formatter: labelFilter,
        position: [10, -30],
        distance: 30,
        textBorderWidth: 3,
        textBorderColor: 'white',
      },
    },
  ]
};

myChart.setOption(option);
<script src="https://cdn.jsdelivr.net/npm/echarts@4.8.0/dist/echarts.min.js"></script>
<div id="main" style="width: 600px;height:400px;"></div>


来源:https://stackoverflow.com/questions/63069291/have-series-label-displaying-only-once-per-series-in-echarts

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!