大家好,欢迎回来鸿蒙5莓创图表组件的专场,我们这一期来讲解柱状图的高亮、渐变、圆角、堆叠等高级场景的实现方案。
一、高亮柱子场景
应用场景:突出显示特定数据点(如最高/最低值) 实现方式: 在数据数组中通过{color: '色值', value: 数值}
格式单独定义目标柱子的颜色。 完整代码:
import { McBarChart, Options } from '@mcui/mccharts'
@Entry
@Component
struct HighlightBar {
@State options: Options = new Options({
title: {
text: '高亮柱子',
right: 20
},
xAxis: {
data: ['周一','周二','周三','周四','周五','周六','周日']
},
series: [
{
name: '最高气温',
data: [11, 11, 15, 13, 12,
{color: '#fb7293', value: 38}, 10] // 第六根高亮
},
{
name: '最低气温',
data: [-11, -11, -15, -13, -12,
{color: '#53e075', value: -20}, -10]
}
]
})
build() {
McBarChart({ options: this.options })
.height('50%')
}
}
二、渐变色柱子场景
应用场景:增强视觉效果,常用于强调数据趋势 实现方式: 在series配置中定义gradient
属性,使用颜色数组设置渐变效果,第二个颜色支持透明度。 完整代码:
import { McBarChart, Options } from '@mcui/mccharts'
@Entry
@Component
struct GradientBar {
@State options: Options = new Options({
title: {
text: '渐变柱状图'
},
xAxis: {
data: ['周一','周二','周三','周四','周五','周六','周日']
},
series: [
{
name: '白天气温',
gradient: {
color: ['#53e075', '#7953e075'] // 线性渐变
},
data: [30,31,35,31,28,31,31]
},
{
name: '夜间气温',
gradient: {
color: ['#fa6262', '#83fa6262'] // 带透明度的渐变
},
data: [11,11,15,13,12,13,10]
}
]
})
build() {
McBarChart({ options: this.options })
.height('50%')
}
}
三、圆角柱子场景
应用场景:美化图表呈现,适合现代风格UI设计 实现方式: 在barStyle
中配置borderRadius
属性,数组参数表示[左上/右上, 右下/左下]的圆角半径。 完整代码:
import { McBarChart, Options } from '@mcui/mccharts'
@Entry
@Component
struct RoundedBar {
@State options: Options = new Options({
title: {
text: '圆角模式'
},
xAxis: {
data: ['周一','周二','周三','周四','周五','周六','周日']
},
series: [
{
name: '最高气温',
barStyle: {
width: 10,
borderRadius: [8, 8] // 统一圆角
},
data: [30,31,35,31,28,31,31]
},
{
name: '最低气温',
barStyle: {
color: '#fa6262',
borderRadius: [4, 20] // 不对称圆角
},
data: [11,11,15,13,12,130,100]
}
]
})
build() {
McBarChart({ options: this.options })
.height('50%')
}
}
四、堆叠柱状图场景
应用场景:展示多维度数据的累计关系 实现方式:
- 在series中设置相同
stack
字段值 - 通过
label.position
实现居中数据标签 完整代码:
import { McBarChart, Options } from '@mcui/mccharts'
@Entry
@Component
struct StackedBar {
@State options: Options = new Options({
title: {
text: '堆叠模式'
},
xAxis: {
data: ['周一','周二','周三','周四','周五','周六','周日']
},
series: [
{
name: '最高气温',
stack: 'temp',
label: {
position: 'center',
color: '#fff'
},
data: [30,31,35,31,28,31,31]
},
{
name: '最低气温',
stack: 'temp', // 相同stack名称实现堆叠
barStyle: {
color: '#fa6262'
},
label: {
position: 'center',
color: '#fff'
},
data: [11,11,15,13,12,130,100]
}
]
})
build() {
McBarChart({ options: this.options })
.height('50%')
}
}
五、组合使用技巧
// 在series中组合多个特性
series: [{
stack: 'group',
gradient: { color: ['#ffd700','#ff4500'] },
barStyle: {
borderRadius: [6,6],
width: 14
},
data: [{color:'#ff0000', value: 88}, 75, 92]
}]
好,这期讲到这里就结束了,希望大家通过本教程能掌握莓创图表的高级用法,在实际项目中灵活运用这些特性打造出更专业的数据可视化效果。有任何问题欢迎在评论区留言讨论!