在 ECharts 中配置多条折线图的图例颜色,可以通过在 `legend` 的 `data` 数组中为每个图例项定义 `itemStyle` 来实现。这样可以为每条折线对应的图例设置不同的颜色,甚至支持渐变色。具体配置方法如下:
### 设置图例颜色
在 `legend` 的 `data` 数组中,为每个图例项添加 `itemStyle` 属性,并通过 `color` 指定颜色值。如果需要渐变色,可以使用 `echarts.graphic.LinearGradient` 来定义渐变效果。
以下是一个示例代码:
```javascript
legend: {
icon: "rect",
itemWidth: 62,
itemHeight: 3,
right: 5,
textStyle: {
fontSize: 14,
color: "#6C7B8A",
},
data: [
{
name: '充电',
itemStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 1, 1, [
{ offset: 0, color: "rgba(12, 165, 235, 1)" }, // 起始颜色
{ offset: 1, color: "rgba(97, 206, 89, 1)" }, // 结束颜色
])
}
},
{
name: '放电',
itemStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 1, 1, [
{ offset: 0, color: "rgba(98, 178, 237, 1)" }, // 起始颜色
{ offset: 0.5, color: "rgba(250, 200, 87, 1)" }, // 中间颜色
{ offset: 1, color: "rgba(242, 78, 40, 1)" }, // 结束颜色
])
}
}
]
}
```
### 设置图例默认显示状态
可以通过 `selected` 属性控制图例的默认显示状态。例如,设置某个图例为隐藏状态:
```javascript
legend: {
data: [
{ name: '充电' },
{ name: '放电' }
],
selected: {
'充电': true, // 默认显示
'放电': false // 默认隐藏
}
}
```
### 图例样式与图标
可以通过 `icon` 设置图例的图标形状,如 `circle`、`rect` 等,同时也可以通过 `itemWidth` 和 `itemHeight` 调整图例的大小。
```javascript
legend: {
icon: "circle", // 图例图标为圆形
itemWidth: 12, // 图例宽度
itemHeight: 12, // 图例高度
data: [
{ name: '充电' },
{ name: '放电' }
]
}
```
### 多条折线图的图例控制
在多条折线图中,图例的名称需要与 `series` 中的 `name` 对应,以确保图例和折线之间的联动效果。
```javascript
series: [
{
name: '充电',
type: 'line',
data: [150, 230, 224, 218, 135, 147, 260]
},
{
name: '放电',
type: 'line',
data: [1, 2, 3, 4, 5, 6, 7]
}
]
```
### 完整示例
结合以上配置,一个完整的多条折线图图例配置示例如下:
```javascript
option = {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
legend: {
icon: "rect",
itemWidth: 62,
itemHeight: 3,
right: 5,
textStyle: {
fontSize: 14,
color: "#6C7B8A",
},
data: [
{
name: '充电',
itemStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 1, 1, [
{ offset: 0, color: "rgba(12, 165, 235, 1)" },
{ offset: 1, color: "rgba(97, 206, 89, 1)" }
])
}
},
{
name: '放电',
itemStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 1, 1, [
{ offset: 0, color: "rgba(98, 178, 237, 1)" },
{ offset: 0.5, color: "rgba(250, 200, 87, 1)" },
{ offset: 1, color: "rgba(242, 78, 40, 1)" }
])
}
}
],
selected: {
'充电': true,
'放电': false
}
},
series: [
{
name: '充电',
type: 'line',
data: [150, 230, 224, 218, 135, 147, 260]
},
{
name: '放电',
type: 'line',
data: [1, 2, 3, 4, 5, 6, 7]
}
]
};
```