需求
今天分享一个很实用的ECharts图例多行显示的经验。
如图,要实现的效果如下。图例需要进行显示多行信息并且icon要与第一行持平。
步骤
显示多行多样式
首先,多行显示需要用到legend.formatter,该配置项支持自定义图例信息, \n
用来换行。
其次,不同的文字显示不同的样式,需要用到富文本样式,具体用法如下。
// 配置项,只展示关键信息
const options = {
legend: {
formatter: function (name) {
return [ `{name|${name}}{percent|30%}`, "{num|300}", `{others|others}`, ].join("\n");
},
textStyle: {
rich: {
name: {
fontSize: 12,
},
percent: {
color: "#77b9c3",
},
num: {
fontSize: 20,
color: "#bd8776",
padding: [10, 0],
},
others: {},
},
},
},
};
此时出来的效果如下。
图标首行对齐
大致上出来了,还剩一个图标的位置问题。通过观察发现,每个图标的总会显示在该图例的中间位置。为了将图标移上去,我们需要将整个图例拉长,也就是需要扩充上部分的长度,可以通过padding实现。如下图。
为了方便调试,可以给每个块添加背景颜色。
添加的代码如下。
注:文档中对 legend.textStyle.rich.<style_name>.padding
这里的描述有误,实际结果为[下, 右, 上, 左]
文档描述
padding: [3, 4, 5, 6]
:表示[上, 右, 下, 左]
的边距。
按照正常思路应该是上右下左,与css保持一致。猜测是代码有误,可以关注该issue
来看一下新增的代码。如果调整完后图例位置太下面,可以使用 top
调整,允许为负值。
// 配置项,只展示关键信息
const options = {
legend: {
top: -10,
formatter: function (name) {
return [ `{name|${name}}{percent|30%}`, "{num|300}", `{others|others}`, ].join("\n");
},
textStyle: {
rich: {
name: {
fontSize: 12,
++ padding: [0, 0, 50, 0], // 下右上左
backgroundColor: 'gray'
},
percent: {
color: "#77b9c3",
++ padding: [0, 0, 50, 10],
backgroundColor: 'lightgray'
},
num: {
fontSize: 20,
color: "#bd8776",
padding: [10, 0],
},
others: {},
},
},
},
};
更好的方法
这时,设计师说,你把第一行的百分比给我加个背景颜色。
那按照上面的做法就有问题了,用来填充的那部分也会被显示出来。
这里有个更好的方法,开头添加一个专门的样式用作填充。
// 配置项,只展示关键信息
const options = {
legend: {
formatter: function (name) {
return [++ `{top|}`, `{name|${name}}{percent|30%}`, "{num|300}", `{others|others}`, ].join("\n");
},
textStyle: {
top: {
++ padding: [0, 0, 40, 0]
},
rich: {
name: {
fontSize: 12,
-- padding: [0, 0, 50, 0],
},
percent: {
color: "#77b9c3",
-- padding: [0, 0, 50, 0],
backgroundColor: 'lightgray'
},
num: {
fontSize: 20,
color: "#bd8776",
padding: [10, 0],
},
others: {},
},
},
},
};
源码
// 配置项,只展示图例信息
const options = {
legend: {
left: 200,
top: 150,
data: ["直接访问", "邮件营销"],
formatter: function (name) {
return [ `{top|}`, `{name|${name}}{percent|30%}`, "{num|300}", `{others|others}`, ].join("\n");
},
textStyle: {
rich: {
top: {
padding: [0, 0, 40, 0],
},
name: {
fontSize: 12,
},
percent: {
color: "#77b9c3",
backgroundColor: "lightgray",
},
num: {
fontSize: 20,
color: "#bd8776",
padding: [10, 0],
},
others: {},
},
},
},
};
欢迎关注我的其他账号~
本文使用 mdnice 排版