`

Charts JavaScript Tutorials. Part 2. Loading External data.

 
阅读更多

 

 
 

Saturday, March 12, 2011

amCharts JavaScript Tutorials. Part 2. Loading External data.

 

In this tutorial we’ll produce a simple example of how to load and parse csv data from a file.

First, download amCharts package and unzip it. Copy amcharts folder from a package to your working dir. Then go to samples folder and copy lineWithDateBasedData.html to the same working dir. If you open this file with a browser, you won’t see anything – paths to amCharts files should be fixed first. Open lineWithDateBasedData.html with text editor and fix paths (delete ../) to the amcharts.js and serial.js files:

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

There is one more path which should be fixed:

chart.pathToImages = "amcharts/images/";

Now, if you open this file, you should see this chart:

 2tut1

Data of this chart is generated html file, so it’s not good for us – we want to load external data.

Lets create a simple text file, called data.txt and add some data to it – first column contains dates and the second one has some numbers. Note, our data is irregular – it has gaps at weekends:

2011-02-23,133034
2011-02-24,122290
2011-02-25,383603
2011-02-28,125285
2011-03-01,118042
2011-03-02,102500
2011-03-03,434047
2011-03-04,422374
2011-03-07,396473
2011-03-08,453142

First column has date and two other columns – some numbers. Save this file to the same folder as lineWithDateBasedData.html file and then go back to the editor with lineWithDateBasedData.html file opened. Delete generateChartData method and also the line where it is called.

Loading data

Add a method which loads external data to the script:

function loadCSV(file) {
    var request;
    if (window.XMLHttpRequest) {
        // IE7+, Firefox, Chrome, Opera, Safari
        request = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        request = new ActiveXObject('Microsoft.XMLHTTP');
    }
    // load
    request.open('GET', file, false);
    request.send();
    parseCSV(request.responseText);
}

And another method which will parse data:

function parseCSV(data){
    alert(data);
}

Now call loadCSV function in the end of AmCharts.ready method (after the chart is created):

loadCSV("data.txt");

To check if data is loaded properly we added alert(data) line in the parseCSV methid. Try to open lineWithDateBasedData.html with your browser now. As you guess, a popup should open with all the data from our data file. But… most likely it won’t. Loading external data requires all the files to be on a web server, this script won’t run if you simply open the file from your hard drive. This means you have to upload all the files to your web site, or, if you have a web server installed on your computer, move all your files to your localhost folder and view the page via your localhost address. Now, you should get the popup. Here you can find html with all the steps made so far (and see the popup with data). View source of this page in case you can’t get the same result.

Note, your data file can be dynamic. This means you can load data from php, asp or any other script which could access data base and generate data you need. This tutorial explains how you can use PHP to get data from mySQL data base and generate JSON string which can by used by the chart.

Parsing data

Delete alert(data); line so it won’t bug you anymore. Next we’ll split our data into rows. As new line can be “marked” as \n, also as \r and as \r\n, first we’ll replace \r and \r\n into \n, and only then split data string. The following lines should go to the parseCSV method:

//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");

Now we have array of rows and we’ll loop through this array to extract data. Before this, I declared variable dataProvider in the top of the script. Below is full script which loads and parses data:

// 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];

        // create object which contains all these items:
        var dataObject = {
            date: date,
            visits: value1
        };
        // add object to chartData array
        chartData.push(dataObject);
    }
    chart.validateData();
}

I called the value field in the data “visits”, because we already have a graph created with valueField set as “visits”. It’s up to you how you want to call it. However don’t forget to change graph.valueField if you use a different name. Same with “date” field – you can give any name to it, but then you should also change chart.categoryField value.

If you analyze the code of the chart, you’ll notice this line: categoryAxis.parseDates = true; - this means our chart parses dates. When chart parses dates, you have two options 1) pass category values as Date objects; 2) set data date format for the chart. As our original example used date objects, and when we loaded data, we have simple date strings, we have to do the 2nd option. So you should add this line:

chart.dataDateFormat = "YYYY-MM-DD";

Side note – some users might notice, that in this particular case the chart will work even without this line. This happens because this particular date format is parsed automatically by modern browsers, however if we have used a different  date format, the chart won’t work. It won’t work on IE8 and older too.

As our chart is already created, and even chartData variable set as data provider of a chart, all we need to do after data is parsed, is to call:

chart.validateData();

Now, open your html in browser and you should see this:

 2tut2

And here is a working example of all what we’ve done here.

分享到:
评论

相关推荐

    Chart 极品web报表控件收集(Flot,AmCharts, Emprise JavaScript Charts...)

    • Emprise JavaScript Charts - Emprise 是一个100% 纯 JavaScript 图表解决方案,并不需要任何 JavaScript 框架. • PlotKit - PlotKit 是一个 图表和图像的Javascript 库. PlotKit 和 MochiKit javascript 库...

    LiveCharts_Demo.7z

    《LiveCharts曲线截屏保存功能详解》 在WPF应用开发中,数据可视化是一个至关重要的环节,它能够帮助用户直观地理解复杂的数据信息。LiveCharts是一款强大的数据可视化库,尤其适用于创建动态、交互式的图表。在...

    TMS.Advanced.Charts.v.3.8.1.2.D6-XE7.XE10_2.Source.rar

    标题 "TMS.Advanced.Charts.v.3.8.1.2.D6-XE7.XE10_2.Source.rar" 提供的信息是关于一个名为 TMS Advanced Charts 的组件库,其版本为 3.8.1.2。这个组件库专为 Delphi 开发者设计,提供对 Delphi 6 到 XE10_2 的...

    基于LiveCharts.Wpf.Core(0.9.8)的几个图形报表实例(柱状图,曲线图,分组柱状图,饼状图)

    在本文中,我们将深入探讨如何使用LiveCharts.Wpf.Core库(版本0.9.8)在C# WPF环境中创建各种图形报表,包括柱状图、曲线图、分组柱状图以及饼状图。这些图表是数据可视化的重要工具,能够帮助用户直观地理解和解析...

    Axhub Charts Pro V2.1.1.rplib

    Axhub Charts Pro V2.1.1.rplib Axhub Charts Pro V2.1.1.rplib Axhub Charts Pro V2.1.1.rplib Axhub Charts Pro V2.1.1.rplib Axhub Charts Pro V2.1.1.rplib Axhub Charts Pro V2.1.1.rplib Axhub Charts Pro V...

    TMS Advanced IntraWeb Charts 2015.3.8.1.2 Full Source XE7-DX10

    TMS Advanced IntraWeb Charts 利用了 IntraWeb 的优势,将图形渲染和交互功能直接集成到 Web 应用中,无需复杂的 JavaScript 或其他前端技术。 三、源码分析 提供的源码包括了 Delphi XE7 至 DX10 不同版本的适配...

    Good.Charts.1633690709.epub

    A new generation of tools and massive amounts of available data make it easy for anyone to create visualizations that communicate ideas far more effectively than generic spreadsheet charts ever could...

    Arthas和LiveCharts的dll.zip

    LiveCharts.Wpf.dll是这个库的主要组件,提供了丰富的图表类型和自定义选项,使开发者能够轻松创建动态和交互式的图表,增强数据展示的效果。LiveCharts不仅支持静态数据,还可以实时更新数据,非常适合用于监控和...

    WPFVisifire.Charts.dll v5.1.7去水印版.rar

    1. 将`WPFVisifire.Charts.dll`文件添加到你的WPF项目引用中。 2. 在XAML中引用该控件库,如:`xmlns:v="clr-namespace:Visifire.Charts;assembly=WPFVisifire.Charts"` 3. 添加图表控件,例如:`&lt;v:Chart/&gt;` 4. ...

    PyPI 官网下载 | svg.charts-4.0.1.tar.gz

    《PyPI官网下载:深入解析svg.charts-4.0.1.tar.gz》 在Python的世界里,PyPI(Python Package Index)是开发者们的重要资源库,它为Python用户提供了一个集中下载各种开源库和模块的平台。今天我们将深入探讨一个...

    jscharts_mb.js

    现在ie浏览器安全性加高,实现预览滚能我用了好多列子,终于成功了

    axure_charts元件库.rar

    ECharts是一款开源的JavaScript数据可视化库,它在Web开发中广泛应用,因为其强大的功能和灵活的定制性。 首先,让我们深入了解一下ECharts。ECharts是由百度开发的,支持多种类型的图表,如柱状图、折线图、饼图、...

    PyPI 官网下载 | djangocms_charts-3.0.1.tar.gz

    《PyPI官网下载:探索djangocms_charts-3.0.1.tar.gz的奥秘》 在Python的世界里,PyPI(Python Package Index)是开发者们分享和获取Python库的重要平台。这次我们关注的是一款名为“djangocms_charts”的Python库...

    PyPI 官网下载 | eea.googlecharts-7.5.zip

    2. **导入库** - 在你的Python脚本中,你需要导入eea.googlecharts模块: ```python from eea.googlecharts import GoogleCharts ``` 3. **创建图表** - 使用GoogleCharts类实例化一个对象,并设置所需的参数,...

    Live-Charts-master.zip

    LiveCharts是一款专为C#开发者设计的开源图表库,它为.NET框架提供了强大的图表功能,尤其在WPF(Windows Presentation Foundation)应用中表现卓越。这个库的目的是简化数据可视化的过程,让开发者能够快速、轻松地...

Global site tag (gtag.js) - Google Analytics