大家好,欢迎回来鸿蒙5莓创图表组件的专场,我们这一期来讲解横向柱状图(McHorBarChart)基础属性的详细用法。本文将全面解析每个配置项的作用、类型、默认值、可选值和使用场景,并通过完整代码案例帮助您快速掌握。
一、grid 网格布局
作用:控制图表绘图区域与容器边缘的间距 类型:Object 默认值:{}
场景:当需要精细化控制图表四周边距时使用,替代旧版cPadding系列属性
子属性详解:
- left:左侧间距(Number | String,默认auto)
- right:右侧间距(Number | String,默认auto)
- top:顶部间距(Number | String,默认auto)
- bottom:底部间距(Number | String,默认auto)
代码案例:
grid: {
left: 50,
right: '20%',
top: 30,
bottom: 40
}
二、color 调色盘
作用:定义数据系列的颜色序列 类型:String[] 默认值:['#296DFF', '#ff5495fd', ...]
可选值:支持HEX、RGB、RGBA等颜色格式 场景:需要统一管理多系列配色时
代码案例:
color: ['#FF6B6B', '#4ECDC4', '#45B7D1']
三、title 标题配置
作用:设置图表主标题样式与位置 类型:Object 默认值:{ show: true, text: '', right: 20, top: 30 }
子属性详解:
show:显示开关(Boolean,默认true)
text:标题内容(String)
left/right/top/bottom:定位(Number | String)
textStyle:文本样式对象
- color:文字颜色(String)
- fontSize:字号(Number)
- fontWeight:字重('normal' | 'bold')
场景:需突出显示图表主题时
代码案例:
title: { show: true, text: '月度销售统计', left: 'center', textStyle: { color: '#333', fontSize: 18, fontWeight: 'bold' } }
四、xAxis X轴配置(核心)
作用:控制X轴样式与数据 类型:Object 必填:是
关键子属性:
- axisLine 轴线样式
- show:显示开关(Boolean)
- lineStyle:线样式对象
lineStyle: { color: '#666', width: 2 }
- axisLabel 标签样式
- color:文字颜色
- fontSize:字号
- formatter:自定义格式化函数
formatter: (name, index) => `${name}日`
- data:数据源(必填)
场景:需要定制X轴样式或处理长文本时
完整案例:
xAxis: { axisLine: { show: true, lineStyle: { color: '#999', width: 1 } }, axisLabel: { color: '#666', fontSize: 12, overflow: 'truncate' }, data: ['北京', '上海', '广州', '深圳'] }
五、series 数据系列(核心)
作用:定义数据系列样式与行为 类型:Object[] 必填:是
关键配置项:
- barStyle 柱状样式
barStyle: { width: 15, // 柱宽 borderRadius: [0, 8, 8, 0] // 圆角 }
- gradient 渐变配置
gradient: { color: ['#FF9A9E', '#FAD0C4'] }
- label 数据标签
label: { show: true, color: '#FFF', position: 'right', fontSize: 14 }
完整案例:
series: [{ name: '线上销量', data: [235, 401, 288, 399], barStyle: { width: 20, borderRadius: 8 }, gradient: { color: ['#6A11CB', '#2575FC'] } }]
六、综合案例:销售数据看板
@Entry @Component struct SalesDashboard { @State options: Options = new Options({ title: { show: true, text: '2023 Q3区域销售', left: 'center', textStyle: { fontSize: 20 } }, xAxis: { data: ['华北', '华东', '华南', '华中'], axisLabel: { fontSize: 14, color: '#666' } }, yAxis: { name: '销售额(万元)', nameTextStyle: { color: '#333' } }, series: [{ name: '实际销售额', data: [450, 680, 520, 410], barStyle: { width: 25, borderRadius: 12 }, gradient: { color: ['#36D1DC', '#5B86E5'] }, label: { show: true, color: '#FFF', position: 'right' } }] }) build() { Row() { McHorBarChart({ options: this.options }) }.height('60%') } }
结语
好,这期讲到这里就结束了,希望大家通过本文能够全面掌握McHorBarChart的基础属性配置。在实际开发中,建议先规划好可视化需求,再逐步调试各配置项参数。遇到问题欢迎在评论区留言,我们下期将深入讲解交互扩展功能!