Echarts配置项解析 (图例篇) | 8月更文挑战

776 阅读2分钟

这是我参与8月更文挑战的第4天,活动详情查看:8月更文挑战

legend 图例相关配置

type: 图例类型,支持normal、scroll scroll 支持滚动,如下图:

image.png

id: 组件ID,方便引用

show: 控制的图例的显示隐藏

zlevel:Canvas的层次,设置了这个属性后,echarts会为这个组件单独增加canvas,并设置它的层次。

z: 设置组件的层次

left: 图例相对容器的左边距离

top: 图例相对容器的上方距离

right: 图例相对容器的右边距离

down: 图例相对容器的下方距离

width: 图例的宽度 默认是容器的宽度

height: 图例的高度 默认是auto

align: 对齐方式,默认是left, 这个项会使图标和文字的位置也会发生变化 padding: 图例的内间距,支持数字和数组,数组的四个元素代表上、右、下、左,四个方向的距离 itemGap:图例项之间的间距 itemWidth:图例项的宽度 itemHeight:图例项的高度 itemStyle:图例项的样式

  • color: 图例项图标的颜色,如:#ff0000, rgba(255, 0, 0, 0.5),一般不会设置这个配置,会导致图标的颜色变成一样的
  • borderColor: 图例项的边框颜色
  • borderWidth: 图例项的边框宽度
  • borderType: 图例项的边框风格

icon:图例图标的类型,可以使用echarts提供的line、circle、rectangle、triangle、arrow、diamond、pin等,也可以自定义path, 使用图片等 formatter: 自定义图例的显示文字

完整例子

index.html:

<!DOCTYPE html>
<html lang="en">

<head>
 <meta charset="UTF-8">
 <meta http-equiv="X-UA-Compatible" content="IE=edge">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Echarts实例 - 图例</title>
 <script src="../../echarts.js"></script>
</head>

<body>
 <div id="container" style="width: 500px;height:500px;">

 </div>
 <script src="./index.js"></script>
</body>

</html>

index.js

var chart = echarts.init(document.getElementById("container"));

var legendData = [];
for (var i = 1995; i <= 2021; i++) {
 legendData.push(i + "年")
}

var series = [];

for (var i = 1995; i <= 2021; i++) {
 series.push({

     name: i + "年",
     data: [Math.floor(Math.random() * 10000), Math.floor(Math.random() * 10000), Math.floor(Math.random() * 10000)],
     type: 'line'
 })
}

chart.setOption({
 title: {
     text: '网站访问量'
 },
 legend: {
     id: '',
     top: 40,
     show: true,
     zlevel: 3,
     // orient: 'vertical', // 默认是水平,支持horizontal、vertical
     type: 'scroll',
     // align: 'right',
     data: legendData,
     padding: [5, 30, 5, 30],
     itemGap: 5,
     itemWidth: 10,
     itemHeight: 10,
     itemStyle: {
         // color: 'rgba(255, 0, 0, 0.5)',
         borderColor: 'red',
         borderWidth: 1,
         borderType: 'solid'
     },
     lineStyle: {
         color: 'rgba(255, 0, 0, 0.5)',
         join: 'round'
     },
     icon: 'line',
     formatter: function(name) {
         return name;
     }
 },
 xAxis: {
     type: 'category',
     data: ['百度', '腾讯', '新浪']
 },
 yAxis: {
     type: 'value'
 },
 grid: {
     top: 80
 },
 series: series
})