码迷,mamicode.com
首页 > 其他好文 > 详细

Echarts 学习系列(3)-Echarts动态数据交互

时间:2019-08-16 18:57:29      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:插入数据   内蒙古   you   开发环境   def   conf   ati   styles   element   

写在前面


上一小节,我们总结了折线(面积)图、柱状(条形)图、饼(圆环)图类型的图表。

但是,都是静态的。接下来的,这一小节,总结的是Echarts 动态数据的交换。

前置条件


开发环境:win10 家庭版

开发工具:Visual Studio 2019

数据库:MySQL

数据连接工具:Navicat Premium

使用技术:.Net Mvc+Dapper

创建数据库


//创建 sys_visitoronhour
DROP TABLE IF EXISTS `sys_visitoronhour`;
CREATE TABLE `sys_visitoronhour` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `Houer_name` int(11) DEFAULT NULL COMMENT '小时',
  `Hour_time` int(11) DEFAULT NULL COMMENT '次数',
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=24 DEFAULT CHARSET=utf8;

//插入数据
INSERT INTO `sys_visitoronhour` VALUES ('1', '1', '111');
INSERT INTO `sys_visitoronhour` VALUES ('2', '2', '223');
INSERT INTO `sys_visitoronhour` VALUES ('3', '3', '456');
INSERT INTO `sys_visitoronhour` VALUES ('4', '4', '432');
INSERT INTO `sys_visitoronhour` VALUES ('5', '5', '412');
INSERT INTO `sys_visitoronhour` VALUES ('6', '6', '321');
INSERT INTO `sys_visitoronhour` VALUES ('7', '7', '342');
INSERT INTO `sys_visitoronhour` VALUES ('8', '8', '341');
INSERT INTO `sys_visitoronhour` VALUES ('9', '9', '324');
INSERT INTO `sys_visitoronhour` VALUES ('10', '10', '456');
INSERT INTO `sys_visitoronhour` VALUES ('11', '11', '654');
INSERT INTO `sys_visitoronhour` VALUES ('12', '12', '546');
INSERT INTO `sys_visitoronhour` VALUES ('13', '13', '654');
INSERT INTO `sys_visitoronhour` VALUES ('14', '14', '765');
INSERT INTO `sys_visitoronhour` VALUES ('15', '15', '657');
INSERT INTO `sys_visitoronhour` VALUES ('16', '16', '667');
INSERT INTO `sys_visitoronhour` VALUES ('17', '17', '789');
INSERT INTO `sys_visitoronhour` VALUES ('18', '18', '987');
INSERT INTO `sys_visitoronhour` VALUES ('19', '19', '897');
INSERT INTO `sys_visitoronhour` VALUES ('20', '20', '888');
INSERT INTO `sys_visitoronhour` VALUES ('21', '21', '988');
INSERT INTO `sys_visitoronhour` VALUES ('22', '22', '768');
INSERT INTO `sys_visitoronhour` VALUES ('23', '23', '399');

