好久没有写echarts的文章了,主要是一直以来的项目没有用到echarts的。在最近的一个项目中又用到了echarts,因为还得考虑echarts2.0最新的报表样式,所以采用了echarts2.0,支持地图、变化瀑布图等等。今天先分享一个线状态和柱状图联动的例子。
效果图:
当点击月份的时候,出现第一个报表数据,点击月份的每一个节点,出现下面按照地区分类的柱状图,我们就成为A报表和B报表吧。
下面一步一步的贴出代码和说明
1、首先是有数据,我定义了A报表的3个数据:用户总数、用户认证总数、以及X轴的数据。同时每个日期对应一组城市数据,我采用数组的方式存放。
请看一下实体:
public partial class MonthWeekCity
{
/// <summary>
/// 月份日期
/// </summary>
public DateTime MonthDate { get; set; }
/// <summary>
/// 描述。为月 或者周几 周几
/// </summary>
public string DateText { get; set; }
/// <summary>
/// 总量
/// </summary>
public int AllCount { get; set; }
/// <summary>
/// 认证总量
/// </summary>
public int AuthCount { get; set; }
/// <summary>
/// 该时间内的城市数据列表
/// </summary>
public List<CityData> CityList { get; set; }
}
public partial class CityData
{
public City Cityinfo { get; set; }
public int AllCount { get; set; }
public int AuthCount { get; set; }
}
然后我通过一般处理程序ashx返回数据,我这个数据是从数据库取的,大家可以自行修改:
返回数据集合:
private List<MonthWeekCity> GetMonthList()
{
List<MonthWeekCity> list = new List<MonthWeekCity>();
DateTime date = CheckResponse.GetDateTimeResponse("dt");
ShopStay ds = new ShopStay();
try
{
IAnalysisService APService = KtContainer.Instance.Resolve<IAnalysisService>();
//本月第一天时间
DateTime dt_First = date.AddDays(1 - (date.Day));
//获得某年某月的天数
int year = date.Date.Year;
int month = date.Date.Month;
int dayCount = DateTime.DaysInMonth(year, month);
DateTime dt_Last = dt_First.AddDays(dayCount - 1);
List<Tb_Statistic> listcity = new List<Tb_Statistic>();
listcity = APService.GetCityDayCount(dt_First, dt_Last, 0);
for (int i = 0; i <= dayCount; i++)
{
MonthWeekCity oneday = new MonthWeekCity();
oneday.MonthDate = dt_First.AddDays(i);
oneday.CityList = new List<CityData>();
oneday.AuthCount = 0;
oneday.AllCount = 0;
list.Add(oneday);
}
foreach (Tb_Statistic cd in listcity)
{
MonthWeekCity temp = list.SingleOrDefault(a => a.MonthDate == cd.StatisticDate);
if (temp == null)
{
}
else
{
temp.AuthCount = temp.AuthCount + cd.AuthenNum;
temp.AllCount = temp.AllCount + cd.AllNum;
temp.CityList.Add(new CityData { AllCount = cd.AllNum, AuthCount = cd.AuthenNum, Cityinfo = cd.city });
}
}
return list;
}
2、html结构
<%@ Page Title="" Language="C#" MasterPageFile="~/Content.master" AutoEventWireup="true" CodeFile="MonthWeekGroup.aspx.cs" Inherits="Page_NewStat_MonthWeekGroup" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<div id="content">
<!-- content starts -->
<div>
<ul class="breadcrumb">
<li>首页 <span class="divider">/</span>
</li>
<li><a href="#">活跃用户分析</a> </li>
</ul>
</div>
<div class="row-fluid sortable">
<div class="box-content">
<fieldset>
<div class="control-group ">
<div class="controls">
选择月份:<input type="text" style="width:100px;" id="SDate"
onfocus="WdatePicker({dateFmt:'yyyy年MM月',readOnly:true,onpicked:btnGetData,maxDate:'%yyyy-%MM'})" />
<span id="divlast">
</span>
</div>
</div>
</fieldset>
<div class="clearfix"></div>
<!-- 为ECharts准备一个具备大小(宽高)的Dom -->
<div id="mainmonth" style="height:400px"></div>
<div id="mainmonthcity" style="height:300px"></div>
</div>
<div class="box-content">
<fieldset>
<div class="control-group ">
<div class="controls">
选择周:
<input type="text" style="width:100px;" id="SDate2"
onfocus="WdatePicker({dateFmt:'yyyy年WW周',readOnly:true,onpicked:btnGetData,maxDate:'%yyyy-%WW'})" />
</div>
</div>
</fieldset>
<div class="clearfix"></div>
<div id="divTiShi" style=" display:none;">正在统计请稍后......</div>
<!-- 为ECharts准备一个具备大小(宽高)的Dom -->
<div id="mainweek" style="height:400px"></div>
<div id="mainweekcity" style="height:300px"></div>
</div>
<!--/row-->
<!-- content ends -->
</div>
</div>
<!--/#content.span10-->
<script src="../../js/echart2.2.1/build/dist/echarts.js"></script>
<script src="../../BusinessJs/NewStat/MonthWeek.js"></script>
</asp:Content>
<div id="mainmonth" style="height:400px"></div> A报表容器
<div id="mainmonthcity" style="height:300px"></div> B报表容器
<script src="../../js/echart2.2.1/build/dist/echarts.js"></script> 这段是引用echarts。这是echarts2.0中最新的一种方式。
http://echarts.baidu.com/doc/doc.html#引入ECharts2
3、关键JS代码:
题外话:生成最近的日期
function LoadLastMonth() {
var html = "";
var thismonth = new Date();
for (var i = 1;i < 10; i++) {
var months = thismonth.DateAdd('m', -i);
html = html + " <a onclick='ClickGetData(\"" + months.Format("yyyy年MM月") + "\");'>" + months.Format("yyyy年MM月") + "</a>";
}
$("#divlast").html(html);
}
js日期的格式化请看:[Javacript对Date日期的格式化及转换]
配置参数:
// 路径配置
require.config({
paths: {
echarts: '../../js/echart2.2.1/build/dist'
}
});
js ajax获取数据,并绑定A报表,绑定A报表的时候设置点击事件,因为代码不好完全分离开写,我就全贴出来
var staticsdt;
$(document).ready(function () {
$("#SDate").val((new Date()).Format("yyyy年MM月"));
LoadLastMonth();
btnGetData();
});
function LoadLastMonth() {
var html = "";
var thismonth = new Date();
for (var i = 1;i < 10; i++) {
var months = thismonth.DateAdd('m', -i);
html = html + " <a onclick='ClickGetData(\"" + months.Format("yyyy年MM月") + "\");'>" + months.Format("yyyy年MM月") + "</a>";
}
$("#divlast").html(html);
}
function ClickGetData(datee) {
$("#SDate").val(datee);
btnGetData();
}
function btnGetData() {
staticsdt = $("#SDate").val();
// 使用
require(
[
'echarts',
'echarts/chart/line' // 使用柱状图就加载bar模块,按需加载
],
showdatacllback
);
}
var echarts;
function showdatacllback(ec) {
echarts = ec;
GetDetailData(ec);
}
var MonthData;
function GetDetailData(ec) {
var AjaxUrl = "../../Service/MonthWeekStat.ashx";
if (staticsdt.length == 0) {
alert("请选择月份进行统计"); return;
}
$.ajax({
type: "post",
dataType: 'json',
url: AjaxUrl,
data: {
dt: staticsdt,
oper: "month"
},
success: function (data, textStatus) {
if (data != null) {
var customfre = eval(data);
//设置点击事件
var ecConfig = require('echarts/config');
if (customfre != null && customfre != "undefined") {
var Xdata = new Array();
var MonthAllCount = new Array();
var MonthRenZhengCount = new Array();
var myChart = ec.init(document.getElementById('mainmonth'));
customfre.sort();
$.each(customfre, function (i, val) {
Xdata.push((new Date(val.MonthDate)).Format("yyyy-MM-dd"));
MonthRenZhengCount.push(val.AuthCount);
MonthAllCount.push(val.AllCount);
});
MonthData = customfre;
//oneday.MonthDate = cd.StatisticDate;
//oneday.CityList = new List<CityData>();
//oneday.AuthCount = oneday.AuthCount + cd.AuthenNum;
//oneday.AllCount = oneday.AllCount + cd.AllNum;
//oneday.CityList.Add(new CityData { AllCount=cd.AllNum, AuthCount=cd.AuthenNum, Cityinfo=cd.city});
//---------------------------------------------------------------------------------------------------------------
var option = {
title: {
text: staticsdt + '--月分析',
subtext: '活跃用户'
},
tooltip: {
trigger: 'axis'
},
legend: {
data: ['用户总数', '用户认证总数']
},
toolbox: {
show: false,
feature: {
mark: { show: true },
dataView: { show: true, readOnly: false },
magicType: { show: true, type: ['line'] },
restore: { show: true },
saveAsImage: { show: true }
}
},
calculable: true,
xAxis: [
{
type: 'category',
boundaryGap: false,
data: Xdata
}
],
yAxis: [
{
type: 'value',
axisLabel: {
formatter: '{value}'
}
}
],
series: [
{
name: '用户总数',
type: 'line',
data: MonthAllCount,
markLine: {
data: [
{ type: 'average', name: '平均值' }
]
}
},
{
name: '用户认证总数',
type: 'line',
data: MonthRenZhengCount,
markLine: {
data: [
{ type: 'average', name: '平均值' }
]
}
}
]
};
myChart.setOption(option);
myChart.on(ecConfig.EVENT.CLICK, function (param) {
var selected = param;
var date = selected.name;
OpenPage(date);
})
//---------------------------------------------------------------------------------------------------------------
}
else {
alert("加载数据失败!"); return;
}
}
},
complete: function (XMLHttpRequest, textStatus) {
},
error: function (e) {
alert("加载数据失败!"); return;
}
});
}
function OpenPage(datet) {
SelectedMonthDate = datet;
// 使用
require(
[
'echarts',
'echarts/chart/bar' // 使用柱状图就加载bar模块,按需加载
],
showdatacllback2
);
}
var SelectedMonthDate;
function showdatacllback2(ec) {
var onday = null;
$.each(MonthData, function (i, val) {
if ((new Date(val.MonthDate)).Format("yyyy-MM-dd") == SelectedMonthDate) {
onday = val;
}
});
if (onday == null) { return; }
var Xdata = new Array();
var MonthAllCount = new Array();
var MonthRenZhengCount = new Array();
var myChart = ec.init(document.getElementById('mainmonthcity'));
onday.CityList.sort();
$.each(onday.CityList, function (i, val) {
Xdata.push(val.Cityinfo.Name);
MonthRenZhengCount.push(val.AuthCount);
MonthAllCount.push(val.AllCount);
});
var option = {
title: {
text: SelectedMonthDate + '--按照城市',
subtext: '城市用户'
},
tooltip: {
trigger: 'axis',
axisPointer: { // 坐标轴指示器,坐标轴触发有效
type: 'shadow' // 默认为直线,可选为:'line' | 'shadow'
}
},
legend: {
data: ['用户总数', '认证用户数']
},
toolbox: {
show: false,
orient: 'vertical',
x: 'right',
y: 'center',
feature: {
mark: { show: true },
dataView: { show: true, readOnly: false },
magicType: { show: true, type: ['bar'] },
restore: { show: true },
saveAsImage: { show: true }
}
},
calculable: true,
xAxis: [
{
type: 'category',
data: Xdata
}
],
yAxis: [
{
type: 'value'
}
],
series: [
{
name: '用户总数',
type: 'bar', stack: '认证用户数',
data: MonthAllCount
},
{
name: '认证用户数',
type: 'bar',
stack: '用户总数',
data: MonthRenZhengCount
}
]
};
myChart.setOption(option);
//myChart.on(ecConfig.EVENT.CLICK, function (param) {
// var selected = param;
// var date = selected.name;
// OpenPage(date);
//})
}
1
绑定echarts的事件,必须要引用config文件:
var ecConfig = require('echarts/config');
然后根据你要的事件,进行处理:
myChart.on(ecConfig.EVENT.CLICK, function (param) {
var selected = param;
var date = selected.name;
OpenPage(date);
})