学习使用echarts图表中formatter的用法,格式化数字金额,控制x轴、y轴展示长度
- 控制金额长度
- 两位小数,并去除多余.00
- 效果图
- 控制文字长度
- 完整代码
控制金额长度
series: [{name: '',type: 'bar',sort: 'none',label: { //饼图图形上的文本标签normal: {show: true,position: 'outside', //标签的位置inner\inside(饼图扇区内部),outside(饼图扇区外侧,通过视觉引导线连到相应的扇区。),center(在饼图中心位置)textStyle: {fontWeight: 100,},formatter: function (params) {let number = params.data;if (number && number > 10000) {let new_number = number / 10000;return unifyNumber(new_number) + '万' + series_unit;} else {return number + series_unit;}}}},itemStyle: {normal: {//这里设置每个柱子颜色不一样color: function (params) {// 定义一个颜色数组colorListvar colorList = all_data.color_data;return colorList[params.dataIndex]},}},data: all_data.series_data}]
两位小数,并去除多余.00
function unifyNumber(num) {if (num === '') {return 0} else {let handleNum = parseFloat(num)let isToFixed = handleNum.toString().includes('.') && handleNum.toString().split('.')[1].length > 2if (isToFixed) {return handleNum.toFixed(2)} else {return handleNum}}}
效果图
控制文字长度
yAxis: {type: 'category',data: all_data.yaxis_data,axisLabel: {formatter: function (params) {var maxLength = 3;//判断长度,超出使用...代替if (params && params.length > maxLength) {return params.substring(0, maxLength - 1) + '.';} else {return params;}}}
},
修改后效果图如下:
完整代码
option = {title: {text: '',show: false,},tooltip: {trigger: 'axis',formatter: "{a} <br\/>{b} : {c}" + series_unit,//{a}:系列名。{b}:数据名。{c}:数据值。textStyle: {"fontSize": 13},axisPointer: {type: 'shadow'}},legend: {},grid: {left: '3%',right: '0%',bottom: '3%',containLabel: true},xAxis: {show: false,type: 'value',boundaryGap: [0, 0.01],},yAxis: {type: 'category',data: all_data.yaxis_data,axisLabel: {formatter: function (params) {var maxLength = 3;//判断长度,超出使用...代替if (params && params.length > maxLength) {return params.substring(0, maxLength - 1) + '.';} else {return params;}}}},series: [{name: '',type: 'bar',sort: 'none',label: { //饼图图形上的文本标签normal: {show: true,position: 'outside', //标签的位置inner\inside(饼图扇区内部),outside(饼图扇区外侧,通过视觉引导线连到相应的扇区。),center(在饼图中心位置)textStyle: {fontWeight: 100,},formatter: function (params) {let number = params.data;if (number && number > 10000) {let new_number = number / 10000;return unifyNumber(new_number) + '万' + series_unit;} else {return number + series_unit;}}}},itemStyle: {normal: {//这里设置每个柱子颜色不一样color: function (params) {// 定义一个颜色数组colorListvar colorList = all_data.color_data;return colorList[params.dataIndex]},}},data: all_data.series_data}]};