//创建 sys_visitoronprovince
DROP TABLE IF EXISTS `sys_visitoronprovince`;
CREATE TABLE `sys_visitoronprovince` (
  `Id` int(36) NOT NULL AUTO_INCREMENT COMMENT 'Id自增',
  `Visitors_Province_Name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '省份',
  `Visitors_Time` int(11) DEFAULT NULL COMMENT '访问次数',
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=51 DEFAULT CHARSET=utf8;

//插入数据

INSERT INTO `sys_visitoronprovince` VALUES ('1', '北京', '223');
INSERT INTO `sys_visitoronprovince` VALUES ('5', '天津', '332');
INSERT INTO `sys_visitoronprovince` VALUES ('7', '上海', '442');
INSERT INTO `sys_visitoronprovince` VALUES ('11', '重庆', '442');
INSERT INTO `sys_visitoronprovince` VALUES ('14', '内蒙古自治区', '552');
INSERT INTO `sys_visitoronprovince` VALUES ('17', '新疆维吾尔自治区', '664');
INSERT INTO `sys_visitoronprovince` VALUES ('20', '西藏自治区', '223');
INSERT INTO `sys_visitoronprovince` VALUES ('24', '宁夏回族自治区', '556');
INSERT INTO `sys_visitoronprovince` VALUES ('26', '广西壮族自治区', '321');
INSERT INTO `sys_visitoronprovince` VALUES ('28', '黑龙江省', '432');
INSERT INTO `sys_visitoronprovince` VALUES ('29', '吉林省', '456');
INSERT INTO `sys_visitoronprovince` VALUES ('30', '辽宁省', '432');
INSERT INTO `sys_visitoronprovince` VALUES ('31', '河北省', '345');
INSERT INTO `sys_visitoronprovince` VALUES ('32', '山西省', '121');
INSERT INTO `sys_visitoronprovince` VALUES ('33', '青海省', '232');
INSERT INTO `sys_visitoronprovince` VALUES ('34', '山东省', '421');
INSERT INTO `sys_visitoronprovince` VALUES ('35', '河南省', '512');
INSERT INTO `sys_visitoronprovince` VALUES ('36', '江苏省', '123');
INSERT INTO `sys_visitoronprovince` VALUES ('37', '安徽省', '425');
INSERT INTO `sys_visitoronprovince` VALUES ('38', '浙江省', '321');
INSERT INTO `sys_visitoronprovince` VALUES ('39', '福建省', '232');
INSERT INTO `sys_visitoronprovince` VALUES ('40', '江西省', '211');
INSERT INTO `sys_visitoronprovince` VALUES ('41', '湖南省', '344');
INSERT INTO `sys_visitoronprovince` VALUES ('42', '湖北省', '151');
INSERT INTO `sys_visitoronprovince` VALUES ('43', '广东省', '242');
INSERT INTO `sys_visitoronprovince` VALUES ('44', '台湾省', '125');
INSERT INTO `sys_visitoronprovince` VALUES ('45', '海南省', '111');
INSERT INTO `sys_visitoronprovince` VALUES ('46', '甘肃省', '222');
INSERT INTO `sys_visitoronprovince` VALUES ('47', '陕西省', '333');
INSERT INTO `sys_visitoronprovince` VALUES ('48', '四川省', '444');
INSERT INTO `sys_visitoronprovince` VALUES ('49', '贵州省', '555');
INSERT INTO `sys_visitoronprovince` VALUES ('50', '云南省', '666');

创建项目


【1】.打开Visual Studio 2019 创建空的Mvc 项目

技术图片
【2】.打开web.config节点下去除 BrowserLink

<add key="vs:EnableBrowserLink" value="false" />

【3】.在下 创建链接字符串

<connectionStrings>
    <add name="mq" connectionString="server=localhost;uid=root;pwd=root;Database=mysqldemodb;Charset=utf8;Allow User Variables=True;"/>
  </connectionStrings>

【4】.在项目中 创建lib文件夹 存放下载好的Echarts和其他的插件

技术图片

【5】.在View文件夹中 创建Share文件夹

【6】.在Share文件夹中 创建**_LayoutIndex**布局页 引用Echarts、主题和其他插件脚本、样式

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    <link href="~/lib/layui/css/layui.css" rel="stylesheet" />
    <link href="~/lib/layer/theme/default/layer.css" rel="stylesheet" />
    <script src="~/lib/jquery/jquery-1.12.4.min.js"></script>
    <script src="~/lib/layer/layer.js"></script>
    <script src="~/lib/layui/layui.js"></script>
    <script src="~/lib/echarts/echarts.min.js"></script>
    <script src="~/lib/echarts/walden.js"></script>
    <style>
        .layout {
            margin: 20px;
            padding-left: 15px;
            padding-right: 15px;
            margin-bottom: 70px;
            border: 1px solid #ddd;
            border-radius: 10px;
        }
    </style>
</head>
<body>
    @RenderBody()
</body>
</html>

【7】.在Controllers文件夹 创建IndexController 控制器

【8】.在IndexController控制器 创建Index视图 引用**_LayoutIndex**布局页

技术图片

安装程序包


【1】安装 MySQL.Data 安装命令

PM> Install-Package MySql.Data

技术图片

【2】安装 Dapper 安装命令

Install-Package Dapper

技术图片

柱状图


【1】在Index视图中

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Share/_LayoutIndex.cshtml";
}
<div class="layui-fluid">
    <div class="layout">
        <fieldset class="layui-elem-field layui-field-title"><legend>动态图表</legend></fieldset>
        <div class="layui-row">
            <div class="layui-col-md12">
                <div id="main" style="width: 100%;height:400px;"></div>
            </div>
        </div>
    </div>
</div>

【2】脚本

var myChart1 = echarts.init(document.getElementById('main'), 'walden');
myChart1.setOption({
            tooltip: { trigger: 'axis' },
            legend: { data: ['访问量'] },
            calculable: true,
            xAxis: [
                {
                    type: 'category',
                    data: [],
                    axisLabel: {
                        show: true,
                        textStyle: { color: '#000' },
                        rotate: 25,
                        interval: 0,
                    }
                }
            ],
            yAxis: [
                {
                    type: 'value'
                }
            ],
            series: [
                {
                    name: '访问量',
                    type: 'bar',
                    data: [],
                    markPoint: {
                        data: [
                            { type: 'max', name: '最大值' },
                            { type: 'min', name: '最小值' }
                        ]
                    },
                    markLine: {
                        data: [
                            { type: 'average', name: '平均值' }
                        ]
                    }
                },
            ]
});
Get_load();
//text: 文本内容
//maskColor: 背景色
//textColor:文本颜色
myChart1.showLoading('default', { text: '统计中,请稍候...', maskColor: '#404a59', textColor: '#fff', });
function Get_load() {
       var xvalue = [];
       var yvalue = [];
        $.ajax({
                url: "../Index/Area_Times",
                type: "Get",
                async: false,
         }).done(function (msg) {
                if ($.isEmptyObject(msg) == false) {
                    $.each(msg, function (i, obj) {
                        xvalue.push(obj.Visitors_Province_Name);
                        yvalue.push(obj.Visitors_Time);
                    });
                    myChart1.setOption({
                        xAxis: [{ data: xvalue }],
                        series: [{ data: yvalue }]
                    });
                    setTimeout(function () { myChart1.hideLoading(); }, 1000);
                }
            }).fail(function (error) { });
        }

【3】在IndexController 控制器中

 #region 地区访问次数
public JsonResult Area_Times() {
      using (var mqconns = new MySqlConnection(mqcon)) {
              string sql = "select * from v_Visitor_Area";
              var result = mqconns.Query<sys_visitorOnProvince>(sql);
              return Json(result,JsonRequestBehavior.AllowGet);
       }
}
#endregion

效果:

技术图片

图表的详细


有时候我们需要通过点击图表的某一列,想查询选择的这一列的详细数据。

以下,我们来讲一下,如何可以通过选中某一列跳转到对应的数据。

我们就以柱状图为列子~


【1】首先,我们需要在IndexController控制器中 创建Detial方法 获取前台传过来的值

 public ActionResult Detial(string Id) {
          ViewBag.Id = Id;
          return View();
}

【2】其次,我们需要在IndexController控制器中 创建AreaByname_Times方法 用于接收值

     public JsonResult AreaByname_Times() {
            using (var mqconns = new MySqlConnection(mqcon)) {
                string paraname = Request["paraname"];
                string sql = "select * from sys_visitoronprovince where 1=1";
                if (paraname == "华东地区")
                {
                    sql += " and (Visitors_Province_Name LIKE '%山东%' OR ";
                    sql += " Visitors_Province_Name LIKE '%江苏%' OR";
                    sql += " Visitors_Province_Name LIKE '%上海%' OR";
                    sql += " Visitors_Province_Name LIKE '%浙江%' OR";
                    sql += " Visitors_Province_Name LIKE '%安徽%' OR";
                    sql += " Visitors_Province_Name LIKE '%福建%' OR";
                    sql += " Visitors_Province_Name LIKE '%江西%')";
                }
                else if (paraname == "华南地区") {
                    sql += " and (Visitors_Province_Name LIKE '%广东%' OR";
                    sql += " Visitors_Province_Name LIKE '%广西%' OR";
                    sql += " Visitors_Province_Name LIKE '%海南%')";
                }
                else if (paraname == "华中地区")
                {
                    sql += " and (Visitors_Province_Name LIKE '%河南%' OR";
                    sql += " Visitors_Province_Name LIKE '%湖南%' OR";
                    sql += " Visitors_Province_Name LIKE '%湖北%')";
                }
                else if (paraname == "华北地区")
                {
                    sql += " and (Visitors_Province_Name LIKE '%北京%' OR";
                    sql += " Visitors_Province_Name LIKE '%天津%' OR";
                    sql += " Visitors_Province_Name LIKE '%河北%' OR";
                    sql += " Visitors_Province_Name LIKE '%山西%' OR ";
                    sql += " Visitors_Province_Name LIKE '%内蒙古%')";
                }
                else if (paraname == "西北地区")
                {
                    sql += " and (Visitors_Province_Name LIKE '%宁夏%' OR";
                    sql += " Visitors_Province_Name LIKE '%青海%' OR";
                    sql += " Visitors_Province_Name LIKE '%陕西%' OR";
                    sql += " Visitors_Province_Name LIKE '%甘肃%' OR ";
                    sql += " Visitors_Province_Name LIKE '%新疆%')";
                }
                else if (paraname == "西南地区")
                {
                    sql += " and (Visitors_Province_Name LIKE '%四川%' OR";
                    sql += " Visitors_Province_Name LIKE '%贵州%' OR";
                    sql += " Visitors_Province_Name LIKE '%云南%' OR";
                    sql += " Visitors_Province_Name LIKE '%重庆%' OR ";
                    sql += " Visitors_Province_Name LIKE '%西藏%')";
                }
                else if (paraname == "东北地区")
                {
                    sql += " and (Visitors_Province_Name LIKE '%辽宁%' OR";
                    sql += " Visitors_Province_Name LIKE '%吉林%' OR";
                    sql += " Visitors_Province_Name LIKE '%黑龙江%')";
                }
                var result = mqconns.Query<sys_visitorOnProvince>(sql);
                return Json(result,JsonRequestBehavior.AllowGet);
            }
        }

【3】在Detail 视图

@{
    ViewBag.Title = "Detial";
    Layout = "~/Views/Share/_LayoutIndex.cshtml";
}
<div class="layui-fluid">
    <div class="layout">
        <table class="layui-table " lay-skin="line" id="tb">
            <thead>
                <tr>
                    <th>序号</th>
                    <th>地区名称</th>
                    <th>访问次数</th>
                </tr>
            </thead>
        </table>
    </div>
</div>

【4】创建脚本

<script type="text/javascript">
    $(function () {
        var id = '@ViewBag.id';
        $.get("../Index/AreaByname_Times?paraname=" + id, function (msg) {
            if ($.isEmptyObject(msg) == false) {
                var str_tb = "";
                $("#tb tr:gt(0)").remove();
                $.each(msg, function (i, obj) {
                    str_tb += "<tr>";
                    str_tb += "<td>" + (i + 1) + "</td>";
                    str_tb += "<td>" + obj.Visitors_Province_Name + "</td>";
                    str_tb += "<td>" + obj.Visitors_Time + "</td>";
                    str_tb += "</tr>";
                });
                $(str_tb).appendTo("#tb");
            }
        });
    });
</script>

效果:

技术图片

曲线图


【1】在Index 视图中

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Share/_LayoutIndex.cshtml";
}
<div class="layui-fluid">
    <div class="layout">
        <fieldset class="layui-elem-field layui-field-title"><legend>动态图表</legend></fieldset>
        <div class="layui-row">
            <div class="layui-col-md12">
                <div id="main1" style="width: 100%;height:400px;"></div>
            </div>
        </div>
    </div>
</div>

【2】脚本

 var myChart = echarts.init(document.getElementById('main'), 'walden');
        myChart.setOption({
            tooltip: { trigger: 'axis' },
            legend: { data: ['每天访问量'] },
            calculable: true,
            xAxis: [
                {
                    type: 'category',
                    boundaryGap: false,
                    data: []
                }
            ],
            yAxis: [
                {
                    type: 'value'
                }
            ],
            series: [
                {
                    name: '每天访问量',
                    type: 'line',
                    stack: '访问次数',
                    data: []
                },
            ]
        });

        Get_load();
        //text: 文本内容
        //maskColor: 背景色
        //textColor:文本颜色
        myChart.showLoading('default', { text: '统计中,请稍候...', maskColor: '#404a59', textColor: '#fff', });
        function Get_load() {
            var xvalue = [];
            var yvalue = [];
            $.ajax({
                url: "../Index/SingleBar",
                type: "Get",
                async: false,
            }).done(function (msg) {
                if ($.isEmptyObject(msg) == false) {
                    $.each(msg, function (i, obj) {
                        xvalue.push(obj.Houer_name);
                        yvalue.push(obj.Hour_time);
                    });
                    myChart.setOption({
                        xAxis: [{ data: xvalue }],
                        series: [{ data: yvalue }]
                    });
                    setTimeout(function () { myChart.hideLoading(); }, 1000);
                }
            }).fail(function (error) { });
        }
    }

【3】在IndexController控制器中

#region 获取24小时访问次数
        /// <summary>
        /// 获取24小时访问次数
        /// </summary>
        /// <returns></returns>
        public JsonResult SingleBar()
        {
            using (var mqconns = new MySqlConnection(mqcon))
            {
                string sql = "select * from sys_visitorOnHour ";
                var result = mqconns.Query<sys_visitorOnHour>(sql);
                return Json(result, JsonRequestBehavior.AllowGet);
            }
        }
#endregion

效果图:

技术图片

饼图


【1】在Index 视图中

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Share/_LayoutIndex.cshtml";
}
<div class="layui-fluid">
    <div class="layout">
        <fieldset class="layui-elem-field layui-field-title"><legend>动态图表</legend></fieldset>
        <div class="layui-row">
            <div class="layui-col-md12">
                <div id="main1" style="width: 100%;height:400px;"></div>
            </div>
        </div>
    </div>
</div>

【2】脚本

        var myChart2 = echarts.init(document.getElementById('main2'), 'walden');
        myChart2.setOption({
            title: {
                text: '民族自治区访问量',
                x: 'center'
            },
            tooltip: {
                trigger: 'item',
                formatter: "{b} : {c} ({d}%)"
            },
            legend: {
                orient: 'vertical',
                x: 'left',
                data: []
            },
            calculable: true,
            series: [
                {
                    name: '访问来源',
                    type: 'pie',
                    radius: '55%',
                    center: ['50%', '60%'],
                    data: []
                }
            ]
        });
        Get_load();
        //text: 文本内容
        //maskColor: 背景色
        //textColor:文本颜色
        myChart1.showLoading('default', { text: '统计中,请稍候...', maskColor: '#404a59', textColor: '#fff', });
        function Get_load() {
            var xvalue = [];
            var yvalue = [];
            $.ajax({
                url: "../Index/Native_Times",
                type: "Get",
                async: false,
            }).done(function (msg) {
                if ($.isEmptyObject(msg) == false) {
                    $.each(msg, function (i, obj) {
                        xvalue.push(obj.Visitors_Province_Name);
                        yvalue.push({ value: obj.Visitors_Time, name: '' + obj.Visitors_Province_Name + '' });
                    });
                    myChart2.setOption({
                        legend: { data: xvalue },
                        series: [{ data: yvalue }]
                    });
                    setTimeout(function () { myChart2.hideLoading(); }, 1000);
                }
            }).fail(function (error) { });
        }

【3】在IndexController控制器中

#region 自治区访问量
public JsonResult Native_Times() {
            using (var mqconns =new MySqlConnection(mqcon)) {
                string sql = "select * from sys_visitoronprovince ";
                sql += "where (Visitors_Province_Name='内蒙古自治区' ";
                sql += "or Visitors_Province_Name='广西壮族自治区'";
                sql += "or Visitors_Province_Name='宁夏回族自治区'";
                sql += "or Visitors_Province_Name='新疆维吾尔自治区' ";
                sql += "or Visitors_Province_Name='西藏自治区') ORDER BY Visitors_Time desc";
                var result = mqconns.Query<sys_visitorOnProvince>(sql);
                return Json(result,JsonRequestBehavior.AllowGet);
            }
}
#endregion

效果:

技术图片

Echarts 学习系列(3)-Echarts动态数据交互

标签:插入数据   内蒙古   you   开发环境   def   conf   ati   styles   element   

原文地址:https://www.cnblogs.com/ZengJiaLin/p/11356966.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!