小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
问题
前端经常会遇到绘制图表的需求,当初在使用echarts
绘制柱状图时曾经遇到过柱顶的文字颜色设置成不同颜色问题。
需要达到的效果:
条形柱状的颜色可以在series
-itemStyle
中通过color
进行设置,并且每一根都可以设置为不同。因为color
可以定义为function
设置主体颜色主要代码(params为4根柱体,dataIndex是序号,在echarts中可以通过echarts.graphic.LinearGradient来设置渐变色):
color: function (params) {
var colorList = [ ['#5498ff', '#89d3f6'],['#0acd81', '#b7f5bf'], ['#ff9137', '#ffd59a'], ['#f97878', '#ffafaf'] ];
var index = params.dataIndex;
if (params.dataIndex >= colorList.length) {
index = params.dataIndex - colorList.length;
}
return new echarts.graphic.LinearGradient(0, 0, 0, 1, [{ offset: 0, color: colorList[index][0] }, { offset: 1, color: colorList[index][1] } ]);
}
复制代码
此时柱体上面并没有显示文字,如果需要显示文字,可以在itemStyle
继续设置label
属性
具体设置:
label: {
show: true,
position: 'top',
textStyle: {
fontSize: '14px',
},
},
复制代码
此时,图表的样式(柱状上的文字颜色为统一的黑色):
当时我想能否在textStyle
中对color
类似与柱条颜色一样设置,但是通过查看配置项手册发现只能设置为字符串,不能通过function来设置。这样的话四种文字还是只会变成一种颜色。
解决
可以在series
的data
设置时添加配置颜色,之前设置数据时是直接数值数组的方式
// 成绩
data: [9, 21, 23, 12]
复制代码
其实可以在配置时,就将label的相应颜色设置,数值放在value中 代码:
data: [{
value:9,
label: {
textStyle: { color: '#2e77dc' }
}
}, {
value:21,
label: {
textStyle: { color: '#0aa211' }
}
}, {
value:23,
label: {
textStyle: { color: '#ff6600' }
}
}, {
value:12,
label: {
textStyle: { color: '#f12222' }
}
}]
复制代码
完整配置项
option01 = {
xAxis: {
type: 'category',
data: ['优秀', '良好', '合格','不合格'],
axisTick: { show: false, },
axisLabel: {
textStyle: { color: '#999999' },
interval: 0,
},
axisLine: {
lineStyle: { color: '#cccccc' }
},
},
yAxis: {
type: 'value',
name: '人数',
nameTextStyle:{ color: '#666666' },
axisTick: { show: false },
axisLabel: { textStyle: { color: '#999999' }, },
axisLine: {
lineStyle: { color: '#cccccc', },
show: true
},
splitLine: {
show: true,
lineStyle:{ type: 'dashed', }
}
},
series: [
{
name: '班级成绩分布',
type: 'bar',
barWidth: '24px',
itemStyle:{
normal:{
barBorderRadius:[12, 12, 0, 0],
label: {
show: true,
position: 'top',
textStyle: { fontSize: '14px', },
},
color: function (params) {
var colorList = [ ['#5498ff', '#89d3f6'],['#0acd81', '#b7f5bf'], ['#ff9137', '#ffd59a'], ['#f97878', '#ffafaf'] ];
var index = params.dataIndex;
if (params.dataIndex >= colorList.length) {
index = params.dataIndex - colorList.length;
}
return new echarts.graphic.LinearGradient(0, 0, 0, 1, [{ offset: 0, color: colorList[index][0] }, { offset: 1, color: colorList[index][1] } ]);
},
}
},
// 成绩
data: [{
value:9,
label: {
textStyle: { color: '#2e77dc' }
}
}, {
value:21,
label: {
textStyle: { color: '#0aa211' }
}
}, {
value:23,
label: {
textStyle: { color: '#ff6600' }
}
}, {
value:12,
label: {
textStyle: { color: '#f12222' }
}
}]
}
],
grid: {
x: 40,
y: 30,
x2: 0,
y2: 35
},
}
复制代码