Echarts 多曲线“断点”问题解决方法

Echarts 用来做可视化曲线是非常优秀的一个库。建议使用 Echarts 作为项目的可视化图标库时,仔细研究 官方实例,根据需求来选择类似的示例,下载实例模板来开发,节省时间,减少出错,提高效率。

最近在项目中遇到了一个棘手的问题:

1. 在图表中要显示多条曲线

2. 每一条曲线的横坐标(时间轴)的时间点不一定相同

对于单条曲线,时间不同的话,时间点就会比总时间点少,这时,只在对应的时间上显示点,然后连线。

首先说明解决方法(以两条曲线为例):

1. 获取到全部时间,作为横坐标的数据。也就是 xAxis.data 的值。如 xAxis.data = ["10:00:00", "11:00:00", "12:00:00", "13:00:00", "14:00:00", "15:00:00"]

2. 在各条曲线上,它们的值采用数组类型,也就是 series.data 的值。 如 series.data[0] = [['10:00:00', '120'], ['12:00:00', '132'], ['14:00:00', '101']],series.data[1] = [['11:00:00', '220'], ['13:00:00', '132'], ['15:00:00', '201']]

 

上面例子展示了横坐标一共有六个点,第一条曲线只在第 1、3、5 个上有值,第二条曲线只在第 2、4 、6 个点上有值,这个时候需要注意一点的是,series.data 值的数组的第一个值要和 xAxis.data 数组中的值能对应上,不然不能绘制曲线

下面详细说明:

一、该项目用到的框架是 Angular ,在 Angular 中使用 Echarts ,首先要先引入 Echarts 库

1. 在静态资源文件 assets 中新建一个脚本文件夹 scripts 里面存放 echarts.min.js

2. 在 Angular CLI 配置文件 .angular-cli.json 中 ["apps"]["scripts"] 中引入这个脚本

二、在需要使用的组件中先声明 echarts

declare const echarts: any;

三、绘制曲线(参考示例:Echarts 堆叠线

/*绘制曲线*/
curvePlotting() {
    let detectRecordCurveContainer = document.getElementById("detectRecordCurveContainer"); // 获取到绘制曲线的容器
    let myChart = echarts.init(detectRecordCurveContainer);  // 初始化

    const DetectRecordCurveInfo = {
      title: {
        text: this.getTitleTextData(),  // 选择的项目名称,该图表的标题
        textStyle: {
          color: '#333',
          fontWeight: 'normal',
          fontSize: 18
        },
        left: 'center'
      },
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        type: 'scroll', // 当检测属性过多时,水平滚动
        bottom: 0,
        data: this.getLegendData()   // 各条曲线的名称,数组类型
      },
      grid: {
        left: 60,  // 比css中padding-left多40px
        right: 60, // 比css中padding-right多40px
        bottom: 40,
        containLabel: true
      },
      toolbox: {
        right: 30,  // 设置'保存图片'文本的位置
        feature: {
          saveAsImage: {}
        }
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: this.getTimeData()   // 横坐标,时间
      },
      yAxis: {
        type: 'value'
      },
      series: this.getSeries()  // 曲线的点
    };
    if (DetectRecordCurveInfo && typeof DetectRecordCurveInfo === "object") {  // 如果获取到了数据且数据是对象,DetectRecordCurveInfo 是父组件传来的可用的数据信息
      myChart.setOption(DetectRecordCurveInfo, true);
    }
  }

 

posted @ 2018-12-20 15:31  艾前端  阅读(2761)  评论(0编辑  收藏  举报