前言

因为比赛需要将数据可视化,在前端以折线图的形式展现,而Echart就是一个基于 JavaScript 的开源可视化图表库。成功实现后写一篇博客记录一下过程~~

一、官方文档

先直接上链接https://echarts.apache.org/zh/index.html官方链接

官方文档有各种的图示例,也可以直接在页面上编辑代码运行代码
在这里插入图片描述
在这里插入图片描述

二、最终效果展示

横坐标是都是时间,第一个图的纵坐标是检测值的分数,取值范围为[0-1],不带面积的折线图;
第二图的纵坐标是检测情况,取值为[0/1],是标准的就为1,不标准的就为0,带面积的折线图。
在这里插入图片描述在这里插入图片描述

三、使用本地数据加载折线图

1.代码

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>echarts</title>
    <link rel="stylesheet" href="index.css" />
</head>
<body>
    <div class="container">
        <!-- 折线图 -->
        <div id="showchart">
            <div id="pschart" class="chart"></div>
            <div id="schart" class="chart"></div>
        </div>
    </div>
    <!-- jQuery文件 -->
    <script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
    <!-- 引入 echart 所需的JavaScript文件-->>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/4.3.0/echarts.min.js"></script>
    <script src="index.js" type="text/javascript" charset="utf-8"></script>
</body>
</html>
#showchart{
    background-color: #4F4F4F;
}
.chart{
    height: 300px;
    width: 500px;
}
var pschart = echarts.init(document.getElementById('pschart')); //初始化echart图表
var schart = echarts.init(document.getElementById('schart'));
var ps_option = {
    title: {
        text: 'ps',
        textStyle: {
            color: '#FFFAFA',
        }
    },
    xAxis: {
        type: 'category', //数值轴的值,数字或字符都可以、time时间轴、catagory类目轴
        boundaryGap: false,//坐标轴两边的留白
        data: [1,2,3,4,5],
        splitLine: {
            show: false
        },
        axisLine: {
            lineStyle: {
                color: '#FFFAFA',
            }
        },
        axisTick: {
            show: false
        }
    },
    yAxis: {
        type: 'value',//数值轴
        splitLine: {
            show: false
        },
        axisLine: {
            lineStyle: {
                color: '#FFFAFA',
            }
        },
    },
    series: [
        {
            name: 'p',
            type: 'line', //折线图
            step: 'start',
            colorBy: '#FF0000',
            showSymbol: false,//不展示标记的图形
            data: [0.9,0.8,0,0.95,0.88],
        },
    ]
};
var s_option = {
    title: {
        text: 'standard plane',
        textStyle: {
            color: '#FFFAFA',
        }
    },
    xAxis: {
        type: 'category', //数值轴的值,数字或字符都可以、time时间轴、catagory类目轴
        boundaryGap: false,
        data: [1,2,3,4,5],
        splitLine: {
            show: false
        },
        axisLine: {
            lineStyle: {
                color: '#FFFAFA',
            }
        },
        axisTick: {
            show: false
        }
    },
    yAxis: {
        type: 'value',//数值轴
        splitLine: {
            show: false
        },
        axisLine: {
            lineStyle: {
                color: '#FFFAFA',
            }
        },
    },
    series: [
        {
            name: 's',
            type: 'line', //折线图
            step: 'start',
            areaStyle: 
            showSymbol: false,
            data: [0,1,1,1,0]
        },
    ]
};
pschart.setOption(ps_option);    //载入图表
schart.setOption(s_option);

2.执行效果和代码说明

在这里插入图片描述
html的文件很简单,定义两个有宽高的div,然后命名id,引入echarts的js文件。在js文件中,先用id初始化图,再定义图的option,最后用option去载入图,即pschart.setOption(ps_option)。

3.常用组件的属性介绍

1.X轴/Y轴/线(xAxis/xAxis/series)

x轴和y轴的属性类似,就介绍一种即可
在这里插入图片描述

series代表一种图,它的type也有很多,比如line-折线图,bar-柱状图,pie-饼图,我用到折线图,所以就介绍折线图了
在这里插入图片描述

2.其余组件(title/legend/grid)

在这里插入图片描述
【注】这里只是把常用的,或者说我这个项目中用到的属性列出来了,如果你还需要对轴线或者线的展示有其他的要求,就去翻阅官方文档吧
在这里插入图片描述

四、异步数据加载折线图(ajax请求)

之前展示图的数据是在初始化后setOption中直接填入,已经写死了。但在实际应用中,肯定需要动态加载数据。ECharts 中实现异步数据的更新非常简单,在图表初始化后不管任何时候只要通过 jQuery 等工具异步获取数据后通过 setOption 填入数据和配置项就行。

js中使用JQuery内置的Ajax方法请求,其url为 “/getdata”,后端定义’/getdata’对应的路由,返回一个json形式的data。

1.前端js代码

