ECharts 图表插件使用整理

说明

ECharts 是一个 JavaScript 实现的开源可视化库,兼容当前绝大部分浏览器 IE 8 以上,是一个可高度个性化定制的数据可视化图表

ECharts 版本 –> 4.0.2

这篇文章只是对 ECharts 的 API 学习了一遍后,做的简单记录,结合 react 和 vue 的案例模板会在代码库中陆续实现。

基本使用

1. 初始化实例

注意初始化时,echarts 内部会获取 domclientWidthclientHeight 来计算宽高,如果设置 width、height 为百分比,某些框架(react)会导致,计算出的 clientWidthclientHeight 不符合预期(没有计算完就被获取使用),解决办法一个是计算出确定的像素值后传入,另一个办法是设置定时器,等待新的值计算完直接使用

    <!-- 需要设置宽高 -->
    <div id="main" style="width: 100px;height: 100px"></div>
    const chart = echart.init(document.getElementById('main'));

react 中使用

    render() {
        const {width = '100%', height = '100%'} = this.props;
        return (
            <div 
                className="default-chart" 
                ref={el => this.el = el} 
                style={{width, height}}
            ></div>
        );
    }
    initChart = (el) => {
        return new Promise((resolve) => {
            // 设置定时器,使得获得的 clientWidth clientHeight 符合预期
            setTimeout(() => { 
                this.chart = echarts.init(el, null, {renderer: 'svg', width: 'auto', height: 'auto'});
                resolve();
            }, 0);
        })
    }
    async componentDidMount() { // 变成异步的
        console.log('did mount');
        await this.initChart(this.el);
        this.setOption(this.props.options);
    }

或者等待容器尺寸后重新绘制

    initChart = (el) => {
        /*
            设置定时器调用 echarts 实例的 resize() 方法,重新刷新画布
        */ 
        this.chart = echarts.init(el, null, {renderer: 'svg', width: 'auto', height: 'auto'});
        setTimeout(() => this.chart.resize(), 0);
    }
    componentDidMount() { // 不在需要异步
        console.log('did mount');
        this.initChart(this.el);
        this.setOption(this.props.options);
        window.addEventListener('resize', throttle(this.resize, 100));
    }
2. 异步加载数据

echart 在图标初始化后的任何时候,都可以通过实例的 setOption() 方法直接填入数据,如果需要加载数据,可以在加载数据完成后调用此方法;也可以阶段性的获取数据,然后通过 setOption() 方法注入数据。

    const chart = echart.init(document.getElementById('main'));

    get('/xxx').then(res => chart.setOption(res));
3. 加载动画

echart 提供简单的加载动画

    const chart = echart.init(document.getElementById('main'));

    chart.showLoading();
    get('/xxx').then(res => {
        chart.hideLoading();
        chart.setOption(res);
    }); 
4. 交互组件
  • legend 图例组件
  • title 标题组件
  • visualMap 视觉映射组件
  • dataZoom 数据区域缩放组件
  • timeline 时间线组件
5. 移动端自适应

ECharts 实现了类似 CSS Media Query 的自适应能力

    option = {
        baseOption: { // 这里是基本的『原子option』。
            title: {...},
            legend: {...},
            series: [{...}, {...}, ...],
            ...
        },
        media: [ // 这里定义了 media query 的逐条规则。
            {
                query: { // 这里写规则。
                    minWidth: 200,
                    maxHeight: 300,
                    minAspectRatio: 1.3 // 长宽比
                },   
                option: {       // 这里写此规则满足下的option。
                    legend: {...},
                    ...
                }
            },
            {
                query: {...},   // 第二个规则。
                option: {       // 第二个规则对应的option。
                    legend: {...},
                    ...
                }
            },
            {                   // 这条里没有写规则,表示『默认』,
                option: {       // 即所有规则都不满足时,采纳这个option。
                    legend: {...},
                    ...
                }
            }
        ]
    };
5. 数据的视觉映射

数据可视化是数据到视觉元素的映射过程,ECharts 的每种图表本身就内置了这种映射过程,比如折线图把数据映射到 ‘线’,柱状图 把数据映射到 ‘长度’ 等

ECharts 提供 visualMap 组件来提供通用的视觉映射

ECharts 中的数据,一般存放于 series.data 中,根据图表类型不同,数据的具体形式也可能有些许差异

6. ECharts 中的事件和行为

在 ECharts 的图表中用户的操作将会触发相应的事件,开发者可以监听这些事件,然后通过回调函数做相应的处理,比如跳转到一个地址,或者弹出对话框

    chart.on('click', function (params) {
        console.log('chart in click', params);
    })

鼠标事件的监听函数会得到参数 params ,这是一个包含点击图形的数据信息对象

由组件的交互行为可以触发事件,除此之外也可以在程序里调用方法触发图表行为

    // 调用此方法可以触发图表行为,type对应着动作
    chart.dispatchAction({
        type: ''
    })
