Highcharts 中文文檔翻譯

 

如何使用

內容表

  1. 安裝
  2. How to set up the options如何設置選項
  3. Understanding axes理解軸
  4. Preprocessing the options預處理選項
  5. Live charts在線圖表
  6. Exporting module導入模塊
  7. Freeform drawing多邊形繪圖

 

 

 

如何使用(How To Use)

內容表(Table of contents)

  1. 安裝 Installatio n 
  2. 如何設置選項How to set up the options
  3. 理解軸Understanding axes
  4. 預處理選項Preprocessing the options
  5. 在線圖表Live charts
  6. 導出模塊Exporting module
  7. 多邊形繪圖Freeform drawing

1. 安裝Installation

  1. Highcharts uses either jQuery, MooTools or Prototype for some common JavaScript tasks. You need to include the JavaScript files in the section of your web page *). If you already have jQuery included, you can skip the first one. Use this code to include Highcharts with jQuery:(Highcharts使用jQuery, MooTolsg還有Prototype用於執行一些公共的Javascript任務。你要在你的Web頁面的區域包含這些Javascript文件。如果你的頁面中已經包含了jQuery,那你可以略過這第一節。使用以下的代碼去導入jQuery,還有Highcharts(注:這裏翻譯可能有誤,從字面意義上說,應是,“使用以下代碼會用jQuery導入Highcharts。”,但顯然不應該是這樣子。))
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
    <script src="/js/highcharts.js" type="text/javascript"></script>
    
    While the jQuery adapter is built into Highcharts and Highstock, the MooTools adapter and the Prototype adapter has to be included separately. Use this code to include Highcharts with MooTools:(因爲jQuery適配器是內建於Hightcharts和Highstock,MooTools適配器和Prototype適配器要分開導入。使用以下的代碼導入MooTools適配器。)
    <script src="https://ajax.googleapis.com/ajax/libs/mootools/1.4.2/mootools-yui-compressed.js" type="text/javascript"></script>
    <script src="/js/adapters/mootools-adapter.js" type="text/javascript"></script>
    <script src="/js/highcharts.js" type="text/javascript"></script>
    
    and use this code to include Highcharts with Prototype:(使用以下的代碼去導入prototype適配器。)
    <script src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js" type="text/javascript"></script>
    <script src="/js/adapters/prototype-adapter.js" type="text/javascript"></script>
    <script src="/js/highcharts.js" type="text/javascript"></script>
    
    If you're installing Highstock, the procedure is the same as above, except the JavaScript file name is highstock.js rather than highcharts.js. *) Highcharts version 1.x relied on excanvas.js for rendering in IE. From Highcharts 2.0 (and all Highstock versions) IE VML rendering is build into the library.(安裝Highstorck的時候,步驟和上面的一致,除了Javascript文件的名字是highcharts.js而不是highcharts.js.*。也就是說要用具體版本的hightcharts.js.*替換highcharts.js)
  2. In a script tag in the head of your web page, or in a separate .js file, add the JavaScript code to initialize the chart. Note that the id of the div where you want to put the chart (see #3) is given in the renderTo option below:(在頁面的head標籤裏的script標籤中,或者在一個單獨的.js文件裏,添加以下代碼去初始化圖表。需要注意的時,你想放置圖表所在div的id會被設置在下面代碼中的renderTo 項:)
    var chart1; // globally available
    $(document).ready(function() {
          chart1 = new Highcharts.Chart({
             chart: {
                renderTo: 'container',
                type: 'bar'
             },
             title: {
                text: 'Fruit Consumption'
             },
             xAxis: {
                categories: ['Apples', 'Bananas', 'Oranges']
             },
             yAxis: {
                title: {
                   text: 'Fruit eaten'
                }
             },
             series: [{
                name: 'Jane',
                data: [1, 0, 4]
             }, {
                name: 'John',
                data: [5, 7, 3]
             }]
          });
       });
    The code above uses the jQuery specific way of launching code on document ready, as explained at the jQuery website. If you use MooTools, instead of the$(document).ready() syntax you do it slightly differently:(上面的代碼使用jQuery自己的加載方法,這是在文檔加載完成後執行,可以看jQuery website裏的解釋。如果你使用MooTools,會略有不同,就要用以下的代碼去替換 $(document).ready()  這樣的語法。)
    <script type="text/javascript">
       window.addEvent('domready', function() {
          var chart1 = .......
    If you're inserting a Stock chart, there is a separate constructor method called Highcharts.StockChart. In these chart, typically the data is supplied in a separate JavaScript array, either taken from a separate JavaScript file or by an Ajax call to the server.(如果你正在安裝一個柱狀圖表,有一個單獨的構造方法 Highcharts.StockChart。 通常在這裏圖表裏,數據會是由一個單獨的Javascript數組提供,也可以是一個單獨的Javascript文件,或者用Ajax調用服務器裏的數據。
    var chart1; // globally available
    $(document).ready(function() {
          chart1 = new Highcharts.StockChart({
             chart: {
                renderTo: 'container'
             },
             rangeSelector: {
                selected: 1
             },
             series: [{
                name: 'USD to EUR',
                data: usdtoeur // predefined JavaScript array
             }]
          });
       });
  3. Add a div in your webpage. Give it an id refering to the renderTo option in #2, and set a specific width and height which will be the width and height of your chart.(添加一個div到你的頁面中。給它設置一個id,要和#2裏的renderTo選項對應。並且指定寬度和高度,這是圖表的寬高。 )
    <div id="container" style="width: 100%; height: 400px"></div>
  4. Optionally, you can apply a global theme to your charts. A theme is just a set of options that are applies globally through the Highcharts.setOptions method. The download package comes with four predefined themes. To apply a theme from one of these files, add this directly after the highcharts.js file inclusion:(另外,你可以給你的圖表應用一個全局主題。一個主題就是一個選項值的集合,該選項值通過調用Highcharts.setOptions方法後會被全局應用。下載下面的包中有四個預置的主題,要應用其中的一個,在導入highcharts.js文件的後面直接添加上。)
    <script type="text/javascript" src="/js/themes/gray.js"></script>

2. 如何設置選項How to set up the options

Highcharts uses a JavaScript object structure to define the options. The options are nested into categories. The options are mainly strings and numbers, but some are arrays, other objects or even functions. When you initialize the chart using new Highcharts.Chart, the options object is the first parameter you pass.(Highcharts使用一個Javascript對象結構去定義這些選項。選項被內嵌入分類。選項主要是字符串和數值,但有些是數組、其它對象甚至是方法。當你使用new Highcharts.Chart去初始化圖表時,該選項對象是你第一個要傳的參數。)

If you want to apply a set of options to all charts on the same page, use Highcharts.setOptions like shown below.(如果你想要去應用一個選項集合到同一個頁面中的所有圖表,就像下面那樣子使用Highcharts.setOptions。)

See #3 above for an example of an options object. For more examples see the Highcharts demo gallery or the Highstock demo gallery. For a full reference of the options available, see the Highcharts options reference and the Highstock options reference.(看上面的#3的一個選項對象例子,更多的例子就看。。。。。。)

3. 理解軸的概念Understanding axes

Many of the examples in the Highcharts demo come with an xAxis with categories. However, it is important to understand when to use categories and when you are better off with a linear or datetime xAxis.(在Highcharts demo裏的很多例子是和x軸和分類相關的。但是去理解什麼時候去使用分類和什麼時候去更好地使用線性或者一個時間x軸是很重要的。)

Categories are groups of items, like for example "Apples", "Pears" and "Oranges", or "Red", "Green", "Blue", "Yellow". These categories have that in common that there are no intermediate values (there's no sliding transition between apples and pears). Also, if you leave one category out, the user isn't able to understand what is left out. Say if you print every second color of "Red", "Green", "Blue" or "Yellow", the user won't know what colors are missing. Therefore, Highchars doesn't have automatic methods to hide categories if they become to dense on the axis. If you have problems with overlapping axis labels, try either the xAxis.labels.staggerLines option, or give the labels a rotation. If you find that you can skip category labels by the xAxis.labels.step option, chances are that you are better off using a linear or datetime axis.(分類就是一個項目的組合,像“Apples”,"Pears"和“Oranges”, 或者就是“Red”, "Green", "Blue", "Yellow"。這些分類有這樣的共同點,它們都沒有模棱兩可的值,即在apples和pears裏沒有中間值。同樣的,如果你)

An xAxis of the linear or datetime type has the advantage that Highcharts is able to determine how close the data labels should be because it knows how to interpolate. The labels will by default be placed with approximately 100px between them, which can be changed in the tickPixelInterval option. If you have predictable categories like "Item1", "Item2", "Item3" or "2012-01-01", "2012-01-02", "2012-01-03" etc., linear or datetime axis types combined with anxAxis.labels.formatter would probably be a better choice.(一個座標或者日期時間類型的X軸有如下優勢,Highcharts可以確定數據標籤如何關閉,因爲它知道如何插入數據。該標籤會默認地相隔大約100像素左右放置,並且可以根據tickPixelInterval 選項改變。如果你已經你已經大概確定分類會像是"Item1","Item2","Item3"或者" 2012-01-01", "2012-01-02", "2012-01-03" 等,那麼座標軸或者時間軸可以和xAxis.labels.formatter相結合,這會是一個更好的選擇。)

4. 預處理選項Preprocessing the options

To get the most out of Highcharts, it is important to understand how the configuration object works and how it can be altered programmatically. These are some key concepts on JavaScript objects:(爲了更好地使用Highcharts,理解配置對象是如何作用,和它可以如何改寫是很重要的。這裏有一些關於JavaScript對象的關鍵概念。)

  • The Highcharts options in the examples are defined as object literals. By notating the configuration this way, we can have a clean, human readable and low space consuming config object. This complicated code is perhaps more familiar to developers with a background from C-type languages:(示例中的Highcharts選項被定義爲對象常量。通過這種配置方式,可以擁有一個簡潔,可讀性強和低空間消耗的配置對象。這種代碼風格可能更被有類C語言開發背景的人熟識。)
    // Bad code:
    var options = new Object();
    
    options.chart = new Object();
    options.chart.renderTo = 'container';
    options.chart.type = 'bar';
    
    options.series = new Array();
    options.series[0] = new Object();
    options.series[0].name = 'Jane';
    options.series[0].data = new Array(1, 0, 4);
    As JavaScript object literals, we would write it like below. Note that the two options objects will produce exactly the same result.(做爲JavaScript對象常量,我們可以像下面那樣寫。要注意的是,兩個選項是的效果是一樣的。)
    // Good code:
    var options = {
        chart: {
            renderTo: 'container',
            defaultSeriesType: 'bar'
        },
        series: [{
            name: 'Jane',
            data: [1, 0, 4]
        }]
    };
  • After an object is created using the object literal notation, we can extend its members by the dot notation. Say we have an object like defined in the "Good code" above. The code below adds another series to it. Remember options.series is an array, so it has a push method.(用一個對象常量符號創建一個對象之後,我們可以通過點號拓展它的成員。也就是說,我們可以擁有一個像上面定義的代碼一樣。下面的代碼給對象添加了另一個的series。)
    options.series.push({
        name: 'John',
        data: [3, 4, 2]
    })
  • Another fact that can come in handy when working on JavaScript objects, is that the dot notation and square bracket notation are equivalent, so you can access all members by their string names. Which in practice means that(另一個關於Javascript對象的操作方式是,點號和方括號是相當的,所以你可以通過他們的字符串名字訪問到它們。就像如下代碼)
    options.renderTo
    is always the same as(和這個是一樣的)
    options['renderTo']

4.1 學習例子:預處理CSV數據Case study: preprocessing the data from CSV

This example shows how to set up the basic chart options first, then do an Ajax call for the data, parse the data and add them in the proper format to the options. In this example, jQuery is used for handling Ajax, but you could just as well use MooTools' or Prototype's similar functions. All of the code runs in the$(document).ready event handler. The example can be seen live at data-from-csv.htm.(該示例會先展示如何設置基本的圖表選項,然後會調用一個Ajax方法去獲取數據,並以對應的格式添加到該選項集合中。在該示例中jQuery用於處理Ajax,你也可以使用MooTools或者Prototype的相似函數。所有的這些代碼都運行在$(document).ready這一事件柄中。該示例可以在線查看。

  1. Create an external CSV file containing only the data. In this example, the file looks like below. The first line lists the categories with a dummy name in the first position. The subsequent lines list the data series name in the first position and values in the subsequent positions. In real life, you will often create the contents of this file using PHP or other server side programming languages. Or you may choose to use other markup formats like XML or JSON. In those cases, jQuery can also parse the data for you natively.(創建一個單獨包含數據的外部CSV文件。在這個示例中,這個文件會是如下的樣子。第一行列出分類,並且第一個位置是一個虛擬的名字。接下來的行,則是系列數據,同樣是名字在第一個位置,隨後是數據。在實際中,你經常用PHP或者其它的服務端編程語言來生成該文件內容。或者你可以選擇使用XML或者JSON這樣的標記格式)
    Categories,Apples,Pears,Oranges,Bananas
    John,8,4,6,5
    Jane,3,4,2,3
    Joe,86,76,79,77
    Janet,3,16,13,15
    
  2. Define the initial, basic options. Note that we create empty arrays for the categories and series objects, so that we can just push values to them later.(定義初始基本的選項。我們可以創建空的數組和系列對象,這樣我們可以在以後插入數據。)
    var options = {
        chart: {
            renderTo: 'container',
            defaultSeriesType: 'column'
        },
        title: {
            text: 'Fruit Consumption'
        },
        xAxis: {
            categories: []
        },
        yAxis: {
            title: {
                text: 'Units'
            }
        },
        series: []
    };
  3. Put it all together. We use the jQuery.get method to get the contents of the data.csv file. In the success callback function, we parse the returned string, add the results to the categories and series members of the options object, and create the chart. Note that we can't create the chart outside the Ajax callback, as we have to wait for the data to be returned from the server.(把它們合在一起。我們使用jQuery的.get方法去獲取data.cvs文件的內容。在success回調函數裏,我們解析返回的字符流,把結果添加到分類和選項對象的成員中,然後創建圖表。要特別注意的是,我們不能在Ajax的回調方法外創建圖表,因爲我們要等待從服務器返回的數據。)
    $.get('data.csv', function(data) {
        // Split the lines
        var lines = data.split('\n');
        
        // Iterate over the lines and add categories or series
        $.each(lines, function(lineNo, line) {
            var items = line.split(',');
            
            // header line containes categories
            if (lineNo == 0) {
                $.each(items, function(itemNo, item) {
                    if (itemNo > 0) options.xAxis.categories.push(item);
                });
            }
            
            // the rest of the lines contain data with their name in the first position
            else {
                var series = {
                    data: []
                };
                $.each(items, function(itemNo, item) {
                    if (itemNo == 0) {
                        series.name = item;
                    } else {
                        series.data.push(parseFloat(item));
                    }
                });
                
                options.series.push(series);
        
            }
            
        });
        
        // Create the chart
        var chart = new Highcharts.Chart(options);
    });

4.2 從XML中加載Loading from XML

Loading data from an XML file is similar to the CSV approach. Highcharts does not come with a predefined XML data syntax, it is entirely up to you to write the XML and to define a parsing function for it. The downside of using XML over CSV is that it adds some markup to the data, leaving a larger footprint. How large the extra footprint is depends on how you mark up your data. For example, if you wrap each point with a <point> tag and load 1000 points, it will add some weight. If however you add a comma separated list of point values, it doesn't. The upside to using XML, at least for small data sets, is that you don't have to manually parse the incoming data. You can utilize jQuery's existing DOM parsing abilities to access the XML tree. We set up a live example for this at data-from-xml.htm. The data can be viewed at data.xml.(從XML文件中加載數據和從CSV相似。Highcharts不會與一個預先定義好的XML數據語法捆綁,它完全取決於你寫的XML和定義的解析函數。使用XML的缺點就是會添加一些標記到數據中,這導致一個更大的腳本,這是CVS不會有的。額外的數據有多大取決於你如何搭建你的數據。打個比方,如果你用<point>標籤去包裝每個點,並且加載了1000個點,它會添加不少的工作量。但是如果你添加一個逗號去分隔點的數據,它就簡單多了。說話回來,使用XML文件,至少對於少量的數據集合來說,你也是不需要手動去解析傳來的數據。你可以利用jQuery中現有的DOM解析能力,從而訪問XML樹。我們有一個在線的示例。)

5. 在線圖表Live charts

After a chart has been defined by the configuration object, optionally preprocessed and finally initialized and rendered using new Highcharts.Chart(), we have the opportunity to alter the chart using a toolbox of API methods. The chart, axis, series and point objects have a range of methods like updateremove,addSeriesaddPoints and so on. The complete list can be seen in the API Reference under "Methods and Properties" at the left.(用一個配置對象定義一個圖表,選擇性地預處理,並被初始化然後用new Highcharts.Chart()顯示之後,我們就可以使用很多的API方法去改變圖表。這些圖表,軸,系列和點對象都有若干的方法,像update,remove,addSeries,addPoints等等。完整的API列表可以查看左側的"方法和屬性"。)

5.1 學習案例:一個和服務的時時連接Case study: a live connection to the server

The following example shows how to run a live chart with data retrieved from the server each second, or more precisely, one second after the server's last reply. It is done by setting up a custom function, requestData, that initially is called from the chart's load event, and subsequently from its own Ajax success callback function. You can see the results live at live-server.htm.(接下來的示例會說明如何運行一個動態圖表,該圖表每隔一秒從服務器檢索數據。或者更確切地說,從服務器最近一次應答的下一秒。可以這樣子完成,設置一個自定義的函數,requestData,它最初會在圖表的load事件中被調用,並且在隨後它自己的Ajax success回調函數中調用。你可以在線看到結果live-server.htm。)

  1. Set up the server. In this case, we have a simple PHP script returning a JavaScript array with the JavaScript time and a random y value. This is the contents of the live-server-data.php file:(設置服務器。在這個示例中,我們有一個簡單的PHP腳本返回一個Javascript數姐,包含一個Javascript時間和一個隨機的值。這是這個live-server-data.php文件的內容:)
    <?php
    // Set the JSON header
    header("Content-type: text/json");
    
    // The x value is the current JavaScript time, which is the Unix time multiplied by 1000.
    $x = time() * 1000;
    // The y value is a random number
    $y = rand(0, 100);
    
    // Create a PHP array and echo it as JSON
    $ret = array($x, $y);
    echo json_encode($ret);
    ?>
  2. Define the chart variable globally, as we want to access it both from the document ready function and our requestData funcion. If the chart variable is defined inside the document ready callback function, it will not be available in the global scope later.(定義全局的圖表變量,因爲我們會在文檔加載完畢函數和requestData函數裏訪問它。如果該圖表變量被定義在document ready的回調函數裏,那它在接下來的全局範圍內無效。)
    var chart; // global
  3. Set up the requestData function. In this case it uses jQuery's $.ajax method to handle the Ajax stuff, but it could just as well use any other Ajax framework. When the data is successfully received from the server, the string is eval'd and added to the chart's first series using the Highcharts addPoint method. If the series length is greater than 20, we shift off the first point so that the series will move to the left rather than just cram the points tighter.
    /**
     * Request data from the server, add it to the graph and set a timeout to request again
     */
    function requestData() {
        $.ajax({
            url: 'live-server-data.php',
            success: function(point) {
                var series = chart.series[0],
                    shift = series.data.length > 20; // shift if the series is longer than 20
    
                // add the point
                chart.series[0].addPoint(point, true, shift);
                
                // call it again after one second
                setTimeout(requestData, 1000);    
            },
            cache: false
        });
    }
  4. Create the chart. Notice how our requestData function is initially called from the chart's load event. The initial data is an empty array.
    $(document).ready(function() {
        chart = new Highcharts.Chart({
            chart: {
                renderTo: 'container',
                defaultSeriesType: 'spline',
                events: {
                    load: requestData
                }
            },
            title: {
                text: 'Live random data'
            },
            xAxis: {
                type: 'datetime',
                tickPixelInterval: 150,
                maxZoom: 20 * 1000
            },
            yAxis: {
                minPadding: 0.2,
                maxPadding: 0.2,
                title: {
                    text: 'Value',
                    margin: 80
                }
            },
            series: [{
                name: 'Random data',
                data: []
            }]
        });        
    });

6. Exporting module

From version 2.0 an exporting module is available for Highcharts, which allows users to download images or PDF's of your charts. This module consists of an extra JavaScript file, exporting.js, and a web service or server module written in PHP. Highslide Software offers the exporting web service free of charge. If you include the exporting module in your charts, two buttons will appear in the upper right. One button prints the chart, which is done on the client side only. The other button handles exporting. By default, an SVG representation of the chart is sent by POST to http://export.highcharts.com, where it is converted using Apache's Batik converter to PDF, PNG or JPEG.

See the navigation and exporting reference items for a full documentation for the options available. Also see under "Methods and Properties" in the reference for members releated to exporting.

6.1 Client side setup

Add the exporting module JavaScript file after your highcharts.js file.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script src="/js/highcharts.js" type="text/javascript"></script>
<script src="/js/modules/exporting.js" type="text/javascript"></script>

6.2 Server module setup

If you want to set up this web service on your own server, the index.php file that handles the POST is supplied in the download package inside the/exporting-server directory.

  1. Make sure that PHP and Java is installed on your server.
  2. Upload the index.php file from the /exporting-server directory in the download package to your server.
  3. In your FTP program, create directory called temp in the same directory as index.php and chmod this new directory to 777 (Linux/Unix servers only).
  4. Download Batik from http://xmlgraphics.apache.org/batik/#download. Find the binary distribution for your version of jre
  5. Upload batik-rasterizer.jar and the entire lib directory to a location on your web server.
  6. In the options in the top of the index.php file, set the path to batik-rasterier.jar.
  7. In your chart options, set the exporting.url option to match your PHP file location.

As an ASP.NET alternative to our Java/PHP based server module, Clément Agarini has kindly shared his export module for ASP.NET.

7.0 Freeform drawing

Internally, Highcharts is equipped with a rendering module that acts as a wrapper for JavaScript access to SVG in modern browsers and VML in IE < 9. It has much in common with drawing tools like Raphaël or SVG jQuery. This drawing module can be used either to draw shapes or text on the chart, or even as a standalone drawing tool for HTML pages.

Inside a chart, the chart's renderer object is available as chart.renderer. To instanciate a new SVG drawing outside Highcharts, you call new Highcharts.Renderer(parentNode, width, height), where parentNode is the div or container element where you want the drawing to be placed.

The drawing API is documented in detail at /ref#renderer and /ref#element.

7. API reference

Proceed to the API Reference.

發佈了59 篇原創文章 · 獲贊 0 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章