一、饼图图例的排列方式
1.引入饼图
这一步大多数应该都会,官网有例子,直接cv就可以用,简单提一下吧
<template> <div class="box"> <div id="mycircle"></div> </div> </template> <script> export default { data(){ return{ option: { tooltip:{}, legend:{}, series:[], ...... } } }, methods:{ async init(){ var myChart = this.$echarts.init(document.getElementById('mycircle')); myChart.setOption(this.option); myChart.clear(); await getIndex7DayException().then(data => { // data返回值格式就是[{name: '', value: ''}],有且只能是name和value这两个key,其他都不行 // 如果返回值是其他的,那就需要转化一下了 data.map(v =>{ let keymap = {count: 'value',areaName: 'name'} // 将count字段转成value字段,areaName字段转化成name字段 Object.keys(v).map(k =>{ let newKey = keymap[k] if (newKey) { v[newKey] = v[k] delete v[k] } }) }) this.option.series[0].data = data; myChart.setOption(this.option); window.addEventListener("resize", () => { myChart.resize() }); } } }, mounted(){ this.init() } } </script>
到这为止,图表就可以正常显示了,下面开始自定义图例的排列方式
2.水平顶部(底部)排列
top: 0
bottom: 0
示例代码:
legend:{ top: '0', //bottom: '0' textStyle: { color: '#fff'}, }
3.垂直左右排列
垂直属性: orient: ‘vertical’,
left: 0
right: 0
示例代码:
legend:{ left: '0', // right: '0' textStyle: { color: '#fff'}, orient: 'vertical', }
3,两端排列
顶部一半,底部一半
legend: [ { top: '0', textStyle: { color: '#fff', padding: [11,0,11,0] }, data: [], }, { bottom: '0', textStyle: { color: '#fff', padding: [11,0,11,0] }, data: [], }, ], init(){ this.option.legend[0].data = legendName.slice(0,5) this.option.legend[1].data = legendName.slice(-5) }
左边一半,右边一半
legend: [ { x: 'left', textStyle: { color: '#fff', padding: [11,0,11,0] }, orient: 'vertical', data: [], }, { x: 'right', textStyle: { color: '#fff', padding: [11,0,11,0] }, orient: 'vertical', data: [], }, ], init(){ this.option.legend[0].data = legendName.slice(0,5) this.option.legend[1].data = legendName.slice(-5) }
二、formatter使用语法
以图例后面拼接占比百分比为例
使用formatter,让每个图例后面拼接该部分占整体的百分比
1.上下左右排列+占比百分比
legend:{ x: 'left', textStyle: { color: '#fff', }, orient: 'vertical', data: [], formatter: e =>{ var data = this.option.series[0].data; var total = 0; var val = 0; data.forEach(el => { total += el.value; if(e == el.name) val = el.value }); return `${e} ${((val / total)*100).toFixed(2)}%` } }, this.option.legend.data = legendName
2.两端排列+占比百分比
legend: [ { x: 'left', textStyle: { color: '#fff', padding: [11,0,11,0] }, orient: 'vertical', data: [], formatter: e =>{ var data = this.option.series[0].data; var total = 0; var val = 0; data.slice(0,5).forEach(el => { total += el.value; if(e == el.name) val = el.value }); return `${e} ${((val / total)*100).toFixed(2)}%` } }, { x: 'right', textStyle: { color: '#fff', padding: [11,0,11,0] }, orient: 'vertical', data: [], formatter: e =>{ var data = this.option.series[0].data; var total = 0; var val = 0; data.forEach(el => { total += el.value; if(e == el.name) val = el.value }); return `${e} ${((val / total)*100).toFixed(2)}%` } }, ], this.option.legend[0].data = legendName.slice(0,5) this.option.legend[1].data = legendName.slice(-5)
好了,本文就到这里吧,点个关注再走嘛~