彩票走势图

amCharts之JavaScript/HTML5 Charts应用教程三:加载和解析CSV数据

原创|使用教程|编辑:郝浩|2013-03-29 16:15:56.000|阅读 4821 次

概述:本教程演示如何从文件中加载和解析CSV数据。使用amCharts的JavaScript/HTML5 Charts,并且不用FlashOrJavaScript后备脚本,这篇教程将会给你一些启发,同时还能帮助你更好的理解amCharts的JavaScript图表

# 慧都年终大促·界面/图表报表/文档/IDE等千款热门软控件火热促销中 >>

相关链接:

在本教程中,我将用一个小小的例子演示如何从一个文件中加载和解析CSV数据。假如你使用的是amCharts的JavaScript/HTML5 Charts,并且不用下载包中的FlashOrJavaScript后备脚本,那么这篇教程将会给你一些启发,同时还能帮助你更好的理解amCharts的JavaScript图表。

准备数据文件

首先下载JavaScript/HTML5 Charts,由于这里我们不用flash图表,复制 amcharts/javascript文件夹到你的工作目录中,找到 basicSamples/javaScriptOnly文件夹并复制serial.html文件到这个文件夹下。用文本编辑器打开文件并修复JavaScript文件路径,删除路径最开头的../../amcharts/。如果用浏览器打开serial.html,你将会看到以下图表:

amcharts,JavaScript/HTML5 Charts,JS图表,柱状图

图表的数据放在html文件中,它不是基于日期的,所以我们来创建一个简单的文本文件data.txt并添加一些数据到里头,这些数据是不规则的:

2011-02-23,133034,12105.78
2011-02-24,122290,12068.50
2011-02-25,383603,12130.45
2011-02-28,125285,12226.34
2011-03-01,118042,12058.02
2011-03-02,102500,12066.80
2011-03-03,434047,12258.20
2011-03-04,422374,12169.88
2011-03-07,396473,12090.03
2011-03-08,453142,12214.38

将其保存为serial.html文件,然后回到文本编辑器打开这个文件。删除chartData变量和它的所有数据,还有window.onload方法的所有内容。

加载数据

  • 添加一个方法,加载外部数据到脚本中
  • 添加复制的方法
  • 当窗口加载时调用loadCSV函数

示例代码如下:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "//www.w3.org/TR/html4/strict.dtd">

<html>

    <head>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

        <title>amCharts Example</title> 

        <link rel="stylesheet" href="style.css" type="text/css">

        <script src="javascript/amcharts.js" type="text/javascript"></script>

        

        <script type="text/javascript">

        var chart;

        window.onload = function() {

            loadCSV("data.txt");

        }

        function loadCSV(file) {

            if (window.XMLHttpRequest) {

                // IE7+, Firefox, Chrome, Opera, Safari

                var request = new XMLHttpRequest();

            }

            else {

                // code for IE6, IE5

                var request = new ActiveXObject('Microsoft.XMLHTTP');

            }

// load data. 'false' indicates that further script

// is not executed until data is loaded and parsed

            request.open('GET', file, false);

            request.send();

            parseCSV(request.responseText);

        }

        function parseCSV(data){

            alert(data);

        }

        </script>

    </head>

    <body style="background-color:#EEEEEE">

        <div id="chartdiv" style="width:600px; height:400px; background-color:#FFFFFF"></div>

    </body>

</html>

用浏览器打开serial.html文件,需要一个弹出菜单打开所有数据,但这里还没有实现。加载外部数据需要所有的文件放在web服务器上,如果你简单的从硬盘中打开文件,这个脚本不会运行。这意味着必须将所有的文件都上传到网站上。或者在计算机上安装Web服务器,将所有的文件放到本地主机文件夹中,然后在本地查看页面。

注意,数据文件可以是动态的,这意味着你可以用php,asp或者其他脚本加载数据。

解析数据

在脚本顶部声明dataProvider变量,下面是加载和解析数据的完整脚本:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "//www.w3.org/TR/html4/strict.dtd">

<html>

    <head>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

        <title>amCharts Example</title> 

        <link rel="stylesheet" href="style.css" type="text/css">

        <script src="javascript/amcharts.js" type="text/javascript"></script>

        

        <script type="text/javascript">

        var chart;

        var dataProvider;

        window.onload = function() {

            loadCSV("data.txt");

        }

        function loadCSV(file) {

            if (window.XMLHttpRequest) {

                // IE7+, Firefox, Chrome, Opera, Safari

                var request = new XMLHttpRequest();

            }

            else {

                // code for IE6, IE5

                var request = new ActiveXObject('Microsoft.XMLHTTP');

            }

            // load

            request.open('GET', file, false);

            request.send();

            parseCSV(request.responseText);

        }

        function parseCSV(data){ 

            //replace UNIX new lines

            data = data.replace (/\r\n/g, "\n");

            //replace MAC new lines

            data = data.replace (/\r/g, "\n");

            //split into rows

            var rows = data.split("\n");

            // create array which will hold our data:

            dataProvider = [];

            

            // loop through all rows

            for (var i = 0; i < rows.length; i++){

                // this line helps to skip empty rows

                if (rows[i]) {                    

                    // our columns are separated by comma

                    var column = rows[i].split(",");  

                    

                    // column is array now 

                    // first item is date

                    var date = column[0];

                    // second item is value of the second column

                    var value1 = column[1];

                    // third item is value of the fird column 

                    var value2 = column[2];

                    

                    // create object which contains all these items:

                    var dataObject = {date:date, value1:value1, value2:value2};

                    // add object to dataProvider array

                    dataProvider.push(dataObject);

                }

            }

        }

        </script>

    </head>

    <body style="background-color:#EEEEEE">

        <div id="chartdiv" style="width:600px; height:400px; background-color:#FFFFFF"></div>

    </body>

