直接在 data 中设置
可以在 series 的 data 数组中,为每个数据项指定一个对象,该对象除了包含 value 外,还可以包含一个 itemStyle 属性来指定颜色。比较常用,例如:
series: [
{
type: 'bar',
data: [
{ value: 100, itemStyle: { color: 'red' } },
{ value: 200, itemStyle: { color: 'blue' } },
{ value: 300, itemStyle: { color: 'green' } },
],
}
]
效果图:
使用回调函数映射颜色
利用 itemStyle.color 属性的回调函数功能,根据数据项的索引或值来动态设置颜色。个人来说非常推荐这种写法,因为我们通常拿到的是后端的一组数据,代码简洁性和可复用性很高,例如:
series: [
{
type: 'bar',
data: [100, 200, 300, 400],
itemStyle: {
color: function (params) {
// 根据params的
const colorsMap = [
'#ff0000',
'#00ff00',
'#0000ff',
'#ffff00']
return colorsMap[params.dataIndex];
}
}
}
]
效果图:
使用回调函数映射渐变色
如果需要每个柱子有渐变色,可以在 itemStyle 中使用 color 属性设置渐变颜色,并且通过回调函数确保每个柱子的渐变色不同。例如:
series: [
{
type: "bar",
data: [100, 200, 300],
itemStyle: {
color: function (params) {
// 动态生成渐变色或者根据条件返回预设的渐变色
const gradientColors = [
{
// 线性渐变,前四个参数分别是 x0, y0, x2, y2, 范围从 0 - 1,
// 相当于在图形包围盒中的百分比
x: 0,
y: 0,
x2: 0,
y2: 1,
type: "linear",
colorStops: [
{ offset: 0, color: "red" },
{ offset: 1, color: "blue" }
]
},
{
x: 1,
y: 0,
x2: 0,
y2: 0,
type: "linear",
colorStops: [
{ offset: 0, color: "red" },
{ offset: 1, color: "blue" }
]
},
// 径向渐变,前三个参数分别是圆心 x, y 和半径,取值同线性渐变
{
type: "radial",
x: 0.5,
y: 0.5,
r: 1,
colorStops: [
{
offset: 0,
color: "red" // 0% 处的颜色
},
{
offset: 1,
color: "blue" // 100% 处的颜色
}
]
}
];
return gradientColors[params.dataIndex];
}
}
}
]
效果图:
随机颜色
这种一般是用在动态展示不同关键词的时候,比如说关键词云图(echarts-wordcloud),首先是定义一个生成随机颜色的函数
const randomRGB = () => {
const r = Math.floor(Math.random() * 255);
const g = Math.floor(Math.random() * 255);
const b = Math.floor(Math.random() * 255);
return `rgb(${r},${g},${b})`;
};
使用的时候直接在 color 调用即可
// 例如
textStyle: {
color: randomRGB;
}
//完整的series配置
series: [
{
type: "wordCloud",
sizeRange: [8, 46],
rotationRange: [0, 0],
gridSize: 0,
layoutAnimation: true,
textStyle: {
color: randomColor
},
emphasis: {
testStyle: {
fontWeight: "bold",
color: "#ffffff"
}
},
data: props.data.datas
}
];
效果图:
总结
综上所述,主要通过直接赋值、回调函数静态映射和回调函数动态生成(包括渐变色)这几种方式来设置不同柱子的不同颜色。具体采用哪种方法取决于需求的复杂度和个性化程度,我相信总有一款适合你。
最后,推荐一个前端实用的网站CSS 可视化,好多实用工具,就配色而言推荐一个他的配色方案
不同颜色。具体采用哪种方法取决于需求的复杂度和个性化程度,我相信总有一款适合你。