7. 切换 canvas 和 svg 渲染

ECharts 默认使用 canvas 渲染,切换到 svg 需要进行一些设置

    import * as echarts from 'echarts/lib/echarts';
    import 'zrender/lib/svg/svg';

    const chart = echarts.init(dom, null, {renderer: 'svg' /* canvas */}); 

API

1. echarts 属性和方法

1. 初始化 echarts.init(dom, theme, opts) 创建实例

用于创建一个 ECharts 实例,不能在单个容器上初始化多个实例

  • dom: 实例容器,一般是一个具有宽高的 div 元素,需要明确指定 style.width | style.height
  • theme: 应用的主题配置对象,也可以是 echarts.registerTheme 注册的主题名称
  • opts: 附加参数
    • renderer: 渲染器配置项 svg|canvas
    • width: 用于指定实例宽度 null/undefined/'auto' 表示实例容器的宽度
    • height: 同上
    • devicePixelRatio: 设备像素比,会默认获取浏览器的 window.devicePixelRatio
    const chart = echarts.init(document.getElementById('main'), null, {
        renderer: 'svg',
        width: 300,
        height: 400
    });
2. echarts.dispose() 销毁实例

实例销毁后无法被使用

3. echarts.getInstanceByDom() 通过容器获取容器上的实例

2. echartsInstance 实例属性与方法

1. instance.group = 'xxx' 用于设置分组信息
2. instance.setOption({}) 用于设置图标配置项

设置图表实例的配置项以及数据,万能接口,所有参数和数据的修改都可以通过它完成,ECharts 会合并新的参数和数据,然后刷新图表,并通过合适的动画变化

    chart.setOption(option, notMerge, lazyUpdate);
  • option: 图表的配置项和数据
  • notMerge: 是否与之前的 option 合并 默认为 false 即为合并
  • lazyUpdate: 在设置完option后是否不立即更新图表,默认为false,即立即更新。
3. instance.getWidth()|getHeight() 获取实例容器宽度|高度
4. instance.getDom()| () 获取实例容器的 DOM | 获取合并后的配置项
5. instance.resize(opts) 改变图表尺寸,在容器大小发生变化时手动调用

参数可以省略,opts如下

  • width: 显式指定实例宽度,单位为像素
  • height: 显式的指定实例的高度
  • silent: 是否禁止抛出事件 默认 false
6. instance.dispatchAction() 手动触发图表行为
7. instance.on('envent', handle) 绑定事件处理函数

ECharts 中事件有两种,一种是鼠标事件,鼠标点击在某个图形上会触发,还有一种是调用 dispatchAction 后触发的事件,每个 action 都会有对应的事件

    chart.on('click', params => console.log(params));
