欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

数据可视化展示——echarts

程序员文章站 2022-07-14 16:31:28
...

数据可视化展示概述

  • 什么是数据可视化
数据可视化:一副图片最伟大的价值莫过于它能够使得我们实际看到的比我们期望看到的内容更加丰富
  • 使用Spark SQL API完成统计分析为什么要可视化
①视觉获取到的信息要远远比我们感觉到的要多
②而且可视化后可以帮助我们分析数据更加全面
③人的记忆力有限,可以帮我们更直观的观察数据
  • 常见的可视化框架
    1)echarts
    2)highcharts
    3)D3.js
    4)HUE 
    5)Zeppelin

基于Echarts实现数据可视化

前端部分代码实现

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>主站最受欢迎的TopN课程</title>
    <!--引入Echarts文件-->
    <script src="js/echarts.min.js"></script>
    <script src="js/jquery.js"></script>
</head>
<body>
<!-- 为 ECharts 准备一个具备大小(宽高)的 DOM -->
<div id="main" style="width: 600px;height:400px;"></div>

<script type="text/javascript">
    // 基于准备好的dom,初始化echarts实例
    var myChart = echarts.init(document.getElementById('main'));

    // 指定图表的配置项和数据
    option = {
        title : {
            text: '主站最受欢迎的TopN课程',
            x:'center'
        },
        tooltip : {
            trigger: 'item',
            formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        legend: {
            orient: 'vertical',
            left: 'left',
            data: getCourcesName()
        },
        series : [
            {
                name: '访问次数',
                type: 'pie',
                radius : '55%',
                center: ['50%', '60%'],
                data:getCources(),
                itemStyle: {
                    emphasis: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }
        ]
    };

    function getCources() {
        var courses = [];
        $.ajax({
            type:"GET",
            url:"stat?day=20170511",
            dataType:'json',
            async:false,
            success:function (result) {
                for (var i=0;i<result.length;i++){
                    courses.push({"value":result[i].value,"name":result[i].name})
                }
            }
        })
        return courses;
    }
    function getCourcesName() {
        var coursesName = [];
        $.ajax({
            type:"GET",
            url:"stat?day=20170511",
            dataType:'json',
            async:false,
            success:function (result) {
                for (var i=0;i<result.length;i++){
                    coursesName.push({"name":result[i].name})
                }
            }
        })
        return coursesName;
    }
    // 使用刚指定的配置项和数据显示图表。
    myChart.setOption(option);
</script>
</body>
</html>

后端采用Servlet实现

        1.项目结构
数据可视化展示——echarts
         2.实体类的实现
/**
 * Created by *** 2017/12/26 12:12
 * 前端AJAX请求所需value 和 name
 */
public class VideoAccessTopN {
    private String name;
    private long value;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public long getValue() {
        return value;
    }

    public void setValue(long value) {
        this.value = value;
    }
}
3.DAO层的实现
import com.imooc.domain.VideoAccessTopN;
import com.imooc.utils.MySQLUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by *** 2017/12/26 11:07
 * 面向接口编程
 */
public class VideoAccessTopNDao {

    static Map<String, String> courses = new HashMap<String, String>();

    static {
        courses.put("4000", "MySQL优化");
        courses.put("4500", "Crontab");
        courses.put("4600", "Swift");
        courses.put("14322", "SpringData");
        courses.put("14390", "R");
        courses.put("14540", "机器学习");
        courses.put("14623", "redis");
        courses.put("14704", "Docker");
    }

    /**
     * 根据课程编号查询课程名称
     * @param id
     * @return
     */
    public String getCourceName(String id) {
        return courses.get(id);
    }

    /**
     * 根据day查询当天最受欢迎的Top5课程
     *
     * @param day
     * @return
     */
    public List<VideoAccessTopN> query(String day) {
        List<VideoAccessTopN> list = new ArrayList<VideoAccessTopN>();

        Connection connection = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            connection = MySQLUtils.getConnection();
            String sql = "select cms_id,times from day_video_access_topn_stat where day = ? order by times desc limit 5";
            pstmt = connection.prepareStatement(sql);
            pstmt.setString(1, day);
            rs = pstmt.executeQuery();

            VideoAccessTopN domain = null;
            while (rs.next()) {
                domain = new VideoAccessTopN();
                /**
                 * TODO....在页面三应该显示的是课程名称,而此时显示的是课程编号
                 *
                 * 如何根据课程编号去获取课程名称呢?
                 * 编号和名称是有一个对应关系的,一般是存放在关系型数据库
                 */

                domain.setName(getCourceName(rs.getLong("cms_id") + ""));
                domain.setValue(rs.getLong("times"));
                list.add(domain);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            MySQLUtils.release(connection, pstmt, rs);
        }

        return list;
    }

    public static void main(String[] args) {
        VideoAccessTopNDao dao = new VideoAccessTopNDao();
        List<VideoAccessTopN> list = dao.query("20170511");
        for (VideoAccessTopN result : list) {
            System.out.println(result.getName() + " , " + result.getValue());
        }

    }
}
     4.MySql工具类的实现
import java.sql.*;

/**
 * Created by *** 2017/12/26 11:10
 * 操作MySQL的工具类
 */
public class MySQLUtils {

    private static final String USERNAME = "root";
    private static final String PASSWORD = "root";
    private static final String DRIVERCLASS = "com.mysql.jdbc.Driver";
    private static final String URL = "jdbc:mysql://172.17.66.51:3306/imooc_project";

    /**
     * 数据库连接
     *
     * @return
     */
    public static Connection getConnection() {
        Connection connection = null;

        try {
            Class.forName(DRIVERCLASS);

            connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }

    /**
     * 释放资源
     *
     * @param connection
     * @param patmt
     * @param rs
     */
    public static void release(Connection connection, PreparedStatement patmt, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (patmt != null) {
            try {
                patmt.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        System.out.println(getConnection());
    }
}
   5.web层的实现
import com.imooc.dao.VideoAccessTopNDao;
import com.imooc.domain.VideoAccessTopN;
import net.sf.json.JSONArray;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * Created by **** 2017/12/26 11:03
 * 最受欢迎的TOP N课程
 * Web ==> Service ==> DAO
 */
public class VideoAccessTopNServlet extends HttpServlet {

    VideoAccessTopNDao dao;

    @Override
    public void init() throws ServletException {
        dao = new VideoAccessTopNDao();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String day = req.getParameter("day");

        List<VideoAccessTopN> results = dao.query(day);

        JSONArray json = JSONArray.fromObject(results);

        resp.setContentType("text/html;charset=utf-8");

        PrintWriter writer = resp.getWriter();
        writer.println(json);
        writer.flush();
        writer.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
6.运行结果
数据可视化展示——echarts