option
可以复制示例option代码,在echarts的示例background
中粘贴运行来学习
https://echarts.apache.org/examples/zh/editor.html?c=bar-background
option = {
xAxis: [
{
type: 'category',
data: ['一', '', '']
},
{
type: 'category',
position: 'bottom',
data: ['', '二', '']
},
{
type: 'category',
position: 'bottom',
data: ['', '', '三']
}
],
yAxis: {
type: 'value'
},
series: [
// 第一个x轴数据
{
name: '一',
type: 'bar',
xAxisIndex: 0,
barWidth: 30,
data: [1]
},
{
name: '二',
type: 'bar',
xAxisIndex: 0,
barWidth: 30,
data: [2]
},
{
name: '三',
type: 'bar',
xAxisIndex: 0,
barWidth: 30,
data: [3]
},
// 第二个x轴数据
{
name: '一',
type: 'bar',
xAxisIndex: 1,
barWidth: 30,
data: ['', 1]
},
{
name: '二',
type: 'bar',
xAxisIndex: 1,
barWidth: 30,
data: ['', 2]
},
// 第三个x轴数据
{
name: '一',
type: 'bar',
xAxisIndex: 2,
barWidth: 30,
data: ['', '', 2]
},
{
name: '三',
type: 'bar',
xAxisIndex: 2,
barWidth: 30,
data: ['', '', 1]
}
]
};
position: ‘bottom’
用于把x轴的轴名放在正确位置,不然不能正确显示x轴的轴名
xAxisIndex
表示使用的 x 轴的 index,在单个图表实例中存在多个 x 轴的时候有用
比如示例中有三个x轴, xAxisIndex最大则为2,如果超过2,echarts直接报错,会直接渲染echarts失败
在series中设置相应的xAxisIndex可以保证柱在对应x轴中是居中对齐的,可以自己改一改看一看效果
barWidth
不设置的话会柱自动撑满所有宽度
xAxis与series
xAxis与series的data位置要对应
根据以上规律编写js处理后端柱图数组数据
一般来说后端柱图数组数据,是这样格式的:
const xAxis = [
'星期一',
'星期二',
'星期三',
'星期四',
'星期五',
'星期六',
'星期天'
];
const bar1 = [10, 2, 0, 4, 5, 6, 7];
const bar2 = [8, 9, 10, 11, 12, 13, 14];
const bar3 = [0, 0, 17, 18, 19, 20, 21];
function dealBar(arr, name) {
const bar = [];
arr.forEach((item, index) => {
const data = [];
for (let i = 0; i < index; i++) {
data.push('');
}
if (item) {
data.push(item);
bar.push({
name,
type: 'bar',
xAxisIndex: index,
barWidth: 20,
data
});
}
});
return bar;
}
option = {
legend:{},
xAxis: xAxis.map((item, index) => {
const data = Array(xAxis.length).fill('');
data[index] = item;
return {
type: 'category',
position: 'bottom',
data: data
};
}),
yAxis: {
type: 'value'
},
series: [
...dealBar(bar1, 'bar1'),
...dealBar(bar2, 'bar2'),
...dealBar(bar3, 'bar3')
]
};