8. instance.off('event, handle) 解绑事件处理函数
9. instance.convertToPixel(finder, value) 转换为像素值

finder 表示定位参数,用来定位,value 表示要被转换的值,返回像素坐标值

暂时理解为,将图形坐标值,转化为对应的像素坐标值

10. instance.convertFromPixel() 从像素值转换

装换像素坐标值到逻辑坐标系上的点,是 convertToPixel 的逆运算

11. instance.containPixel() 判断给定的点是否在指定的坐标系上
12. instance.showLoading()|hideLoading() 显示隐藏加载动画
13. instance.getDataURL() 导出图表图片
> 获取图表对应图片的 base64的URL,可以设置为 Img 标签的 src , 适合 canvas 渲染的图表
14. instance.getConnectedDataURL() 导出联动的图表图片,返回 bas e64

适合 canvas 渲染的图表

15. instance.clear() 清空当前实例

移除实例中所有组件和图表,清空后调用 getOption 方法返回一个{}空对象。

16. instance.dispose()|isDisposed 销毁实例|判断实例是否销毁

3. 鼠标事件事件参数

事件参数是时间对象的数据的各个属性,图表的点击事件,基本参数如下,一些图表还会有附加参数

常用鼠标事件:click, dbclick, mousedown, mouseup, mouseover, mouseout, globalout, contextmenu

    {
        componentType: string, // 点击的图形元素所属组件名称 series 表示系列
        seriesType: string, // 系列类型
        seriesIndex: number, // 系列编号
        seriesName: string, // 系列名称
        name: string, // 数据名称、类目名称
        dataIndex: number, // 数据在传入的 data 数组中的 index
        data: Object, // 传入的原始数据
        value: number|Array, // 传入的数据值
        color: string, // 数据图形的颜色
    }

4. instance.setOption({}) 的配置项

配置项对象的第一层属性名表示相应的组件,属性值则是对应的组件的配置

    chart.setOption({
        title: {},
        legend: {}
        ....
    })
1. title 标题组件
    title: {
        show: true, // 是否显示
        text: 'ECharts 入门示例xxx', // 主标题
        link: 'http://write.blog.csdn.net/postlist', // 主标题链接
        target: 'self', // 'blank' // 页面跳转方式
        textStyle: { // 主标题文字样式
            color: '#333', // 部分 css 样式
        },
        subtext: '简单示例', // 副标题
        sublink: '',
        subtarget: 'blank',
        subtextStyle: {},
        padding: 10, // [t, r, b, l] 标题内边距
        itemCap: 10, // 主副标题间距
        zlevel: 0, // 所有图形的 zelvel 值,用于 canvas 分层,不同的 zlevel 会放置在不同的 canvas 中
        z: 2, // 组件所有图形的 z 值,控制图形的前后顺序,比 zlevel 优先级低,不会创建 canvas
        left: 'center', // left|top|right|bottom 对其属性
        borderWidth: 1,
        borderColor: '#666',
        borderRadius: 4,
    },
2. legend 图例组件

图例组件展现了不同系列的标记、颜色和名字,可以通过点击图例控制哪些系列不显示

    legend: {
        type: 'scroll', // 图例类型 ‘scroll’
        show: true, // 是否显示
        zlevel: 0,
        z: 2,
        left: 'right',
        top: 'bottom', // left|top|right|bottom 显示位置
        width: '100%', // width|height 图例组件的宽高
        heigth: '100%',
        orient: 'vertical', // 图例列表的布局朝向
        align: 'left', // 标记和文本的对其
        padding: 10, // 组件的内边距
        itemGap: 18, // 每项间距
        itemWidth: 20, // itemWidth|itemHeight每项图形宽高
        // formatter: name => `is ${name}`, // 用来格式化图例文本,也可以使用字符串模板
        selectedMode: true, // 图例选择的模式, 默认为 true 表示可选择
        inactiveColor: '#989796', // 图例关闭时的颜色
        selected: {aaa: true, ccc: true}, // 图例选中状态表
        textStyle: {}, // 图例公用文本样式
        tooltip: { // 图例的 tooltip 配置
            show: true
        },
        /*
            图例数据数组,每一项代表一个系列的 name ,
            图例会根据对应系列的图形标记绘制自己的颜色和标记,
            如果没有指定 data 会自动从当前系列中获取 series.name 等指定的纬度,
            可以将每一项写成对象,来配置样式
        */ 
        // data: ['xxx', 'aaa'],
        borderWidth: 1,
        borderColor: '#333',
        pageButtonItemGap: 3, 
    },
3. grid 直角坐标系内绘图网格组件
    grid: {
        show: true, // 是否显示
        left: '5%', // 组件位置 left|top|right|bottom
        width: 'auto', // 设置宽高 width|height
        containLabel: true, // 计算宽高时是否包含了所有标签,用于防止溢出
        backgroundColor: 'rgba(128, 128, 128, 0.5)',
        tooltip: { // 本坐标系特定的 tooltip 设置
            trigger: 'axis' // 设置触发类型 
        }
    },
4. xAxis yAxis 直角坐标系 grid 中的 X 轴 Y 轴
    xAxis: {
        show: true, // 是否显示
        position: 'bottom', // x 轴的位置
        offset: 0, // x 轴相对默认位置的偏移
        type: 'value', // 坐标轴类型 value数值型|category类目轴|time时间轴|log对数轴
        name: 'x 轴', // 坐标轴名称
        nameLocation: 'end', // 坐标轴显示位置
        nameTextStyle: { // 坐标轴文字颜色
            color: '#425aaa'
        },
        nameGap: 5, // 坐标轴名称与轴线之间的距离
        nameRotate: -30, // 坐标轴名字旋转角度
        inverse: false, // 是否是反向坐标轴
        boundaryGap: true, // 边界留白 类目轴为 boolean,非类目轴为 一个数组,记载最大值,最小值延伸范围
        // min: 1, // 坐标轴刻度最小值 ’dataMin‘表示数据在该轴上的最小值,类目轴中可以设置类目序数,也可以是一个函数
        // max: 'dataMax', // 同上
        scale: true, // 只在数值轴中有效,设置为 true 后不会强制包含零刻度,设置 min max 后无效
        splitNumber: 5, // 坐标轴分割段数的预估值,实际显示的会有调整。类目轴无效
        minInterval: 5, // 自动计算坐标轴的最小间隔大小
        silent: false, // 坐标轴是否是静态的无法交互
        triggerEvent: true, // 坐标轴的标签是否响应和触发鼠标事件,默认不响应
        axisLine: { // 坐标轴轴线相关配置
            show: true,
            onZero: true, // 是否相交另一个轴与 0 刻度
            symbol: ['none', 'arrow'], // 轴线两边箭头
            symbolSize: 10, // 轴线箭头大小
            lineStyle: { // 轴线的样式
                color: 'red'
            }
        },
        axisTick: { // 坐标轴刻度相关设置
            show: true,
            alignWithLabel: true, // 保证刻度线和标签对其
            inside: true, // 设置坐标轴刻度朝向
            length: 10, // 设置刻度长度
            lineStyle: {} // 刻度线样式
        },
        axisLabel: { // 坐标轴刻度标签相关设置
            show: true,
            inside: true, // 设置标签朝向
            rotate: -30, // 旋转
            margin: 8, // 与轴线间距
            formatter: '{value} kk', // 内容格式容器
            color: 'blue',
            align: 'center'
        },
        splitLine: { // grid 分割线设置
            show: true, 
            lineStyle: {
                color: 'green'
            }
        },
        splitArea: { // grid 分割区域
            show: true,
            areaStyle: {}
        },
        /*
            data 类目数据
        */
        // data: [23.4, 25.4, 32, 33.4, 38.4, 40, 42] 
    },
5. polar 极坐标系
   polar: { // 极坐标系,可以用于散点图和折线图,每个极坐标系有一个角度轴和一个半径轴
        center: ['50%', '50%'], // 中心点在实例中的位置
        radius: '90%', // 极坐标系半径
        tooltip: { // 提示线
            trigger: 'axis'
        }
    },
6. radiusAxis 极坐标系径向轴

配置与直角坐标系横竖轴一致

   radiusAxis: { // 极坐标系的径向轴, 配置与直角坐标系基本一致
        type: 'category', // 坐标轴类型 类型与直角坐标系一致
        name: '坐标轴名称',
        nameLocation: 'end', // 位置
        nameTextStyle: { // 样式
            color: 'red'
        },
        nameGap: 20, // 与轴线间距
        namRotate: 0, // 旋转
        boundaryGap: true, // 留白
        axisLine: {
            lineStyle: {
                color: '#999',
                type: 'dashed'
            } 
        },
        axisTick: {
            alignWithLabel: true,
            lineStyle: {
                color: '#333'
            }
        },
        axisLabel: {
            rotate: 30,
            fontSize: 10,
        },
        splitLine: {
            show: false,
        },
      data: days
   },
7. angleAxis 极坐标系的角度轴

配置与直角坐标系坐标轴有很多类似

   angleAxis: {
      type: 'category', // 坐标轴类型
      polarIndex: 0, // 角度轴所在的极坐标系索引,默认使用第一个极坐标系
      startAngle: 60, // 起始刻度的角度,默认 90 度 
      clockwise: false, // 是否顺时针增长刻度
      data: hours,
      boundaryGap: false, // 留白
      axisLine: {
         lineStyle: {
            color: '#999',
            type: 'dashed'
         }
      },
      axisTick: {
         show: false
      },
      splitLine: {
         show: true,
         lineStyle: {
            color: ['#aaa', '#ddd'],
            type: 'dashed'
         }
      }
   },
8. radar 雷达图组件
   radar: {
      indicator: [ // 雷达图的指示器,用来指定雷达图中的多个变量(维度)
         {name: '指示器 1', max: 7777}, // name 标签名
         {name: '指示器 2', max: 666, color: '#592dab'}, // color 设置标签颜色
         {name: '指示器 3', max: 3231}, // max,min 最大最小值
         {name: '指示器 4', max: 2432},
         {name: '指示器 5', max: 2424},
         {name: '指示器 6', max: 2323},
      ],
      center: ['50%', '50%'], // 圆心位置
      radius: '70%', // 半径
      startAngle: 15, // 坐标系起始角度
      name: { // 雷达图每个指示器名称的配置项
         show: true, 
         formatter: '/{value}/', // 格式器
         color: '#662762'
      },
      nameGap: 20, // 指示器名称与轴的间距
      splitNumber: 10, // 指示器轴的分割段数
      shape: 'circle', // 雷达图形状 polygon|circle
      axisLine: {
         show: true, 
         symbol: ['none', 'arrow'],
         lineStyle: {
            color: '#aaa'
         }
      },
   },
   series: [{
      name: 'test anme',
      type: 'radar',
      data: [
         {name: 'data one', value: [1000, 666, 321, 2432, 2424, 223]},
         {name: 'data two', value: [73, 346, 1231, 1432, 2224, 23]},
         {name: 'data three', value: [999, 666, 2231, 2132, 424, 1323]}
      ]
   }]
9. dataZoom 区域缩放组件

用来概览数据整体,关注数据细节,有三种类型

  1. 内置型,内置于坐标系中,用户在坐标系中通过鼠标拖拽来缩放
  2. 滑动条型,有单独的滑动条,在滑动条上进行缩放
  3. 框选型, 提供选框进行数据缩放

dataZoom 组件主要是对数轴进行操作,同时存在多个 dataZoom 组件控制同一个数轴,他们会自动联动

   dataZoom: [
      {
         type: 'slider', // 缩放组件类型
         show: true,
         dataBackground: { // 数据阴影的样式 
            lineStyle: {
               color: 'red'
            },
            areaStyle: {
               color: {
                  type: 'linear',
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [
                     {
                        offset: 0,
                        color: 'red' // 0% 处的颜色
                     },
                     {
                        offset: 1,
                        color: 'blue' // 100% 处的颜色
                     }
                  ],
                  globalCoord: false // 缺省为 false
               }
            }
         },
         fillerColor: 'rgba(2, 35, 220, .3)', // 选中范围的填充颜色
         borderColor: '#6a45e2', // 边框颜色
         // handleIcon: '', // 可以设置成图片
         handleStyle: { // 手柄的样式设置
            color: '#892e8a'
         },
         labelPrecision: 'auto', // 显示 label 的小数精度,默认根据数据自动决定
         labelFormatter: 'p{value}p', // 显示 label 的格式化器
         showDetail: true, // 是否在拖拽时显示 label
         showDataShadow: 'auto', // 是否显示数据阴影
         realtime: false, // 是否是实时刷新,设置 false 表示拖拽结束时更新
         textStyle: { // 文字颜色
            color: 'red'
         },
         xAxisIndex: [0], // 设置当前区域缩放组件控制的 x轴,可以控制多个
         // yAxisIndex: [0], // 设置当前区域缩放组件控制的 y轴,可以控制多个
         filterMode: 'weakFilter', // 设置数据过滤模式
         start: 10, // start|end 数据缩放范围百分比
         end: 50, // startValue|endValue 数据窗口范围的具体数值
         minSpan: 30, // 数据窗口的最小百分比
         maxSpan: 70, // 数据窗口的最大百分比
         origin: 'horizontal', // 布局方向
         zoomLock: true, // 是否锁定选择区域大小
         throttle: 200, // 节流设置,设置视图刷新频率
         left: 'center', // left\top\right\bottom 定位
      },
      {
         type: 'inside', // 参数与 slider 类型类似
         disabled: false, // 是否禁用
         xAxisIndex: [0], // 显式的指定控制的 x 轴
         filterMode: 'weakFilter', // 设置过滤模式
      }
   ],
10. visualMap 视觉映射组件,也就是将数据映射到视觉元素

以下是可映射的视觉元素

  • symbol: 图形形状
  • symbolSize: 图形大小
  • color: 图形颜色
  • colorAlpha: 颜色透明度
  • opacity: 透明度
  • colorLightness: 颜色的明暗度, // 以下三个对应 HSL y颜色表示法
  • colorSaturation: 颜色的饱和度
  • colorHue: 颜色的色调

组件可以定义多个,从而可以同时对数据中的多个维度进行视觉映射,组件可以定义为分段型或连续型,通过 type 来区分

{
         type: 'continuous', // 视觉映射的类型
         min: 0, // min|max 指定视觉映射的定义域
         max: 2500,
         range: [0, 2500], // 设置显示范围,默认 [min, max]
         calculable: true, // 是否显示可选定范围的手柄
         realtime: true, // 是否实时刷新视图
         inverse: true, // 是否反转组件
         precision: 1, // 数据展示的精度,小数点后几位
         itemWidth: 20, // itemWidth|itemHeight 组件图形的宽高
         align: 'auto', // 指定组件中手柄和文字的摆放位置
         text: ['High', 'Low'], // 组件两端文本
         textGap: 20, // 文本与组件间距
         show: true, // 组件是否显示,即使不显示,图表视觉映射效果依然存在
         dimension: 1, // 指定数据的那个维度映射到视觉元素上
         seriesIndex: 0, // 对应某个 series.data 。指定映射的数据来源
         hoverLink: true, // 高亮
         inRange: { // 定义选中范围的视觉元素
            color: ['#121122', 'rgba(3,4,5,0.4)', 'red'],
         },
         outOfRange: { // 定义选定范围之外的视觉元素
            color: 'yellow'
         },
         controller: { // 控制器的 inRange|outOfRange 设置
            inRange: {},
            outOfRange: {}
         },
         orient: 'vertical', // 如何放置 visualMap 组件
         formatter: '{value}', // 标签格式化
      },
            {
         type: 'piecewise', // 分段式映射组件
         splitNumber: 5, // 分段
         // pieces: [ // 分段组件每一段的范围,以及样式
         //    {min: 2500},
         //    {min: 1000, max: 2500},
         //    {min:  500, max: 1000},
         //    {min: 200, max: 500},
         //    {max: 200},
         // ],
         // categories: [], 离散型数据不用 pieces 用这个定义
         min: 0,
         max: 2500,
         precision: 0,
         selectedMode: 'multiple', // 选择模式
         minOpen: true, // minOpen|maxOpen 设置会多出超出边界值选块
         maxOpen: true,
         inverse: true, // 反转
         itemWidth: 23, // itemWidth|itemHeight 设置图形宽高
         align: 'left', 
         text: ['H', 'L'], // 两端文本,设置后不显示 label
         // 其他与 连续型组件配置相似
      }
11. tooltip 提示框组件

提示框组件可以设置在多种地方

  • 全局设置 tooltip
  • 设置在坐标系中 grid.tooltip polar.tooltip single.tooltip
  • 设置在系列中 series.tooltip
  • 设置在系列的数据项中 series.data.tooltip
   tooltip: {
      show: true,
      trigger: 'axis', // 触发类型
      axisPointer: { // 坐标轴指示器配置项,指示坐标轴当前刻度的指示器, 优先级低于在坐标轴组件上的同名定义项
         type: 'cross',
         snap: true,
      },
      showContent: true, // 是否显示提示框浮层
      // alwaysShowContent: false, // 焦点移出触发提示框区域后,是否还显示提示框
      triggerOn: 'mousemove|click', // 提示框触发条件
      showDelay: 0, // 浮层显示的延迟
      hideDelay: 100, // 浮层隐藏的延迟
      enterable: false, // 鼠标是否可以进入浮层, 得配合其他属性使用
      confine: true, // 是否把提示框限制在图表区域内
      transitionDuration: 1, // 提示框跟随鼠标移动动画时长
      // position: 'right', // 提示框浮层的位置,默认不设置会跟随鼠标的位置
      formatter: '{a}-{b}-{c}', // 浮层内容格式器
      textStyle: { // 浮层文字样式
         color: 'red'
      },
      extraCssText: '', // 额外附加到图层的 css 样式
   },
12. axisPointer 坐标轴指示器组件
  • 直角坐标系 grid、极坐标系polar、单轴坐标系 single 中的每个轴都由自己的 axisPointer
   axisPointer: {
      show: true,
      type: 'line', // 指示器类型
      snap: true, // 指示器是否自动吸附到点上
      label: { // 坐标轴指示器的文本报标签
         show: true,
         precision: 0, // 标签中数值的精度
         formatter: '-{value}-', // 格式器
         margin: 10, // label 与轴距离
         textStyle: { // 不好使
            color: '#666', 
         },
         // padding: 5, // label 内边距
      },
      lineStyle: { // type: line
         color: '#836521',
         type: 'dashed'
      },
      shadowStyle: {}, // type: shadow
      triggerTooltip: true, // 是否触发 tooltip
      value: null, // 使用 handle 时的初始值设定
      status: 'hide', // 当前状态
      handle: { // 拖拽手柄,适用于触屏
         show: true, 
         // icon: 'image://url', // 手柄图标
         size: 20, 
         margin: 70, // 手柄与轴间距
         color: '#256392', 
         throttle: 40, // 节流更新频率
      },
      link: [], // 联动设置
      triggerOn: 'click', // 提示框触发条件
   },
13. toolbox 工具栏插件
   toolbox: {
      show: true,
      orient: 'vertical', // 方向
      itemSize: 15, // icon 大小
      itemGap: 10, // icon 间隔
      showTitle: true,
      feature: {
         saveAsImage: {
            type: 'svg',
            name: 'test', 
            excludeComponents: ['toolbox', 'legend'], // 忽略的组件
            show: true,
            title: '保存图片',
            // icon: '' // icon 的 svgPath
            iconStyle: {
               color: '#41390d'
            },
            emphasis: {
               iconStyle: {
                  color: '#9976ad'
               }
            },
            pixelRatio: 2, // 保存的图片的分辨率
         },
         restore: { // 配置项还原
            show: true,
         },
         dataView: {
            show: true,
            readOnly: false, // 是否是只读的
            optionToContent: function (opt) { // 定制化展示样式
               let axisData = opt.xAxis[0].data;
               let series = opt.series;
               let table = `<table style="width:100%;text-align:center"><tbody><tr>
                            <td>时间</td>
                            <td> ${series[0].name} </td>
                            </tr>`;
               for (let i = 0, l = axisData.length; i < l; i++) {
                   table += `<tr>
                            <td> ${axisData[i]} </td>
                            <td> ${series[0].data[i]} </td>
                            </tr>`;
               }
               table += '</tbody></table>';
               return table;
            },
         },
         dataZoom: { // 数据区域缩放
            show: true,
            xAxisIndex: [0], // xAxisIndex|yAxisIndex 指定被控制的 x,y 轴
         },
         magicType: { // 动态类型切换
            show: true,
            type: ['line', 'bar'],
            option: { // 对应 type 中的各个类型的配置项
               line: {}, 
            },
            seriesIndex: { // 各个类型对应的系列
               line: [0]
            }
         },
         brush: { // 选框组件的控制按钮, 也可以在 brush.toolbox 中设置
            type: ['rect', 'polygon']
         }
      },
      iconStyle: {
         color: '#61259d'
      }
   },
14. brush 区域选择组件
   brush: {
      toolbox: ['rect', 'polygon', 'lineX', 'lineY', 'keep', 'clear'],
      brushLink: null, // 联动选项
      seriesIndex: 'all', // 指定可以被筛选的系列
      brushType: 'lineX', // 默认刷子类型
      brushMode: 'multiple', // 默认刷子模式
      transformable: true, // 已经选好的选框是否可以被调整形状或平移。
      brushStyle: {}, // 选框默认样式
      throttleType: 'debounce', // 节流的类型
      throttleDelay: 0, // 节流的时间
      inBrush: {}, // 选中范围的视觉元素
      outOfBrush: {}, // 选中范围外的视觉元素 
   },
15. geo 地理坐标系组件
   geo: {
      show: true, 
      map: 'china', // 地图类型, 地图数据需要另外引入,在 'echarts/map/js/china' 中
      roam: true, // 鼠标缩放和平移漫游 scale|move|true(都开启)
      center: [115.97, 29.71], // 当前视角的中心点
      aspectScale: 0.75, // 设置地图长宽比
      boundingCoords: null, // 定义左上角右下角经纬度
      zoom: 1.5, // 当前视角的缩放比例
      scaleLimit: {min: 0.6, max: 1.7}, // 缩放比例限制
      nameMap: {'China': '中国'}, // 自定义区域名称映射
      selectedMode: true, // 是否支持多选
      label: { // 图形上的文本标签,说明图形上的一些数据
         show: true,
         position: 'top', // 标签位置
         distance: 20, // 距离图形元素的距离
         rotate: -30, // 标签旋转
         offset: [100, 100], // 是否对文字进行偏移
         formatter: '{b}:{@score}', // 内容格式器
      },
      itemStyle: { // 地图区域多边形样式
         areaColor: '#323c48',
         borderColor: '#111'
      },
      emphasis: { // 高亮状态下的多边形和标签样式。
         itemStyle: {
            areaColor: '#2a333d'
         }
      },
      regions: [ // 在地图中对特定的区域配置样式。
         {name: '广东', itemStyle: {areaColor: 'red', color: 'red'}}
      ],
      silent: false, // 是否不响应和触发鼠标事件
   },
16. parallel 平行坐标系

平行坐标系适用于对这种多维数据进行可视化分析,每一个维度对应一个坐标轴,每一个数据项是一条线,贯穿多个坐标轴,在坐标轴上可以进行数据选取等操作

   parallel: {
      left: '5%', // left|top|right|bottom 定义组件容器大小
      right: '13%',
      bottom: '10%',
      top: '20%',
      layout: 'horizontal', // 布局方向
      axisExpandable: true, // 坐标轴可扩展,用于维度较多的情况
      axisExpandCenter: 3, // 初始时,以哪个轴为展开中心
      axisExpandCount: 6, // 初始时处于展开状态的轴的数量
      axisExpandWidth: 60, // 展开轴的间距
      axisExpandTriggerOn: 'mousemove', // 触发展开的操作
      parallelAxisDefault: { // 多个坐标轴的一些默认配置项,即 parallelAxis 中每项配置
          type: 'value', // 坐标轴类型
          name: 'AQI指数', // 坐标轴名称
          nameLocation: 'end', // 名称显示位置
          nameGap: 20, // 名称与轴线间距
          nameTextStyle: { // 名称样式
              fontSize: 12
          },
          nameRotate: 15, // 角度
          inverse: false, // 反向
          boundaryGap: false, // 留白
          // min: 'dataMin', // 最小刻度
          // max: 'dataMax', // 最大值
          scale: true, // 不强制包含零刻度
          splitNumber: 5, // 分割段数
          axisLine: { // 坐标轴轴线设置
             lineStyle: {
                color: 'red'
             }
          },
          data: [], // 类目轴中有效,设置数据,默认会从 series.data 中获取
      }
   },
17. parallelAxis 平行坐标系中坐标轴
      {
         dim: 0, // 坐标轴的维度序号
         parallelIndex: 0, // 表示坐标轴定义到哪个坐标系中
         realtime: true, // 是否是实时刷新视图,在筛选的时候
         areaSelectStyle: { // 每个坐标轴上都由一个选框,在这里进行设置样式
            color: 'blue'
         },
         name: schema[0].text, 
         inverse: true, 
         max: 31, 
         nameLocation: 'start'
         ... 其他设置与 parallel.parallelAxisDefault 配置一致
      },
18. singleAxis 单轴
{
      left: '20%', // left|top|right|bottom
      orient: 'horizontal', // 轴的朝向
      type: 'category', // 坐标轴类型
      name: day,
      nameLocation: 'start',
      nameTextStyle: {
         color: '#333',
         fontSize: 16,
      },
      nameGap: 20,
      nameRotate: 15,
      boundaryGap: false, // 留白策略
      inverse: false, // 反向坐标轴
      data: hours,
      top: (idx * 100 / 7 + 5) + '%',
      height: (100 / 7 - 10) + '%',
      axisLabel: {
          interval: 2
      }
   });