var ps_option = {
    title: {
        text: 'ps',
        textStyle: {
            color: '#FFFAFA',
        }
    },
    grid: {
        left: '7%',
        right: '10%',
        top: '30%',
        bottom: '20%',
        containLabel: true
    },
    legend: {
        right: '0%',
        data: ['p'],
    },
    xAxis: {
        type: 'category', 
        boundaryGap: false,
        data: [],
        splitLine: {
            show: false
        },
        axisLine: {
            lineStyle: {
                color: '#FFFAFA',
            }
        },
        axisTick: {
            show: false
        }
    },
    yAxis: {
        type: 'value',//数值轴
        min: 0,
        max: 1,
        interval: 10,
        //不展示y轴分隔符
        splitLine: {
            show: false
        },
        axisLine: {
            lineStyle: {
                color: '#FFFAFA',
            }
        },
    },
    series: [
        {
            name: 'p',
            type: 'line', //折线图
            step: 'start',
            colorBy: '#FF0000',
            showSymbol: false,//不展示标记的图形
            data: [],
        },
    ]
};
var s_option = {
    title: {
        text: 'standard',
        textStyle: {
            color: '#FFFAFA',
        }
    },
    grid: {
        left: '7%',
        right: '10%',
        top: '30%',
        bottom: '20%',
        containLabel: true
    },
    legend: {
        right: '0%',
        data: ['s'],
    },
    xAxis: {
        type: 'category', 
        boundaryGap: false,
        data: [],
        splitLine: {
            show: false
        },
        axisLine: {
            lineStyle: {
                color: '#FFFAFA',
            }
        },
        axisLabel: {
            show: false,
        },
        axisTick: {
            show: false
        }
    },
    yAxis: {
        type: 'value',//数值轴
        min: 0,
        max: 1,
        interval: 10,
        splitLine: {
            show: false
        },
        axisLine: {
            lineStyle: {
                color: '#FFFAFA',
            }
        },
    },
    series: [
        {
            name: 's',
            type: 'line', //折线图
            step: 'start',
            showSymbol: false,
            data: []
        },
    ]
};
pschart.setOption(ps_option);    //载入图表
schart.setOption(s_option);

//发送ajax数据请求
$(function getdata() {
    var frame = []; // frame数组
    var p = [];//ps数组
    var s = []//s数组
    $.ajax({    //使用JQuery内置的Ajax方法
        type: "post",        //post请求方式
        async: false,        //异步请求(同步请求将会锁住浏览器,用户其他操作必须等待请求完成才可以执行)
        url: "/getdata",   
        data: {},
        dataType: "json",        //返回数据形式为json
        success: function (result) {
            // console.log(result);
            //请求成功时执行该函数内容,result即为服务器返回的json对象
            if (result != null && result.length > 0) {
                for (var i = 0; i < result.length; i++) {
                    frame.push(result[i].frame)
                    p.push(result[i].p);        
                    s.push(result[i].s);
                }
                // console.log(frame)
                pschart.setOption({        //载入数据
                    xAxis: {
                        data: frame    //填入X轴数据
                    },
                    series: [    //填入系列(内容)数据
                        {
                            // 根据名字对应到相应的系列
                            name: 'p',
                            lineStyle: {
                                color: '#fbfb46',
                                width: 1,
                            },
                            data: p,
                        },
                    ]
                }); 
                schart.setOption({        //载入数据
                    xAxis: {
                        data: frame    //填入X轴数据
                    },
                    series: [    //填入系列(内容)数据
                        {
                            name: 's', 
                            areaStyle: {
                                color: '#1b56e4',
                                opacity: 0.5,
                            },
                            lineStyle: {
                                color: '#4F4F4F',
                                width: 0.5,
                            },
                            data: s
                        },
                    ]
                });
            }
            else {
                //返回的数据为空时显示提示信息
                alert("图表请求数据为空,您可以稍后再试!");
                pschart.hideLoading();
                schart.hideLoading();
            }

        },
        error: function (errorMsg) {
            //请求失败时执行该函数
            alert("图表请求数据失败,可能是服务器开小差了");
            pschart.hideLoading();
            schart.hideLoading();
        }
    })
})

2.后端代码(python实现,flask框架)

from flask import Flask,render_template
app = Flask(__name__)

def get_chartdata():
    data=[]
    with open("./static/data/results.txt", "r") as f:
        for line in f:
            dic ={}
            line = line.strip('\n')
            temp = line1.split(' ') 
            dic['frame'] = int(temp[0])
            dic['p'] = temp[1]
            dic['s'] = temp[2]
            data.append(dic)
    return data

@app.route('/')
def index():
    return render_template('index.html')
@app.route("/getdata", methods = ['POST','GET'])
def showcharts():
    data= get_chartdata()
    return jsonify(data)

if __name__ == '__main__':
    app.run()

总结

echarts的功能很强大,提供的组件和属性也很多。刚开始学习的时候,先实现最简单的图形,等图能够展示到前端后,再一步一步的更改样式和添加功能,不要想一口吃成个大胖子!!

更多推荐