在 ECharts 中设置柱状图柱子顶部显示具体数值,主要通过配置 series
中的 label
属性实现。以下是具体方法及示例:
1. 基础配置:显示数值标签
在 series
的 label
属性中设置 show: true
并指定位置 position
,例如:
series: [{
type: 'bar',
data: [120, 200, 150, 80, 70],
label: {
show: true, // 启用数值显示
position: 'top', // 数值显示在柱顶(垂直柱状图)
color: '#333' // 文字颜色
}
}]
此配置会直接在柱子顶部显示原始数值。
2. 自定义数值格式
若需调整显示内容(如添加单位、百分比),可通过 formatter
属性实现:
label: {
show: true,
position: 'top',
formatter: '{c} 件' // {c} 表示数据值,附加单位
}
或使用函数动态生成标签:
formatter: (value) => `${value.value}%` // 显示百分比格式
3. 调整标签样式
通过 textStyle
属性控制字体大小、颜色等:
label: {
show: true,
position: 'top',
textStyle: {
fontSize: 14, // 字体大小
fontWeight: 'bold',// 加粗
color: 'blue' // 字体颜色
}
}
此配置可优化标签可读性。
4. 特殊场景适配
- 水平柱状图:设置
position: 'right'
。 - 堆叠柱状图:使用
position: 'inside'
将数值显示在柱子内部。 - 复杂布局:通过引入透明占位柱形条(数据为极小值如 0.01)实现多标签共存。
完整示例代码
option = {
xAxis: { type: 'category', data: ['Mon', 'Tue', 'Wed'] },
yAxis: { type: 'value' },
series: [{
type: 'bar',
data: [120, 200, 150],
label: {
show: true,
position: 'top',
formatter: '{c} 件',
textStyle: { fontSize: 12, color: '#666' }
}
}]
};
通过以上配置,可实现数值标签的灵活展示与定制化。具体参数可根据需求调整,例如调整 position
的值(如 'bottom'
、'inside'
)或结合 itemStyle
优化柱子颜色。