19. timeline 时间线组件

timeline 组件,提供了在多个 ECharts option 之间进行切换、播放等操作的功能

公有的配置项,推荐配置在 baseOption 中, timeline 播放切换时,会把 option 数组中的对应option 与 baseOption 进行 merge

      timeline:{
         show: true,
         type: 'slider',
         axisType: 'category', // 轴的类型
         currentIndex: 3, // 当前选中项
         autoPlay: false, // 自动播放
         rewind: true, // 反向播放
         loop: true, // 循环播放
         playInterval: 1000, // 速度
         realtime: true, // 实时更新
         controlPosition: 'right', // 播放按钮位置
         data: ['2002', '2003', '2004', '2005', '2006'], // timeline 数据,每一项可以是数值也可以是配置对象
      },
20. graphic 图形元素组件
      graphic: [
         {
            type: 'group',
            id: 'test-1', // 指定图形元素
            $action: 'merge', // setOption 时指定合并规则 merge|replace|remove
            right: 110, // left|top|right|bottom  元素定位
            bottom: 110,
            bounding: 'raw', // 决定图形元素定位时,是否限制在父元素范围中
            invisible: true, // 节点是否可见
            cursor: 'pointer', // 鼠标悬浮样式
            draggable: true, // 是否可以被拖拽
            progressive: false, // 渐进式渲染
            rotation: Math.PI / 4,
            z: 100,
            ondrag: function (params) {
               console.log('drag', params);
            },
            children: [ // 子节点列表,其中项都是一个图形元素定义。
               {
                  type: 'rect', // 其他图形接口类似
                  left: 'center',
                  top: 'center',
                  z: 100,
                  shape: {
                     width: 400,
                     height: 50
                  },
                  style: {
                     fill: 'rgba(0, 0, 0, 0.3)'
                  }
               },
               {
                  type: 'text',
                  left: 'center',
                  top: 'center',
                  z: 100,
                  style: {
                     fill: '#fff',
                     text: 'haike test'
                  }
               }
            ]
         }
      ],