</html>

创建图表

 接下来创建图表,首先设置一个新的方法叫creatChart并初始化 AmSerialChart:

function createChart(){

    // chart variable is declared in the top

    chart = new AmCharts.AmSerialChart();

    // here we tell the chart name of category field in our data provider.

    // we called it "date" (look at parseCSV method)

    chart.categoryField = "date";

    

    // chart must have a graph

    var graph = new AmCharts.AmGraph();

    // graph should know at what field from data provider it should get values.

    // let's assign value1 field for this graph

    graph.valueField = "value1";

    // and add graph to the chart

    chart.addGraph(graph);            

    // 'chartdiv' is id of a container where our chart will be                        

    chart.write('chartdiv');

}

当页面加载时调用这个方法:

window.onload = function() {

    createChart();            

    loadCSV("data.txt");                                    

}

最后,设置图表的data provider,然后让图表重建,方法是在parseCSV方法的最后添加这几行:

// set data provider to the chart

chart.dataProvider = dataProvider;

// this will force chart to rebuild using new data            

chart.validateData();

下面是完整的代码:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "//www.w3.org/TR/html4/strict.dtd">

<html>

    <head>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

        <title>amCharts Example</title> 

        <link rel="stylesheet" href="style.css" type="text/css">

        <script src="javascript/amcharts.js" type="text/javascript"></script>

        

        <script type="text/javascript">

        

        // declaring variables

        var chart;

        var dataProvider;

        

        // this method called after all page contents are loaded

        window.onload = function() {

            createChart();            

            loadCSV("data.txt");                                    

        }

        

        // method which loads external data

        function loadCSV(file) {

            if (window.XMLHttpRequest) {

                // IE7+, Firefox, Chrome, Opera, Safari

                var request = new XMLHttpRequest();

            }

            else {

                // code for IE6, IE5

                var request = new ActiveXObject('Microsoft.XMLHTTP');

            }

            // load

            request.open('GET', file, false);

            request.send();

            parseCSV(request.responseText);

        }

        

        // method which parses csv data

        function parseCSV(data){ 

            //replace UNIX new lines

            data = data.replace (/\r\n/g, "\n");

            //replace MAC new lines

            data = data.replace (/\r/g, "\n");

            //split into rows

            var rows = data.split("\n");

            // create array which will hold our data:

            dataProvider = [];

            

            // loop through all rows

            for (var i = 0; i < rows.length; i++){

                // this line helps to skip empty rows

                if (rows[i]) {                    

                    // our columns are separated by comma

                    var column = rows[i].split(",");  

                    

                    // column is array now 

                    // first item is date

                    var date = column[0];

                    // second item is value of the second column

                    var value1 = column[1];

                    // third item is value of the fird column 

                    var value2 = column[2];

                    

                    // create object which contains all these items:

                    var dataObject = {date:date, value1:value1, value2:value2};

                    // add object to dataProvider array

                    dataProvider.push(dataObject);

                }

            }

            // set data provider to the chart

            chart.dataProvider = dataProvider;

            // this will force chart to rebuild using new data            

            chart.validateData();

        }

        

        // method which creates chart

        function createChart(){

            // chart variable is declared in the top

            chart = new AmCharts.AmSerialChart();

            // here we tell the chart name of category 

            // field in our data provider.

            // we called it "date" (look at parseCSV method)

            chart.categoryField = "date";

            

            // chart must have a graph

            var graph = new AmCharts.AmGraph();

            // graph should know at what field from data

            // provider it should get values.

            // let's assign value1 field for this graph

            graph.valueField = "value1";

            // and add graph to the chart

            chart.addGraph(graph);            

            // 'chartdiv' is id of a container 

            // where our chart will be                        

            chart.write('chartdiv');

        }

        </script>

    </head>

    <body style="background-color:#EEEEEE">

        <div id="chartdiv" style="width:600px; height:400px; background-color:#FFFFFF"></div>

    </body>

</html>

在浏览器中打开serial.html,就能得到下图中的图表:

amCharts的JavaScript/HTML5 Charts图表,线形图表

怎么样?经过上面的解析,对amCharts的JavaScript/HTML5 Charts图表应该有了进一步的了解吧。

 


标签:

本站文章除注明转载外,均为本站原创或翻译。欢迎任何形式的转载,但请务必注明出处、不得修改原文相关链接,如果存在内容上的异议请邮件反馈至chenjj@pclwef.cn

文章转载自:慧都控件

为你推荐

  • 推荐视频
  • 推荐活动
  • 推荐产品
  • 推荐文章
  • 慧都慧问
扫码咨询


添加微信 立即咨询

电话咨询

客服热线
023-68661681

TOP