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.

你可能感兴趣的:(Highcharts)