21. calendar 日历坐标系组件

可切换中西方日历习惯、

   calendar: {
      top: 120, // left|top|right|bottom 限制组件大小
      left: 30,
      right: 30,
      cellSize: 'auto', // 日历每格的大小
      range: '2018', // 日历坐标的范围 ['2017-01-02', '2017-02-23']
      orient: 'vertical', // 日历坐标的布局朝向
      itemStyle: {
         normal: { borderWidth: 0.5 }
      },
      splitLine: {
         // 日历坐标分割线样式
         show: true,
         lineStyle: {
            color: '#12786d'
         }
      },
      itemStyle: {
         // 设置日历格的样式
         color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
               {
                  offset: 0,
                  color: 'red' // 0% 处的颜色
               },
               {
                  offset: 1,
                  color: 'blue' // 100% 处的颜色
               }
            ],
            globalCoord: false // 缺省为 false
         }
      },
      dayLabel: {
         show: true,
         firstDay: 1, // 一周从周几开始
         margin: 10, // 星期八标签与轴线间距
         position: 'start', // 星期的位置
         nameMap: 'cn', // 星期显示效果 en|cn
      },
      monthLabel: { // 月份轴的样式
         show: true,
         align: 'center',
         margin: 10, // 间隔
         position: 'end', // 位置
         nameMap: 'cn', // 显示效果
         formatter: null, // 格式器
      },
      yearLabel: { // 年的样式
         show: true,
         margin: 30, // 间距
         position: 'top', // 位置
      }
   },
