uChart作为一款轻量级的图表库,虽然功能不如ECharts全面,但仍然可以实现堆叠柱状图的数据对比效果。以下是实现方法:
准备数据格式:
const series = [
{
name: '系列1',
data: [120, 132, 101, 134, 90, 230, 210],
stack: 'stack1' // 关键属性,相同stack值的系列会堆叠
},
{
name: '系列2',
data: [220, 182, 191, 234, 290, 330, 310],
stack: 'stack1' // 与系列1相同的stack值
},
{
name: '系列3',
data: [150, 232, 201, 154, 190, 330, 410],
stack: 'stack2' // 不同的stack值会形成新的堆叠组
}
];
配置图表选项:
const options = {
type: 'column',
categories: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
series: series,
yAxis: {
format: (val) => val.toFixed(0)
},
extra: {
column: {
type: 'stack' // 启用堆叠模式
}
}
};
渲染图表:
const chart = new uCharts(options);
chart.render('canvasId');
自定义颜色:
series: [
{
name: '系列1',
data: [120, 132, 101, 134, 90, 230, 210],
stack: 'stack1',
color: '#1890FF'
},
// 其他系列...
]
添加图例:
extra: {
column: {
type: 'stack'
},
legend: {
show: true,
position: 'top',
float: 'center'
}
}
设置数据标签:
extra: {
column: {
type: 'stack',
barWidth: 30,
labelShow: true,
format: (val) => val.toFixed(0)
}
}
功能差异:
性能优势:
const options = {
type: 'column',
categories: ['1月', '2月', '3月', '4月', '5月', '6月'],
series: [
{
name: '产品A',
data: [35, 36, 31, 33, 13, 34],
stack: 'total',
color: '#1890FF'
},
{
name: '产品B',
data: [18, 27, 21, 24, 6, 28],
stack: 'total',
color: '#2FC25B'
},
{
name: '产品C',
data: [18, 27, 21, 24, 6, 28],
stack: 'total2',
color: '#FACC14'
}
],
yAxis: {
gridType: 'dash',
dashLength: 2,
format: (val) => val.toFixed(0) + 'k'
},
extra: {
column: {
type: 'stack',
barWidth: 20,
labelShow: true
},
legend: {
show: true,
position: 'top',
float: 'center'
},
tooltip: {
showBox: true
}
}
};
const chart = new uCharts(options);
chart.render('canvasId');
通过以上配置,您可以在uChart中实现类似ECharts的堆叠柱状图效果,用于数据对比分析。