要实现的效果

要实现的效果很简单,给图例设置不同的legend图标,貌似设置icon就能解决,但是却不支持单独修改每个icon样式。
在这里插入图片描述

方案

方案一:设置legend.data.icon

缺点:icon大小无法单独设置(效果见下图)

在这里插入图片描述

legend: {
    bottom: 0,
    itemWidth: 10,
    itemHeight: 3, // 设置该值的话,square的宽度会变成3, 不设置的话rect是正方形
    textStyle: {
        color: '#434549',
        fontSize: 12
    },
    formatter (item) {
        return item + '      '
    },
    data: [
        {
            name: '大类资产配置收益',
            icon: 'square'
        }, {
            name: '行业配置收益',
            icon: 'square'
        }, {
            name: '行业选股收益',
            icon: 'square'
        }, {
            name: '交易收益',
            icon: 'square'
        }, {
            name: '总超额收益',
            icon: 'rect'
        }
    ]
}

方案二:设置多组legend

缺点:多组legend的位置需单独设置,无法统一居中(效果见下图)

在这里插入图片描述

// 图例类型名称
const legendLabels = [
    {
        type: 'square',
        labels: [
            '大类资产配置收益',
            '行业配置收益',
            '行业选股收益',
            '交易收益'
        ]
    }, {
        type: 'line',
        labels: ['总超额收益']
    }
]

// 根据图例类型名称生成图表的legend配置
const legendData = legendLabels.map((item, idx) => ({
    icon: 'rect',
    bottom: 0,
    itemWidth: 10,
    textStyle: {
        color: '#434549',
        fontSize: 12
    },
    formatter (v) {
        return v + '      '
    },
    data: item.labels,
    itemHeight: item.type === 'line' ? 3 : 10,
    ...(item.type === 'line' ? {
        right: '20%'
    } : {
        left: '20%'
    })
}))

// set echart legend options
legend: legendData

方案三:svg

大小和位置完美适配,最终采用该方案。

在这里插入图片描述

// 图表legend的svg图形
const legendSvg = {
    // 正方形 10*10
    rect: 'path://M-0.000,-0.000 L10.000,-0.000 L10.000,10.000 L-0.000,10.000 L-0.000,-0.000 Z',
    // 线条 10*3
    line: 'path://M-0.000,-0.000 L10.000,-0.000 L10.000,3.000 L-0.000,3.000 L-0.000,-0.000 Z'
}
legend: {
    data: [
        {
            name: '大类资产配置收益',
            icon: legendSvg.rect
        }, {
            name: '行业配置收益',
            icon: legendSvg.rect
        }, {
            name: '行业选股收益',
            icon: legendSvg.rect
        }, {
            name: '交易收益',
            icon: legendSvg.rect
        }, {
            name: '总超额收益',
            icon: legendSvg.line
        }
    ],
    bottom: 0,
    icon: 'rect',
    itemWidth: 10,
    itemHeight: 3,
    textStyle: {
        color: '#434549',
        fontSize: 12
    },
    formatter (item) {
        return item + '      '
    }
}

方案三为最终效果。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