22. dataset 数据集组件

ECharts 4 开始支持 数据集 组件用于单独的数据集声明,从而数据可以单独管理,被多个组件复用,并且可以自由指定数据到视觉的映射,使用上方便了很多

const initialOption = {
   title: {
      top: 30,
      left: 'center',
      text: '2018 每天步数'
   },
   tooltip: {},
   grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
   },
   xAxis: [
      {
         type: 'category',
      }
   ],
   yAxis: {},
   dataset: {
   //    source: [ // 横向表示数据组数, 纵向表示维度,第一行或者第一列表示名称
   //       ['product', '2015', '2016', '2017'], // 第一行是维度信息
   //       ['Matcha Latte', 43.3, 85.8, 93.7],
   //       ['Milk Tea', 83.1, 73.4, 55.1],
   //       ['Cheese Cocoa', 86.4, 65.2, 82.5],
   //       ['Walnut Brownie', 72.4, 53.9, 39.1]
   //   ],
      source: [
         ['Matcha Latte', 43.3, 85.8, 93.7],
         ['Milk Tea', 83.1, 73.4, 55.1],
         ['Cheese Cocoa', 86.4, 65.2, 82.5],
         ['Walnut Brownie', 72.4, 53.9, 39.1]
      ],
      dimensions: ['product', '2015', '2016', '2017'], // 维度信息
      sourceHeader: null, // 第一行是否是维度信息
   },
   // series: [ 
   //    {type: 'bar'}, // 对应纵向几个系列
   //    {type: 'bar'},
   //    {type: 'bar'},
   // ]
   series: [
      { type: 'bar'},
      { type: 'bar'},
      { type: 'bar'}
   ]
};
23. series 系列列表

每个系列通过 type 决定自己的图表类型

查看代码库 vue-ECharts-template

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