Search code examples
javascriptreactjspie-chartecharts

Echart configuration for Pie legends in a particular way


I want to display pie legends along with its value in a different format. I am attaching the image. I am looking for it but did not find how to do it till now. If you see the image, legends and the value corresponding to it are shown that i am unable to replicate.

Pie legends


Solution

  • You want to display value instead percentages? If yes then this is a little work that need to do because by default legend component don't know about another dimensions of you data. Try to start with this code:

    var option = {
      //...
      legend: {
        formatter: name => {
          var series = myChart.getOption().series[0];
          var value = series.data.filter(row => row.name === name)[0].value
          return name + '    ' + value;
        },
      }
    }
    

      var myChart = echarts.init(document.getElementById('main'));
      var option = {
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
            orient: 'vertical',
            left: 10,
            data: ['Category1', 'Category2', 'Category3', 'Category4', 'Category5'],
            formatter: (name) => {
    	        var series = myChart.getOption().series[0];
          		var value = series.data.filter(row => row.name === name)[0].value;
          		return name + '    ' + value;
            },
        },
        series: [
            {
                name: 'Series',
                type: 'pie',
                label: { show: false },
                labelLine: { show: false },
                data: [
                    {value: 335,  name: 'Category1'},
                    {value: 310,  name: 'Category2'},
                    {value: 234,  name: 'Category3'},
                    {value: 135,  name: 'Category4'},
                    {value: 1548, name: 'Category5'}
                ]
            }
        ]
    };
    
    
    myChart.setOption(option);
    <script src="https://cdn.jsdelivr.net/npm/echarts@4.7.0/dist/echarts.min.js"></script>
    <div id="main" style="width: 600px;height:400px;"></div>