2
votes

In pie echarts, normally when I hover the mouse on a slice I can see the series name, value, percent and ..., But when the mouse is on the legend the slice is only selected and comes a little up. I would like to see the information also when the mouse is on the name of a slice in the legend part.

https://www.echartsjs.com/examples/en/editor.html?c=pie-simple

Thanks.

1

1 Answers

2
votes

You need to customize the tooltip in legend with your own format as mentioned in

https://www.echartsjs.com/en/option.html#tooltip.formatter

You can use function (params) under legend.tooltip.formatter

However params only contains the below values:

{
  "componentType": "legend",
  "legendIndex": 0,
  "name": "直接访问",
  "$vars": [
    "name"
  ]
}

Therefore I used a find function to get the corresponding data .

tooltip: {
      trigger: 'item',
      formatter: function(params) {
        let datum = mydata.find(d => d.name == params.name)
        return '' + datum.name + ' : ' + datum.value + ' (' + (datum.value / sum * 100).toFixed(2) + '%)';
      },
      show: true
    }

let myChart = echarts.init(document.getElementById('myChart'));

const mydata = [
  {value: 335, name: '直接访问'},
  {value: 310, name: '邮件营销'},
  {value: 234, name: '联盟广告'},
  {value: 135, name: '视频广告'},
  {value: 1548,name: '搜索引擎'}
];

const sum = mydata.reduce(function(prev, current) {
  return prev + current.value
}, 0);

let myChartOption = {
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    left: 10,
    tooltip: {
      trigger: 'item',
      formatter: function(params) {
        let datum = mydata.find(d => d.name == params.name)
        return '' + datum.name + ' : ' + datum.value + ' (' + (datum.value / sum * 100).toFixed(2) + '%)';
      },
      show: true
    }
  },
  series: [{
    name: '访问来源',
    type: 'pie',
    radius: ['50%', '70%'],
    avoidLabelOverlap: false,
    label: {
      normal: {
        show: false,
        position: 'center'
      },
      emphasis: {
        show: true,
        textStyle: {
          fontSize: '30',
          fontWeight: 'bold'
        }
      }
    },
    labelLine: {
      normal: {
        show: false
      }
    },
    data: mydata
  }]
};

myChart.setOption(myChartOption);
#myChart {
  width: 100%;
  min-height: 330px;
  margin: 0 auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/4.6.0/echarts.min.js"></script>
<div id="myChart"></div>