Treemap Echarts Dynamic label text

Viewed 33
1 Answers

There are a couple of ways to achieve this. Probably the best way would be to add a labelLayout function to the series. There is an example in the eCharts GitHub repo here. So the series in the provided example would end up looking like this:

      series: [
        {
          name: 'Disk Usage',
          type: 'treemap',
          visibleMin: 300,
          label: {
            show: true,
            formatter: '{b}'
          },
          labelLayout: function (params) {
            if (params.rect.width < 5 || params.rect.height < 5) {
                return {  fontSize: 0  };
            }
            return {
                fontSize: Math.min(Math.sqrt(params.rect.width * params.rect.height) / 10, 20)
            };
          },
          itemStyle: {
            borderColor: '#fff'
          },
          levels: getLevelOption(),
          data: diskData
        }
      ]

alternatively, you could alter the label and add a formatter to be a function and which pipes through rich formatting. In the example, send in the Parameters object and we grab the root element value (total overall Disk Usage from the provided example), then find a ratio of the current value to the total value.

          label: {
            show: true,
            formatter: function (params) {
                let totSize=  params.treePathInfo[0].value;
                let size=(params.value/totSize)*100;
                if (size>8) {
                   return `{l|${params.name}}`
                }
                if (size>2) {
                   return `{m|${params.name}}`
                }
                return `{s|${params.name}}`
            },
            rich: {
              l: {
                fontSize: 20,
              },
              m: {
                fontSize: 15,
              },
              s: {
                fontSize: 10,
              }
            },
          },
Related