修改前(中间柱子没数据但是还是会占位置)
修改后(中间柱子没数据情况下会自动调整)
import * as echarts from 'echarts';
var chartDom = document.getElementById('main');
var myChart = echarts.init(chartDom);
var option;
// let data = [100, 200, 150, 80, 70, 110, 10];
// let data1 = [10, 0, 90, 10, 0, 0, 0];
let data = [
[100, 200, 150, 80, 70, 110, 10],
[10, 0, 90, 10, 0, 0, 0],
[0, 90, 50, 10, 0, 0, 0]
];
option = {
tooltip: {},
title: {
show: true,
text: '不符合常理的柱状图表实现',
textStyle: {
fontSize: 14,
lineHeight: 18,
width: 10
}
},
xAxis: [
{
type: 'category',
axisLabel: {
align: 'center',
hideOverlap: true
},
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
}
],
yAxis: [
{
type: 'value'
}
],
series: [
{
type: 'custom',
renderItem: function (params, api) {
return getRect(params, api);
},
data: data[0]
},
{
type: 'custom',
renderItem: function (params, api) {
return getRect(params, api);
},
data: data[1]
},
{
type: 'custom',
renderItem: function (params, api) {
return getRect(params, api);
},
data: data[2]
},
{
//背景
type: 'bar',
barWidth: '90%',
data: [0, 0, 0, 0, 0, 0, 0],
showBackground: true,
backgroundStyle: {
color: 'rgba(180, 180, 180, 0.2)'
}
}
]
};
function getRect(params, api) {
const { seriesIndex } = params;
var categoryIndex = api.value(0); // x轴序列
let vald = api.value(1); //数据
var start = api.coord([categoryIndex, vald]);
var height = api.size([0, vald]);
let width = ((api.getWidth() - 50) / 7) * 0.5;
let x = start[0] - width / 2;
let count = 0;
data.forEach((val, i) => {
if (val[categoryIndex]) {
count++;
}
});
if (count) {
width = width / count;
let i = seriesIndex >= count ? count - 1 : seriesIndex;
x = x + i * width;
}
return {
type: 'rect',
shape: {
x,
y: start[1],
width,
height: height[1]
},
style: api.style()
};
}
option && myChart.setOption(option);