ChartDirector Ver 4.1 (ColdFusion Edition)

ChartDirector
Version 4.1

ColdFusion Edition
Programmer's Manual

By Advanced Software Engineering Limited
© 2006 Advanced Software Engineering Limited. All rights reserved.
[ASE doc code: cddoc CF 4101]


License Agreement

License Agreement

You should carefully read the following terms and conditions before using the ChartDirector software. Your use of the ChartDirector software indicates your acceptance of this license agreement. Do not use the ChartDirector software if you do not agree with this license agreement.

Disclaimer of Warranty

The ChartDirector software and the accompanying files are distributed and licensed "as is". Advanced Software Engineering Limited disclaims all warranties, either express or implied, including, but not limited to implied warranties of merchantability and fitness for a particular purpose. Should the ChartDirector software prove defective, the licensee assumes the risk of paying the entire cost of all necessary servicing, repair, or correction and any incidental or consequential damages. In no event will Advanced Software Engineering Limited be liable for any damages whatsoever (including without limitation damages for loss of business profits, business interruption, loss of business information and the like) arising out of the use or the inability to use the ChartDirector software even if Advanced Software Engineering Limited has been advised of the possibility of such damages.

Intellectual Property

The ChartDirector software is protected by copyright laws and international copyright treaties, as well as other intellectual property laws and treaties. The ChartDirector software is licensed, not sold. Title to the ChartDirector software shall at all times remain with Advanced Software Engineering Limited.

You agree not to modify, decompile, reverse engineer, disassemble or otherwise attempt to derive source code from the ChartDirector software.

Trial Version

The trial version of the ChartDirector software will produce yellow banner messages at the bottom of the chart images generated by it. You agree to not remove, obscure, or alter this message.

Subjected to the conditions in this license agreement:

  • You may use the unmodified trial version of the ChartDirector software without charge.

  • You may redistribute the unmodified trial version of the ChartDirector software, provided you do not charge for it.

  • You may embed the unmodified trial version of the ChartDirector software (or part of it), in a product and distribute the product, provided you do not charge for the product.
If you do not want the yellow banner messages appearing in the charts, or you want to embed the ChartDirector software (or part of it) in a product that is not free, you must purchase a commercial license to use the ChartDirector software from Advanced Software Engineering Limited. Please refer to Advanced Software Engineering's web site at www.advsofteng.com for details.

© 2006 Advanced Software Engineering Limited. All rights reserved.


Introduction

Introduction

Formats Available for This Documentation

This documentation is available in both CHM and HTML formats. CHM is the recommended format on Windows because of the built-in search facilities and better indexing support in CHM viewers, while HTML format can be read on any operating system. Both formats may be downloaded from http://www.advsofteng.com/download.html.

Due to a security update in Microsoft Windows, CHM files may only be opened in local hard disk. CHM files in network drives may not work properly. Please ensure the CHM file is stored in your local hard disk for reading.

Also, in some systems, you may need to "unblock" the CHM after downloading from a web site to read it. The steps are:

  • Right-click the CHM file, and then click Properties.
  • Click Unblock.

Welcome to ChartDirector

ChartDirector is a powerful chart component for creating professional looking charts for web and windows applications. Key features include:

  • Fast and Efficient : ChartDirector is specially designed to handle the demanding requirements of server side usage. It multi-threaded design handles multiple concurrent requests quickly and efficiently.

  • Flexibility : ChartDirector's object oriented API allows you to control and customize chart details, providing you with tremendously flexibility to design the charts you want.

    ChartDirector even includes a general purpose graphics API, so you can add annotations, custom text, shapes and images to decorating your charts the chart in custom ways. It is possible to use ChartDirector as a general-purpose graphics library.

  • Comprehensive Chart Styles : Include pie, donut, bar, line, spline, step-line, trending, curve-fitting, inter-line coloring, area, scatter, bubble, floating box, box-whisker, waterfall, finance, gantt, vector, radar, polar line, polar area, polar spline, polar scatter, polar bubble,polar vector, rose.

    In additional, all chart styles support XY axis swapping. For example, bar charts can be horizontal or vertical, and the same applies to line charts, area charts, etc. Many chart styles also support 3D effects.

  • Meters and Gauges : Include angular meters of arbitrary angular span, and linear meters in horizontal and vertical orientations.

  • Complex Finance Charts : Special support for composing sophisticated financial charts - candlestick, OHLC, volume bars, moving averages, price bands, RSI, MACD, Stochastic, Momentum, ROC, OBV, and numerous other technical indicators.

  • Layer Architecture : Enables new chart styles to be composed easily using chart layers as building blocks. For example, a line chart with error symbols can be composed easily using a line layer and a box-whisker layer. With alpha transparency support, bottom layers remain visible even if hidden by top layers.

  • CDML : The innovative ChartDirector Mark Up Language (CDML) technology allows rich formatting of text with embedding icons and images. CDML is supported in all ChartDirector text positions, including chart titles, legend keys, axis labels, data labels, etc.

  • Advanced Color System : ChartDirector's extended coloring system supports not only solid RGB colors, but also semi-transparent ARGB colors, gradient colors, patterns colors (wallpapers), and colors that change at user-defined positions to represent zones and thresholds. All ChartDirector objects can be filled using these colors.

  • Interactive : ChartDirector generates customizable image maps for chart objects, so chart objects may have "tool tip" help message, become clickable (useful for "drill-down") and support various mouse events. ChartDirector also provides a framework to support scalable and extensible drag to select/zoom/scroll features.

  • AJAX Chart Updates Charts can be updated without the web pages refreshing at all.

  • Browser Friendly : ChartDirector produces charts as PNG, JPEG, and GIF, which are viewable in virtually all browsers, including those in mobile phones and electronic organizers. Charts can be imported to email or word documents. Drag to select/zoom/scroll and AJAX features are implemented using Javascript. No Applets or ActiveX controls required.

  • Bandwidth Efficient : Optimized color reduction algorithm for creating palette based charts that looks as good as true color charts, but with much smaller file size. Ensures fast Internet download.

  • Easy to use : Producing charts requires just a few lines of code. ChartDirector comes with comprehensive documentation and numerous sample programs that can be used as program templates.

  • Internationalization : Unicode characters support. Configurable number and date/time formats.

Programming Languages

ChartDirector is available in the following programming languages and component technologies.

  • ASP / COM / Visual Basic / VBScript / JScript
  • .NET (C#, VB.NET, Managed C++, JScript.NET, J#)
  • ColdFusion
  • Java
  • PHP
  • Perl
  • Python
  • Ruby
  • ColdFusion
  • C++

Supported Platforms

ChartDirector for Java and ColdFusion are in pure Java and is platform independent. ChartDirector for ASP/COM/VB and .NET are supported on Windows 2000/2003/Vista/NT/XP/ME/98. ChartDirector for PHP, Perl, Python, Ruby and C++ are supported on Windows 2000/2003/Vista/NT/XP/ME/98, Linux (x86/x86_64), FreeBSD (x86), Mac OS X (PowerPC/Intel) and Solaris (Sparc).


Installation

Installation

ColdFusion Version Compatibility

ChartDirector for ColdFusion is implemented as a Java class library, and requires ColdFusion MX (Ver 6.0) or above. For earlier versions of ColdFusion, it is recommended you use ChartDirector for ASP/COM/VB and access ChartDirector through COM.

Installing ChartDirector for ColdFusion

ChartDirector for ColdFusion is distributed as a zip file. The distribution contains the ChartDirector for ColdFusion library, comprehensive documentation, and numerous CFM sample scripts.

To install ChartDirector for ColdFusion:

  • Extract the files from the ChartDirector distribution to any directory.

  • Set up the ColdFusion class path to include the ChartDirector for ColdFusion library, at "ChartDirector/lib/ChartDirectorCF.jar".

    For ColdFusion MX 6 or 7 (the latest version as of the writing of this documentation), the method is to open the ColdFusion Administrator, select "Java and JVM" on the left side, and enter "[install_path]/ChartDirector/lib/ChartDirectorCF.jar" in the ColdFusion class path field ([install_path] is the directory which you extract ChartDirector to).

  • Restart the ColdFusion server for the modified ColdFusion class path to take effect.

Below is screen shot setting the ColdFusion class path using the ColdFusion Administrator provided for for your reference.

Running ChartDirector Sample Programs

ChartDirector for ColdFusion comes with numerous CFM sample scripts in "ChartDirector/cfdemo". They are excellent examples and tutorials on how to use ChartDirector.

To run the ChartDirector CFM sample scripts, simply copy the entire "cfdemo" subdirectory to the ColdFusion web directory, then access the index page using:

http://server_name/cfdemo/index.htm

Installing the ChartDirector License

If you have purchased a license to use ChartDirector, you should have a license code delivered to your via email and postal mail.

If your license key is for upgrading from a previous version of ChartDirector, you need to append the upgrade license key to the previous version license key, and use the combined license key.

There are two alternative methods to install the license key.

  • Create a one-line ASCII file using Notepad or other text editor, and put the license code in that line. The whole file should contain only the license code. Name that file "chartdir.lic" and put the file in the Java class path as visible to ColdFusion. A common location is the "WEB-INF/classes" of the web application that hosts the ColdFusion scripts (eg. "c:\CFusionMX7\wwwroot\WEB-INF\classes" for ColdFusion MX 7 on Windows hosted by the built-in JRun server.).

    If the license file appears to have no effect (does not disable the yellow banner line), and you are running on a web server environment, please make sure the web server "anonymous user" has read access to the "chartdir.lic" file. You may copy the file "ChartDirector/cfdemo/cdinfo.cfm" to your web server and access it using a browser. It will display a diagnostic page explaining why the license cannot be loaded.

    Make sure your license file is called "chartdir.lic". In particular, Notepad may automatically append ".txt" to the file name when creating a new file. So even if the file is saved as "chartdir.lic", it may end up as "chartdir.lic.txt". If this is the case, please rename the file back to "chartdir.lic".

  • An alternative method is to hard code the license key into the source code by using the ChartDirector.CFChart.setLicenseCode API. This method is recommended if your are redistributing ChartDirector, because your customer will then be unable to see the license key (unless your software is open source).

    cd = createObject("java", "ChartDirector.CFChart");
    cd.setLicenseCode(".....your-license-key.....");


Getting Started

Getting Started

This section introduces how to use ChartDirector in your development environment. It also demonstrates and explains concepts that are useful in understanding of subsequent sections.

In this section

The First Project
The "Hello World" project for using ChartDirector - creating a simple bar chart to explore using ChartDirector in your development environment.

ChartDirector Object Model Overview
A high level overview of ChartDirector's object model to facilitate understanding of subsequent sections.

What's Next
How to use this documentation to explore ChartDirector's rich features and use them in your own charts.


The First Project

The First Project

To get a feeling of using ChartDirector, and to verify the ChartDirector development environment is set up properly, we will begin by building a very simple bar chart.

If you have not yet tried the sample programs, it is highly recommended you try them now. Please refer to the Installation section for details. They are very useful for exploring and testing the features of ChartDirector.

[File: cfdemo/simplebar.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the bar chart
data = Array(85, 156, 179.5, 211, 123);

// The labels for the bar chart
labels = Array("Mon", "Tue", "Wed", "Thu", "Fri");

// Create a XYChart object of size 250 x 250 pixels
c = cd.XYChart(250, 250);

// Set the plotarea at (30, 20) and of size 200 x 200 pixels
c.setPlotArea(30, 20, 200, 200);

// Add a bar chart layer using the given data
c.addBarLayer(data);

// Set the labels on the x axis.
c.xAxis().setLabels(labels);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "", "title='{xLabel}: US${value}K'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Simple Bar Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>

The code is explained below:

  • cd = CreateObject("java", "ChartDirector.CFChart");

    The above code sets up the variable cd to represent the ChartDirector.CFChart class, which is the access point of the ChartDirector API.

  • c = cd.XYChart(250, 250);

    The first step in creating any chart in ChartDirector is to create the appropriate chart object. In this example, an XYChart object of size 250 x 250 pixels is created. In ChartDirector, XYChart represents any chart that has x-axis and y-axis, such as the bar chart we are drawing.

  • c.setPlotArea(30, 20, 200, 200);

    The second step in creating a bar chart is to specify where should we draw the bar chart. This is by specifying the rectangle that contains the bar chart. The rectangle is specified by using the (x, y) coordinates of its top-left corner, together with its width and height.

    For this simple bar chart, we will use the majority of the chart area to draw the bar chart. We will leave some margin to allow for the text labels on the axis. In the above code, the top-left corner is set to (30, 30), and both the width and height is set to 200 pixels. Since the entire chart is 250 x 250 in size, there will be 20 to 30 pixels margin for the text labels.

    Note that ChartDirector uses a pixel coordinate system that is customary for computer screen. The x pixel coordinate is increasing from left to right. The y pixel coordinate is increasing from top to bottom. The origin (0, 0) is at the top-left corner.

    For more complex charts which may contain titles, legend box and other things, we can use this method (and other methods) to design the exact layout of the entire chart.

  • c.addBarLayer(data);

    The above code adds a bar layer to the XYChart. In ChartDirector, any chart type that has x-axis and y-axis is represented as a layer in the XYChart. An XYChart can contain multiple layers. This allows "combination charts" to be created easily by combining different layers on the same chart (eg., a chart containing a line layer on top of a bar layer) .

    In the above line of code, the argument is an array of numbers representing the values of the data points.

    For simplicity, in this example, the array is filled with hard coded values. In real applications, you may fill the array with dynamic values. You may also create the array from a ColdFusion query column by using the toArray method, like:

    data = myQuery["columnName"].toArray();

  • c.xAxis().setLabels(labels);

    The above code sets the labels on the x-axis. The first method XYChart.xAxis retrieves the Axis object that represents the x-axis. The second method Axis.setLabels binds the text labels to the x-axis. The argument to the setLabels method is an array of text strings.

  • chart1URL = c.makeSession(GetPageContext(), "chart1");

    Up to this point, the chart is completed. The above code uses BaseChart.makeSession to output the chart image into a session variable called "chart1".

    We need to store the image in a session variable because we cannot deliver the image to the browser now. In HTML, we need to send an <IMG> tag to the browser first. The browser will then use the URL in the <IMG> to get the chart image from another HTTP connection.

    BaseChart.makeSession returns a URL query that can be used in the <IMG> tag to reference the image (see below).

    By default, BaseChart.makeSession outputs in PNG format, which is supported by all major browsers. You may also use other formats (such as GIF and JPG). Please refer to BaseChart.makeSession for details.

  • imageMap1 = c.getHTMLImageMap("", "", "title='{xLabel}: US${value}K'");

    After creating the chart image, an image map can be created for the chart to configure mouse interactions. In this example, the image map is configured to display tool tips of the format "title='{xLabel}: US${value}K'" when the mouse cursor is on top of the bars.

    Note that mouse interactions are optional. Your can always leave out the BaseChart.getHTMLImageMap code if mouse interactions are not required.

  • <img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>

    The <IMG> tag above instructs the browser to load the chart image. The URL of the chart image is getchart.cfm?#chart1URL#. The getchart.cfm is a standard CFM that comes with ChartDirector. It uses the query chart1URL returned by BaseChart.makeSession to retrieve the chart image from the session variable, and delivers it to the browser.

    The usemap attribute and the <MAP> tag above instruct the browser to apply the image map to the chart image for providing tool tips support.

Note: The trial version of ChartDirector will include small yellow banners at the bottom of the charts it produces. These banners will disappear in the licensed version of ChartDirector.


ChartDirector Object Model Overview

ChartDirector Object Model Overview

This section will give a very brief high level overview of the ChartDirector object model, which may be helpful for understanding of subsequent ChartDirector tutorials. The full details object model and API are documented in the ChartDirector Reference section.

The Top Level

At the top level, all ChartDirector charts (including meters) are derivatives of the BaseChart object. The following describes the top level class hierarchy.

  • BaseChart : Base class for all charts (including meters) in ChartDirector.

    • PieChart : Represents pie and donut charts

    • XYChart : Represents all charts that have x and y axes.

    • PolarChart : Represents all charts that uses polar coordinates.

    • BaseMeter : Base class for all meters in ChartDirector.

      • AngularMeter : Represents angular meters.

      • LinearMeter : Represents linear meters.

    • MultiChart : A container chart that can be used to combine multiple BaseChart objects together.

      • FinanceChart : Represents complex finance charts.

BaseChart

The BaseChart class represents features common to all ChartDirector charts, such as the chart background, legend box (LegendBox), titles and custom text boxes (TextBox). It also contains a DrawArea tool, which allows you to add arbitrary custom drawings to the chart.

PieChart

The PieChart class, as it name implies, represents pie charts, including donut charts. PieChart objects contain Sector objects, which represent the sectors in the pie charts.

XYChart

The XYChart class represents all chart types that have x and y axes. Each XYChart object contains a PlotArea object, representing the rectangular region where the chart is actually drawn. A XYChart also contains Axis objects, representing the x and y axes.

The actual chart types in a XYChart are implemented as layers. The available layers are listed below. A XYChart can contain many layers, so combination and custom chart types can easily be created.

Layer | Description
BarLayer | Represent all style of bar charts, such as simple bar charts, multi-bar charts, stacked bar charts, multi-stacked bar charts, percentage bar charts, depth bar charts.
LineLayer | Represent line charts.
SplineLayer | Represent spline line charts.
StepLineLayer | Represent step line charts.
TrendLayer | Represent trend line charts. A trend line the best fit straight line computed using the least square method.
InterLineLayer | A layer used for filling regions between two lines. The lines can come from LineLayer, SplineLayer, StepLineLayer, TrendLayer, or from Mark.
ScatterLayer | Represents scatter and bubble charts.
VectorLayer | Represents vector charts.
AreaLayer | Represent area charts.
HLOCLayer | Represent high-low-open-close charts.
CandleStickLayer | Represent candlestick charts.
BoxWhiskerLayer | Represent box-whisker charts.

The above layers are derived from the Layer class, which represents features common to all layers.

Each chart layer contains one or more DataSet objects. A DataSet object represents a data series. Several chart types require multiple data series, such as high-low-open-close, candlestick and box-whisker charts. Other chart types support combining the data series in various ways. For example, in a bar chart, multiple data series can be combined to form a stacked bar chart, percentage bar chart, multi-bar chart, multi-stacked bar chart, etc.

PolarChart

The PolarChart class represents polar and radar charts. Each PolarChart object contains a RadialAxis and an AngularAxis. The actual chart types in a PolarChart are implemented as layers. A PolarChart can contain many layers, so combination and custom chart types can easily be created.

The available layers are listed below.

Layer | Description
PolarLineLayer | Represent line charts, as well as scatter and bubble charts. (A scatter chart is a line chart with line set to Transparent. A bubble chart is a scatter chart in which the data symbols are of variable sizes.)
PolarAreaLayer | Represent area charts.
PolarSplineLineLayer | Represent spline line charts.
PolarSplineAreaLayer | Represent spline area charts.
PolarVectorLayer | Represent vector charts.

The above layers are derived from the PolarLayer class, which represents features common to all layers.

BaseMeter

The BaseMeter class is the base class for all meters. It represents features common to all meters. A BaseMeter object contains MeterPointer objects for representing meter pointers.

AngularMeter

The AngularMeter class represents angular meters, which are meters of which the meter pointers rotate to show the readings.

LinearMeter

The LinearMeter class represents horizontal and vertical linear meters, which are meters of which the meter pointers move linearly to show the readings.

MultiChart

A MultiChart object is a container for combining multiple BaseChart objects into a combined chart object.

FinanceChart

FinanceChart is a financial charting library built on top of the main ChartDirector library. It extends MultiChart by implementing many financial indicators, and allowing complex financial charts to be composed easily.


What's Next

What's Next

This documentation introduces ChartDirector features by using a sequence of examples. In the following sections, you will find plenty of examples for pie charts, xy charts, polar charts, etc. These examples are arranged from simple to sophisticated, and are designed to demonstrate various ChartDirector features step by step.

A complete, comprehensive reference to all ChartDirector features can be found in the section on ChartDirector Reference.

As a quick start, most people find it useful to just use the examples as code templates for their own charts. If you want to draw your own chart immediately, you may browse for the example that most closely matches you needs, and modify it to fit your needs.

Sometimes, the features you need may be illustrated in different examples. Provided you understand the code roughly so that you know which code fragment is for which feature, you may try to cut and paste code fragments from different examples together to compose your own chart. The ChartDirector Reference will be an invaluable aid as it explains the functions of every API in the examples.

To find the description of a method in the ChartDirector Reference, the easiest way is to use the Index section in the ChartDirector documentation.

In case you are reading the HTML format of the ChartDirector documentation, it may be useful to download the CHM format from http://www.advsofteng.com/download.html, as the CHM format has better support for index lookup and also supports searching.


Pie Charts

Pie Charts

In this section, we will discuss how to create pie charts using ChartDirector through a number of examples.

Title | Description
Simple Pie Chart | Demonstrates the basic steps in creating pie charts.
3D Pie Chart | Extends the Simple Pie Chart example by drawing the chart in 3D, adding a title, and exploding a sector.
Multi-Depth Pie Chart | Demonstrates a 3D pie chart where sectors have different 3D heights.
Side Label Layout | This method demonstrates the "side label layout" method for positioning the sector labels.
Pie with Small Sectors | Demonstrates how "side label layout" can avoid sector labels from overlapping. Also demonstrates metallic background colors, and sector labels with glass shading effect and rounded corners.
Circular Label Layout | Demonstrates various options in the "circular label layout" method. Also demonstrates the use of alternative sector label format.
Pie Chart with Legend | Demonstrates how to add a legend box to a pie chart. Also demonstrates the use of alternative sector label format.
Icon Pie Chart | Demonstrates using CDML and Parameter Substitution and Formatting to include icons in sector labels. Also demonstrates gradient background color, glass shading effect for the title and rounded corners for the chart frame.
Icon Pie Chart (2) | Extends the Icon Pie Chart example to demonstrate using CDML to include multiple fonts and colors in chart title, sector labels and to draw logo. Also demonstrates silver background color, rounded corners, and glass shading effect for title.
Multi-Pie Chart | Demonstrates drawing multiple pies with different data and colors. Also demonstrates putting labels on the sectors and using sector borders.
Donut Chart | Demonstrates a donut chart. Also demonstrates other chart effects, such as using CDML to nicely format sector labels, silver background color, rounded corners, and glass shading effect for title and sector labels.
Icon Donut Chart | Modifies the Icon Pie Chart example by using a semi-transparent donut instead of a pie, and using metallic background color.
Texture Donut Chart | Demonstrates wooden, rocky and marble texture effects by using pattern colors to load image patterns.
Concentric Donut Chart | Demonstrates creating concentric donut chart by merging two donuts of different radii.
Text Styles and Colors | Demonstrates various text styles, text colors, background colors and text box border effects.
Coloring and Wallpaper | Demonstrates different coloring schemes and background effects.
3D Angle | Demonstrates the effects of different 3D angles.
3D Depth | Demonstrates the effects of different 3D depths.
3D Shadow Mode | Demonstrates an alternative 3D drawing method that uses shadows.
Start Angle and Direction | Demonstrates different sector layout angles and directions.
Donut Width | Demonstrates the effects of different donut widths.


Simple Pie Chart

Simple Pie Chart

This example demonstrates the basic steps in creating pie charts.

  • Create a pie chart object using PieChart.PieChart.

  • Specify the center and radius of the pie using PieChart.setPieSize.

  • Specify the data used to draw the pie using PieChart.setData.

  • Generate the chart using BaseChart.makeSession.

  • Generate tool tips for the chart using BaseChart.getHTMLImageMap.

Source Code Listing

[File: cfdemo/simplepie.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the pie chart
data = Array(25, 18, 15, 12, 8, 30, 35);

// The labels for the pie chart
labels = Array("Labor", "Licenses", "Taxes", "Legal", "Insurance", "Facilities",
    "Production");

// Create a PieChart object of size 360 x 300 pixels
c = cd.PieChart(360, 300);

// Set the center of the pie at (180, 140) and the radius to 100 pixels
c.setPieSize(180, 140, 100);

// Set the pie data and the pie labels
c.setData(data, labels);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "", "title='{label}: US${value}K ({percent}%)'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Simple Pie Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


3D Pie Chart

3D Pie Chart

This example extends the Simple Pie Chart example by drawing the chart in 3D, adding a title, and exploding a sector.

  • Add a title to the chart using BaseChart.addTitle.

  • Draw the pie in 3D using PieChart.set3D.

  • Explode a sector using PieChart.setExplode.

Source Code Listing

[File: cfdemo/threedpie.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the pie chart
data = Array(25, 18, 15, 12, 8, 30, 35);

// The labels for the pie chart
labels = Array("Labor", "Licenses", "Taxes", "Legal", "Insurance", "Facilities",
    "Production");

// Create a PieChart object of size 360 x 300 pixels
c = cd.PieChart(360, 300);

// Set the center of the pie at (180, 140) and the radius to 100 pixels
c.setPieSize(180, 140, 100);

// Add a title to the pie chart
c.addTitle("Project Cost Breakdown");

// Draw the pie in 3D
c.set3D();

// Set the pie data and the pie labels
c.setData(data, labels);

// Explode the 1st sector (index = 0)
c.setExplode(0);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "", "title='{label}: US${value}K ({percent}%)'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    3D Pie Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Multi-Depth Pie Chart

Multi-Depth Pie Chart

This example demonstrates a 3D pie chart where sectors have different 3D heights.

Instead of using PieChart.set3D to set a single 3D depth for all sectors, in this example, PieChart.set3D2 is used to set different depths for the sectors with an array of integers.

Source Code Listing

[File: cfdemo/multidepthpie.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the pie chart
data = Array(72, 18, 15, 12);

// The labels for the pie chart
labels = Array("Labor", "Machinery", "Facilities", "Computers");

// The depths for the sectors
depths = Array(30, 20, 10, 10);

// Create a PieChart object of size 360 x 300 pixels, with a light blue (DDDDFF)
// background and a 1 pixel 3D border
c = cd.PieChart(360, 300, "0xddddff", -1, 1);

// Set the center of the pie at (180, 175) and the radius to 100 pixels
c.setPieSize(180, 175, 100);

// Add a title box using 15 pts Times Bold Italic font and blue (AAAAFF) as
// background color
c.addTitle("Project Cost Breakdown", "Times New Roman Bold Italic", 15
    ).setBackground("0xaaaaff");

// Set the pie data and the pie labels
c.setData(data, labels);

// Draw the pie in 3D with variable 3D depths
c.set3D2(depths);

// Set the start angle to 225 degrees may improve layout when the depths of the
// sector are sorted in descending order, because it ensures the tallest sector is at
// the back.
c.setStartAngle(225);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "", "title='{label}: US${value}K ({percent}%)'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Multi-Depth Pie Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Side Label Layout

Side Label Layout

This method demonstrates the "side label layout" method for positioning the sector labels.

With "side label layout", the sector labels are positioned on the left and right sides of the chart. In contrast, all previous examples use "circular label layout", in which the labels are positioned circularly around the pie.

"Circular label layout" typically uses less space and is the default layout method. However, if the pie chart contains a lot of small sectors, the labels may overlap with each others. It is because there may be insufficient space on the perimeter to position the labels.

"Side label layout" has the advantages that the labels will automatically shift up and down to avoid overlapping. By default, the labels are joined to the sectors with join lines.

The label layout method to use is specified with PieChart.setLabelLayout.

Source Code Listing

[File: cfdemo/sidelabelpie.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the pie chart
data = Array(25, 18, 15, 12, 8, 30, 35);

// The labels for the pie chart
labels = Array("Labor", "Licenses", "Taxes", "Legal", "Insurance", "Facilities",
    "Production");

// Create a PieChart object of size 500 x 230 pixels
c = cd.PieChart(500, 230);

// Set the center of the pie at (250, 120) and the radius to 100 pixels
c.setPieSize(250, 120, 100);

// Add a title box using 15 points Times Bold Italic as font
c.addTitle("Project Cost Breakdown", "Times New Roman Bold Italic", 15);

// Draw the pie in 3D
c.set3D();

// Use the side label layout method
c.setLabelLayout(cd.SideLayout);

// Set the pie data and the pie labels
c.setData(data, labels);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "", "title='{label}: US${value}K ({percent}%)'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Side Label Layout
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Pie with Small Sectors

Pie with Small Sectors

This example demonstrates how "side label layout" can avoid sector labels from overlapping. It also demonstrates metallic background colors, and sector labels with glass shading effect and rounded corners.

  • The golden background is achieved by using ChartDirector.CFChart.goldColor to create the golden color, then use PieChart.PieChart to set it as the chart background color.

  • Similarly, the pink metallic background for the chart title is achieved by using ChartDirector.CFChart.metalColor to create the pink metallic color, then use Box.setBackground of the title TextBox object to set it as the background color.

  • The glass shading effect of the sector labels is defined using ChartDirector.CFChart.glassEffect, then applied to the sector labels using Box.setBackground of the sector label prototype object (obtained via PieChart.setLabelStyle).

  • The rounded corners of the sector labels are configured using Box.setRoundedCorners of the sector label prototype object.
Note that in the above chart, there are a number of small sectors. With the "side label layout" method selected using PieChart.setLabelLayout, ChartDirector automatically shifts the labels up and down to avoid overlapping.

This example demonstrates a technique for further improving sector label layout by adjusting the start angle of the first sector using PieChart.setStartAngle.

If a pie chart may contain a lot of small sectors crowded together (common if the sectors are in descending or ascending order), the labels may become very crowded and need to be shifted far away to avoid overlapping.

In this case, label layout will be optimal (with the least shifting required) if the small sectors happen to lie almost horizontally.

For example, if the data is in ascending order (small sectors at the beginning), you may use a start angle of 45 degrees with clockwise sector layout. This will put the small sectors at approximately 45 - 135 degrees, which are around the horizontal position.

Similarly, if the data is in descending order (like this example), you may use a start angle of 135 degrees with clockwise sector layout to achieve similar effect.

Source Code Listing

[File: cfdemo/smallsectorpie.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the pie chart
data = Array(35, 30, 25, 7, 6, 5, 4, 3, 2, 1);

// The labels for the pie chart
labels = Array("Labor", "Production", "Facilities", "Taxes", "Misc", "Legal",
    "Insurance", "Licenses", "Transport", "Interest");

// Create a PieChart object of size 560 x 270 pixels, with a golden background and a
// 1 pixel 3D border
c = cd.PieChart(560, 270, cd.goldColor(), -1, 1);

// Add a title box using 15 pts Times Bold Italic font and metallic pink background
// color
c.addTitle("Project Cost Breakdown", "Times New Roman Bold Italic", 15
    ).setBackground(cd.metalColor("0xff9999"));

// Set the center of the pie at (280, 135) and the radius to 110 pixels
c.setPieSize(280, 135, 110);

// Draw the pie in 3D with 20 pixels 3D depth
c.set3D(20);

// Use the side label layout method
c.setLabelLayout(cd.SideLayout);

// Set the label box background color the same as the sector color, with glass
// effect, and with 5 pixels rounded corners
t = c.setLabelStyle();
t.setBackground(cd.SameAsMainColor, cd.Transparent, cd.glassEffect());
t.setRoundedCorners(5);

// Set the border color of the sector the same color as the fill color. Set the line
// color of the join line to black (0x0)
c.setLineColor(cd.SameAsMainColor, "0x000000");

// Set the start angle to 135 degrees may improve layout when there are many small
// sectors at the end of the data array (that is, data sorted in descending order).
// It is because this makes the small sectors position near the horizontal axis,
// where the text label has the least tendency to overlap. For data sorted in
// ascending order, a start angle of 45 degrees can be used instead.
c.setStartAngle(135);

// Set the pie data and the pie labels
c.setData(data, labels);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "", "title='{label}: US${value}K ({percent}%)'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Pie with Small Sectors
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Circular Label Layout

Circular Label Layout

This example demonstrates various options in the "circular label layout" method. It also demonstrates the use of alternative sector label format.

By default, in "circular label layout", the sector labels will be external and close to the perimeter of the pie.

The PieChart.setLabelPos method can be used to control the distance between the sector labels and the perimeter. It also allows enabling join lines to connect the labels to the sectors, which are useful if the labels are far away from the perimeter.

The distance between the sector labels and the perimeter can be negative, in which case the sectors will be internal to the pie.

Note also the sector label format in this example, which consists of 3 lines. It is specified using PieChart.setLabelFormat.

Source Code Listing

[File: cfdemo/circlelabelpie.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// Function to create the demo charts
function createChart(img)
{
    // Declare local variables
    var data = 0;
    var labels = 0;
    var c = 0;
    var ret = 0;

    // The data for the pie chart
    data = Array(25, 18, 15, 12, 30, 35);

    // The labels for the pie chart
    labels = Array("Labor", "Licenses", "Taxes", "Legal", "Facilities", "Production")
        ;

    // Create a PieChart object of size 300 x 300 pixels
    c = cd.PieChart(300, 300);

    if (img EQ "0") {
    //============================================================
    //    Draw a pie chart where the label is on top of the pie
    //============================================================

        // Set the center of the pie at (150, 150) and the radius to 120 pixels
        c.setPieSize(150, 150, 120);

        // Set the label position to -40 pixels from the perimeter of the pie (-ve
        // means label is inside the pie)
        c.setLabelPos(-40);

    } else {
    //============================================================
    //    Draw a pie chart where the label is outside the pie
    //============================================================

        // Set the center of the pie at (150, 150) and the radius to 80 pixels
        c.setPieSize(150, 150, 80);

        // Set the sector label position to be 20 pixels from the pie. Use a join
        // line to connect the labels to the sectors.
        c.setLabelPos(20, cd.LineColor);

    }

    // Set the label format to three lines, showing the sector name, value, and
    // percentage. The value 999 will be formatted as US$999K.
    c.setLabelFormat("{label}<*br*>US${value}K<*br*>({percent}%)");

    // Set the pie data and the pie labels
    c.setData(data, labels);

    // Explode the 1st sector (index = 0)
    c.setExplode(0);

    // Output the chart
    ret = StructNew();
    ret.imageURL = c.makeSession(GetPageContext(), "chart" & img);

    // Include tool tip for the chart
    ret.imageMap = c.getHTMLImageMap("", "",
        "title='{label}: US${value}K ({percent}%)'");

    return ret;
}

chart0 = createChart(0);
chart1 = createChart(1);

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Circular Label Layout
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart0.imageURL#" usemap="##map0" border="0" />
<map name="map0">#chart0.imageMap#</map>
<img src="getchart.cfm?#chart1.imageURL#" usemap="##map1" border="0" />
<map name="map1">#chart1.imageMap#</map>
</cfoutput>
</body>
</html>


Pie Chart with Legend

Pie Chart with Legend

This example demonstrates how to add a legend box to a pie chart. It also demonstrates the use of alternative sector label format.

  • Add a legend box using BaseChart.addLegend.

  • Change the sector label format using PieChart.setLabelFormat.

  • Add a title to the bottom of the chart using BaseChart.addTitle2.

Source Code Listing

[File: cfdemo/legendpie.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the pie chart
data = Array(25, 18, 15, 12, 8, 30, 35);

// The labels for the pie chart
labels = Array("Labor", "Licenses", "Taxes", "Legal", "Insurance", "Facilities",
    "Production");

// Create a PieChart object of size 450 x 240 pixels
c = cd.PieChart(450, 240);

// Set the center of the pie at (150, 100) and the radius to 80 pixels
c.setPieSize(150, 100, 80);

// Add a title at the bottom of the chart using Arial Bold Italic font
c.addTitle2(cd.Bottom, "Project Cost Breakdown", "Arial Bold Italic");

// Draw the pie in 3D
c.set3D();

// add a legend box where the top left corner is at (330, 40)
c.addLegend(330, 40);

// modify the label format for the sectors to $nnnK (pp.pp%)
c.setLabelFormat("{label} ${value}K<*br*>({percent}%)");

// Set the pie data and the pie labels
c.setData(data, labels);

// Explode the 1st sector (index = 0)
c.setExplode(0);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "", "title='{label}: US${value}K ({percent}%)'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Pie Chart with Legend
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Icon Pie Chart

Icon Pie Chart

This example demonstrates using CDML and Parameter Substitution and Formatting to include icons in sector labels. It also demonstrates gradient background color, glass shading effect for the title and rounded corners for the chart frame.

  • The gradient background color is created using ChartDirector.CFChart.metalColor, with blue as the base color, and in vertical orientation.

  • The rounded frame is configured using BaseChart.setRoundedFrame.

  • The glass shading effect of the title is defined using ChartDirector.CFChart.glassEffect, then applied to the title using Box.setBackground of the title TextBox object.

  • The icons file names are added to the chart as an extra field using BaseChart.addExtraField.

  • The sector label format string is specified using CDML and Parameter Substitution and Formatting as:

    <*block,valign=absmiddle*><*img={field0}*> <*block*>{label}<*br*>{percent}%<*/*><*/*>

    This means that the sector label is a block, which contains an image followed by another text block. The image file is taken from the extra field. The text block contains two lines showing the sector name and percentage.

  • The format string is applied to the chart using PieChart.setLabelFormat.

Source Code Listing

[File: cfdemo/iconpie.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the pie chart
data = Array(72, 18, 15, 12);

// The depths for the sectors
depths = Array(30, 20, 10, 10);

// The labels for the pie chart
labels = Array("Sunny", "Cloudy", "Rainy", "Snowy");

// The icons for the sectors
icons = Array("sun.png", "cloud.png", "rain.png", "snowy.png");

// Create a PieChart object of size 400 x 310 pixels, with a blue (CCCCFF) vertical
// metal gradient background, black border, 1 pixel 3D border effect and rounded
// corners
c = cd.PieChart(400, 310, cd.metalColor("0xccccff", 0), "0x000000", 1);
c.setRoundedFrame();

// Set search path to current directory for loading icon images
c.setSearchPath(GetPageContext());

// Set the center of the pie at (200, 180) and the radius to 100 pixels
c.setPieSize(200, 180, 100);

// Add a title box using 15 pts Times Bold Italic font, on a blue (CCCCFF) background
// with glass effect
c.addTitle("Weather Profile in Wonderland", "Times New Roman Bold Italic", 15
    ).setBackground("0xccccff", "0x000000", cd.glassEffect());

// Set the pie data and the pie labels
c.setData(data, labels);

// Add icons to the chart as a custom field
c.addExtraField(icons);

// Configure the sector labels using CDML to include the icon images
c.setLabelFormat(
    "<*block,valign=absmiddle*><*img={field0}*> <*block*>{label}<*br*>{percent}%" &
    "<*/*><*/*>");

// Draw the pie in 3D with variable 3D depths
c.set3D2(depths);

// Set the start angle to 225 degrees may improve layout when the depths of the
// sector are sorted in descending order, because it ensures the tallest sector is at
// the back.
c.setStartAngle(225);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "", "title='{label}: {value} days ({percent}%)'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Icon Pie Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Icon Pie Chart (2)

Icon Pie Chart (2)

This example extends the Icon Pie Chart example to demonstrate using CDML to include multiple fonts and colors in chart title, sector labels and to draw logo. It also demonstrates silver background color, rounded corners, and glass shading effect for title.

  • The silver background is achieved by using ChartDirector.CFChart.silverColor to create the silver color, then use PieChart.PieChart to set it as the chart background color.

  • The rounded frame is configured using BaseChart.setRoundedFrame.

  • The title containing multiple fonts and colors is written in CDML and added to the chart using BaseChart.addTitle.

  • The glass shading effect of the title is defined using ChartDirector.CFChart.glassEffect, then applied to the title using Box.setBackground of the title TextBox object.

  • The logo designed using CDML is added to the chart as another title using BaseChart.addTitle2 with BottomRight alignment.

  • The icons file names for sector labels are added to the chart as an extra field using BaseChart.addExtraField.

  • The sector label format string is specified using CDML and Parameter Substitution and Formatting as:

    <*block,valign=absmiddle*><*img={field0}*> {label} ({percent|0}%)

    This means that the sector label is a block, which contains an image, followed by the sector name and percentage. The image file is taken from the extra field.

  • The format string is applied to the chart using PieChart.setLabelFormat.

Source Code Listing

[File: cfdemo/iconpie2.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the pie chart
data = Array(28, 45, 5, 1, 12);

// The labels for the pie chart
labels = Array("Excellent", "Good", "Bad", "Very Bad", "Neutral");

// The icons for the sectors
icons = Array("laugh.png", "smile.png", "sad.png", "angry.png", "nocomment.png");

// Create a PieChart object of size 560 x 300 pixels, with a silver background, black
// border, 1 pxiel 3D border effect and rounded corners
c = cd.PieChart(560, 300, cd.silverColor(), "0x000000", 1);
c.setRoundedFrame();

// Set search path to current directory for loading icon images
c.setSearchPath(GetPageContext());

// Set the center of the pie at (280, 150) and the radius to 120 pixels
c.setPieSize(280, 150, 120);

// Add a title box with title written in CDML, on a sky blue (A0C8FF) background with
// glass effect
c.addTitle(
    "<*block,valign=absmiddle*><*img=doc.png*> Customer Survey: <*font=Times New " &
    "Roman Italic,color=000000*>Do you like our <*font,color=dd0000*>Hyper" &
    "<*super*>TM<*/font*> molecules?", "Times New Roman Bold Italic", 15, "0x000080"
    ).setBackground("0xa0c8ff", "0x000000", cd.glassEffect());

// Add a logo to the chart written in CDML as the bottom title aligned to the bottom
// right
c.addTitle2(cd.BottomRight,
    "<*block,valign=absmiddle*><*img=molecule.png*> <*block*><*color=FF*>" &
    "<*font=Times New Roman Bold Italic,size=12*>Molecular Engineering<*br*>" &
    "<*font=Arial,size=10*>Creating better molecules");

// Set the pie data and the pie labels
c.setData(data, labels);

// Set 3D style
c.set3D();

// Use the side label layout method
c.setLabelLayout(cd.SideLayout);

// Set the label background color to transparent
c.setLabelStyle().setBackground(cd.Transparent);

// Add icons to the chart as a custom field
c.addExtraField(icons);

// Configure the sector labels using CDML to include the icon images
c.setLabelFormat("<*block,valign=absmiddle*><*img={field0}*> {label} ({percent|0}%)")
    ;

// Explode the 3rd and 4th sectors as a group (index = 2 and 3)
c.setExplodeGroup(2, 3);

// Set the start angle to 135 degrees may improve layout when there are many small
// sectors at the end of the data array (that is, data sorted in descending order).
// It is because this makes the small sectors position near the horizontal axis,
// where the text label has the least tendency to overlap. For data sorted in
// ascending order, a start angle of 45 degrees can be used instead.
c.setStartAngle(135);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='{label}: {value} responses ({percent}%)'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Icon Pie Chart (2)
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Multi-Pie Chart

Multi-Pie Chart

This example demonstrates drawing multiple pies with different data and colors. It also demonstrates putting labels on the sectors and using sector borders.

  • The sectors colors in this example are specified using BaseChart.setColors2.

  • The sectors all have white borders set using PieChart.setLineColor. The borders around the perimeters are invisible as they are the same color as the background. The sector borders internal to the pies become the separating lines among sectors.

  • The sector labels are configured with a pale yellow background and black border. This is by getting the TextBox object representing the sector label prototype using PieChart.setLabelStyle, and then call its Box.setBackground method.

  • The sector labels are moved inside the pie by using PieChart.setLabelLayout with a negative label position.

Source Code Listing

[File: cfdemo/multipie.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// Function to create the demo charts
function createChart(img)
{
    // Declare local variables
    var data0 = 0;
    var data1 = 0;
    var data2 = 0;
    var labels = 0;
    var c = 0;
    var ret = 0;

    // The data for the pie chart
    data0 = Array(25, 18, 15);
    data1 = Array(14, 32, 24);
    data2 = Array(25, 23, 9);

    // The labels for the pie chart
    labels = Array("Software", "Hardware", "Services");

    // Create a PieChart object of size 180 x 160 pixels
    c = cd.PieChart(180, 160);

    // Set the center of the pie at (90, 80) and the radius to 60 pixels
    c.setPieSize(90, 80, 60);

    // Set the border color of the sectors to white (ffffff)
    c.setLineColor("0xffffff");

    // Set the background color of the sector label to pale yellow (ffffc0) with a
    // black border (000000)
    c.setLabelStyle().setBackground("0xffffc0", "0x000000");

    // Set the label to be slightly inside the perimeter of the circle
    c.setLabelLayout(cd.CircleLayout, -10);

    // Set the title, data and colors according to which pie to draw
    if (img EQ "0") {
        c.addTitle("Alpha Division", "Arial Bold", 8);
        c.setData(data0, labels);
        c.setColors2(cd.DataColor, Array("0xff3333", "0xff9999", "0xffcccc"));
    } else if (img EQ "1") {
        c.addTitle("Beta Division", "Arial Bold", 8);
        c.setData(data1, labels);
        c.setColors2(cd.DataColor, Array("0x33ff33", "0x99ff99", "0xccffcc"));
    } else {
        c.addTitle("Gamma Division", "Arial Bold", 8);
        c.setData(data2, labels);
        c.setColors2(cd.DataColor, Array("0x3333ff", "0x9999ff", "0xccccff"));
    }

    // Output the chart
    ret = StructNew();
    ret.imageURL = c.makeSession(GetPageContext(), "chart" & img);

    // Include tool tip for the chart
    ret.imageMap = c.getHTMLImageMap("", "",
        "title='{label}: US${value}M ({percent}%)'");

    return ret;
}

chart0 = createChart(0);
chart1 = createChart(1);
chart2 = createChart(2);

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Multi-Pie Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart0.imageURL#" usemap="##map0" border="0" />
<map name="map0">#chart0.imageMap#</map>
<img src="getchart.cfm?#chart1.imageURL#" usemap="##map1" border="0" />
<map name="map1">#chart1.imageMap#</map>
<img src="getchart.cfm?#chart2.imageURL#" usemap="##map2" border="0" />
<map name="map2">#chart2.imageMap#</map>
</cfoutput>
</body>
</html>


Donut Chart

Donut Chart

This example demonstrates a donut chart. It also demonstrates other chart effects, such as using CDML to nicely format sector labels, silver background color, rounded corners, and glass shading effect for title and sector labels.

  • A donut chart is the same as a pie chart, except that the PieChart.setDonutSize is used instead of PieChart.setPieSize.

  • The silver background is achieved by using ChartDirector.CFChart.silverColor to create the silver color, then use PieChart.PieChart to set it as the chart background color.

  • The rounded frame is configured using BaseChart.setRoundedFrame.

  • The glass shading effect of the title is defined using ChartDirector.CFChart.glassEffect, then applied to the title using Box.setBackground of the title TextBox object.

  • The glass shading effect of the sector labels is defined using ChartDirector.CFChart.glassEffect, then applied to the sector labels using Box.setBackground of the sector label prototype object (obtained via PieChart.setLabelStyle).

  • The rounded corners of the sector labels are configured using Box.setRoundedCorners of the sector label prototype object.

Source Code Listing

[File: cfdemo/donut.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the pie chart
data = Array(20, 10, 15, 12);

// The labels for the pie chart
labels = Array("Labor", "Licenses", "Facilities", "Production");

// Create a PieChart object of size 560 x 280 pixels, with a silver background, black
// border, 1 pxiel 3D border effect and rounded corners
c = cd.PieChart(560, 280, cd.silverColor(), "0x000000", 1);
c.setRoundedFrame();

// Add a title box using 15 pts Times Bold Italic font in white color, on a deep blue
// (0000CC) background with reduced-glare glass effect
c.addTitle("Donut Chart Demonstration", "Times New Roman Bold Italic", 15, "0xffffff"
    ).setBackground("0x0000cc", "0x000000", cd.glassEffect(cd.ReducedGlare));

// Set donut center at (280, 140), and outer/inner radii as 110/55 pixels
c.setDonutSize(280, 140, 110, 55);

// Set 3D effect with 3D depth of 20 pixels
c.set3D(20);

// Set the label box background color the same as the sector color, with
// reduced-glare glass effect and rounded corners
t = c.setLabelStyle();
t.setBackground(cd.SameAsMainColor, cd.Transparent, cd.glassEffect(cd.ReducedGlare));
t.setRoundedCorners();

// Set the sector label format. The label consists of two lines. The first line is
// the sector name in Times Bold Italic font and is underlined. The second line shows
// the data value and percentage.
c.setLabelFormat(
    "<*block,halign=left*><*font=Times New Roman Bold Italic,size=12,underline=1*>" &
    "{label}<*/font*><*br*>US$ {value}K ({percent}%)");

// Set the pie data and the pie labels
c.setData(data, labels);

// Use the side label layout method
c.setLabelLayout(cd.SideLayout);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "", "title='{label}: US${value}K ({percent}%)'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Donut Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Icon Donut Chart

Icon Donut Chart

This example modifies the Icon Pie Chart example by using a semi-transparent donut instead of a pie, and using metallic background color.

  • BaseChart.setColors is used to select the default semi-transparent palette transparentPalette. This palette uses semi-transparent data colors instead of the normal data colors.

  • ChartDirector.CFChart.metalColor is used to create metallic colors using light blue and blue as the base colors. The colors are then used as the chart background color by calling BaseChart.setBackground, and as chart title background color by calling Box.setBackground of the title TextBox object.

Source Code Listing

[File: cfdemo/icondonut.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the pie chart
data = Array(72, 18, 15, 12);

// The depths for the sectors
depths = Array(30, 20, 10, 10);

// The labels for the pie chart
labels = Array("Sunny", "Cloudy", "Rainy", "Snowy");

// The icons for the sectors
icons = Array("sun.png", "cloud.png", "rain.png", "snowy.png");

// Create a PieChart object of size 400 x 300 pixels
c = cd.PieChart(400, 300);

// Use the semi-transparent palette for this chart
c.setColors(cd.transparentPalette);

// Set the background to metallic light blue (CCFFFF), with a black border and 1
// pixel 3D border effect,
c.setBackground(cd.metalColor("0xccccff"), "0x000000", 1);

// Set search path to current directory for loading icon images
c.setSearchPath(GetPageContext());

// Set donut center at (200, 175), and outer/inner radii as 100/50 pixels
c.setDonutSize(200, 175, 100, 50);

// Add a title box using 15 pts Times Bold Italic font and metallic blue (8888FF)
// background color
c.addTitle("Weather Profile in Wonderland", "Times New Roman Bold Italic", 15
    ).setBackground(cd.metalColor("0x8888ff"));

// Set the pie data and the pie labels
c.setData(data, labels);

// Add icons to the chart as a custom field
c.addExtraField(icons);

// Configure the sector labels using CDML to include the icon images
c.setLabelFormat(
    "<*block,valign=absmiddle*><*img={field0}*> <*block*>{label}<*br*>{percent}%" &
    "<*/*><*/*>");

// Draw the pie in 3D with variable 3D depths
c.set3D2(depths);

// Set the start angle to 225 degrees may improve layout when the depths of the
// sector are sorted in descending order, because it ensures the tallest sector is at
// the back.
c.setStartAngle(225);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "", "title='{label}: {value} days ({percent}%)'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Icon Donut Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Texture Donut Chart

Texture Donut Chart

This example demonstrates wooden, rocky and marble texture effects by using pattern colors to load image patterns.

In ChartDirector, metallic and pattern colors are just like normal ARGB colors, and are represented as a 32-bit integer. They can be applied to anything that can be colored. In this example, metallic colors are applied to the background, while pattern colors are applied to the donut slices to create texture effects.

  • BaseChart.patternColor2 is used to load the texture images. It returns an array of integers representing the pattern colors created from the images.

  • The pattern colors are then set into the DataColor positions of the default palette using BaseChart.setColor. These colors will be used for the sectors.

Source Code Listing

[File: cfdemo/texturedonut.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the pie chart
data = Array(18, 45, 28);

// The labels for the pie chart
labels = Array("Marble", "Wood", "Granite");

// The icons for the sectors
texture = Array("marble3.png", "wood.png", "rock.png");

// Create a PieChart object of size 400 x 330 pixels, with a metallic green (88EE88)
// background, black border and 1 pixel 3D border effect
c = cd.PieChart(400, 330, cd.metalColor("0x88ee88"), "0x000000", 1);

// Set search path to current directory for loading icon images
c.setSearchPath(GetPageContext());

// Set donut center at (200, 160), and outer/inner radii as 120/60 pixels
c.setDonutSize(200, 160, 120, 60);

// Add a title box using 15 pts Times Bold Italic font and metallic deep green
// (008000) background color
c.addTitle("Material Composition", "Times New Roman Bold Italic", 15).setBackground(
    cd.metalColor("0x008000"));

// Set the pie data and the pie labels
c.setData(data, labels);

// Set the colors of the sectors to the 3 texture patterns
c.setColor(cd.DataColor + 0, c.patternColor2(texture[1]));
c.setColor(cd.DataColor + 1, c.patternColor2(texture[2]));
c.setColor(cd.DataColor + 2, c.patternColor2(texture[3]));

// Draw the pie in 3D with a 3D depth of 30 pixels
c.set3D(30);

// Use 12 pts Arial Bold Italic as the sector label font
c.setLabelStyle("Arial Bold Italic", 12);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "", "title='{label}: {value}kg ({percent}%)'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Texture Donut Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Concentric Donut Chart

Concentric Donut Chart

This example demonstrates creating concentric donut chart by merging two donuts of different radii.

The chart in this example is created as two separate PieChart objects. The first PieChart represents the outer donut chart and the overall structure of the chart (such as the legend box, chart title, etc). The second PieChart has a Transparent background and represents the inner donut chart. The two charts are merged together by using the DrawArea.merge method.

Source Code Listing

[File: cfdemo/concentric.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// Data for outer ring
data = Array(88, 124, 96);

// Data for inner ring
data2 = Array(77, 87, 45);

// Labels for the sectors
labels = Array("Hardware", "Software", "Services");

// Colors for the sectors
colors = Array("0xff9999", "0x9999ff", "0x66ff66");

//
// Create the main chart, which contains the chart title, the outer ring, and the
// legend box
//

// Create a PieChart object of size 450 x 360 pixels, with transparent background
c = cd.PieChart(450, 360);

// Add a title to the chart with 18pts Times Bold Italic font
c.addTitle("Concentric Donut Chart", "Times New Roman Bold Italic", 18);

// Set donut center at (160, 200), and outer/inner radii as 150/100 pixels
c.setDonutSize(160, 200, 150, 100);

// Add a label at the bottom-right corner of the ring to label the outer ring Use
// 12pts Arial Bold Italic font in white (ffffff) color, on a green (008800)
// background, with soft lighting effect and 5 pixels rounded corners
t = c.addText(260, 300, " Year 2006 ", "Arial Bold Italic", 12, "0xffffff");
t.setBackground("0x008800", cd.Transparent, cd.softLighting());
t.setRoundedCorners(5);

// Set the legend box at (320, 50) with 12 pts Arial Bold Italic font, with no border
c.addLegend(320, 50, True, "Arial Bold Italic", 13).setBackground(cd.Transparent,
    cd.Transparent);

// Set the pie data and the pie labels
c.setData(data, labels);

// Set the pie colors
c.setColors2(cd.DataColor, colors);

// Set pie border color to white (ffffff)
c.setLineColor("0xffffff");

// Set pie label to value in $###M format, percentage in (##.#%) format, in two
// lines.
c.setLabelFormat("${value}M<*br*>({percent|1}%)");

// Use 10pts Airal Bold for the sector labels
c.setLabelStyle("Arial Bold", 10);

// Set the label position to -25 pixels from the sector (which would be internal to
// the sector)
c.setLabelPos(-25);

//
// Create the inner ring.
//

// Create a PieChart object of size 280 x 320 pixels, with transparent background
c2 = cd.PieChart(280, 320, cd.Transparent);

// Set donut center at (110, 110), and outer/inner radii as 100/50 pixels
c2.setDonutSize(110, 110, 100, 50);

// Add a label at the center of the ring to label the inner ring. Use 12pts Arial
// Bold Italic font in white (ffffff) color, on a deep blue (0000cc) background, with
// soft lighting effect and 5 pixels rounded corners
t2 = c2.addText(110, 110, " Year 2005 ", "Arial Bold Italic", 12, "0xffffff",
    cd.Center);
t2.setBackground("0x0000cc", cd.Transparent, cd.softLighting());
t2.setRoundedCorners(5);

// Set the pie data and the pie labels
c2.setData(data2, labels);

// Set the pie colors
c2.setColors2(cd.DataColor, colors);

// Set pie border color to white (ffffff)
c2.setLineColor("0xffffff");

// Set pie label to value in $###M format, percentage in (##.#%) format, in two
// lines.
c2.setLabelFormat("${value}M<*br*>({percent|1}%)");

// Use 10pts Airal Bold for the sector labels
c2.setLabelStyle("Arial Bold", 10);

// Set the label position to -25 pixels from the sector (which would be internal to
// the sector)
c2.setLabelPos(-25);

// merge the inner ring into the outer ring at (50, 90)
c.makeChart3().merge(c2.makeChart3(), 50, 90, cd.TopLeft, 0);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// include tool tip for the chart
imageMap1 = c2.getHTMLImageMap("", "",
    "title='{label} revenue for 2005: US${value}M ({percent}%)'", 50, 90) &
    c.getHTMLImageMap("", "",
    "title='{label} revenue for 2006: US${value}M ({percent}%)'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Concentric Donut Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Text Styles and Colors

Text Styles and Colors

This example demonstrates various text styles, text colors, background colors and text box border effects.

In the chart above, 3 different pattern colors (wallpapers) are used for the chart background, legend box background and chart title background. In addition, the chart title, sector labels, and legends all have different fonts, text colors, background colors, and border styles.

  • BaseChart.patternColor2 is used to load the wallpaper images and return integers that represent the pattern colors created from the images.

  • The pattern colors are then used in BaseChart.setBackground, and also the Box.setBackground methods of the LegendBox object and title TextBox object to set the various background colors.

  • The title text and font are specified using BaseChart.addTitle.

  • The legend box font is specified using BaseChart.addLegend. It returns a LegendBox object to support further legend box configuration. In this example, the Box.setBackground method of this object is used to set the background color and 3D border effects of the legend box.

  • The default sector label font is specified using PieChart.setLabelStyle.

  • The sector label font of individual sector is specified using Sector.setLabelStyle.

  • The sector label's background color, border color and 3D border effects are specified by first obtaining the TextBox object that represents the sector label using Sector.setLabelStyle, then calling its Box.setBackground method.

Source Code Listing

[File: cfdemo/fontpie.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the pie chart
data = Array(25, 18, 15, 12, 8, 30, 35);

// The labels for the pie chart
labels = Array("Labor", "Licenses", "Taxes", "Legal", "Insurance", "Facilities",
    "Production");

// Create a PieChart object of size 480 x 300 pixels
c = cd.PieChart(480, 300);

// Set search path to current directory for loading icon images
c.setSearchPath(GetPageContext());

// Use a blue marble pattern as the background wallpaper, with a black border, and 1
// pixel 3D border effect
c.setBackground(c.patternColor("marble.png"), "0x000000", 1);

// Set the center of the pie at (150, 150) and the radius to 100 pixels
c.setPieSize(150, 150, 100);

// Add a title to the pie chart using Times Bold Italic/15 points/deep blue
// (0x000080) as font, with a wood pattern as the title background
c.addTitle("Project Cost Breakdown", "Times New Roman Bold Italic", 15, "0x000080"
    ).setBackground(c.patternColor("wood.png"));

// Draw the pie in 3D
c.set3D();

// Add a legend box using Arial Bold Italic/11 points font. Use a pink marble pattern
// as the background wallpaper, with a 1 pixel 3D border. The legend box is top-right
// aligned relative to the point (465, 70)
b = c.addLegend(465, 70, True, "Arial Bold Italic", 11);
b.setBackground(c.patternColor("marble2.png"), cd.Transparent, 1);
b.setAlignment(cd.TopRight);

// Set the default font for all sector labels to Arial Bold/8 pts/dark green
// (0x008000).
c.setLabelStyle("Arial Bold", 8, "0x008000");

// Set the pie data and the pie labels
c.setData(data, labels);

// Explode the 3rd sector
c.setExplode(2, 40);

// Use Arial Bold/12 pts/red as label font for the 3rd sector
c.sector(2).setLabelStyle("Arial Bold", 12, "0xff0000");

// Use Arial/8 pts/deep blue as label font for the 5th sector. Add a background box
// using the sector fill color (SameAsMainColor), with a black (0x000000) edge and 2
// pixel 3D border.
c.sector(4).setLabelStyle("Arial", 8, "0x000080").setBackground(cd.SameAsMainColor,
    "0x000000", 2);

// Use Arial Italic/8 pts/light red (0xff9999) as label font for the 6th sector. Add
// a dark blue (0x000080) background box with a 2 pixel 3D border.
c.sector(0).setLabelStyle("Arial Italic", 8, "0xff9999").setBackground("0x000080",
    cd.Transparent, 2);

// Use Times Bold Italic/8 pts/deep green (0x008000) as label font for 7th sector.
// Add a yellow (0xFFFF00) background box with a black (0x000000) edge.
c.sector(6).setLabelStyle("Times New Roman Bold Italic", 8, "0x008000"
    ).setBackground("0xffff00", "0x000000");

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1", cd.GIF);

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "", "title='{label}: US${value}K ({percent}%)'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Text Style and Colors
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Coloring and Wallpaper

Coloring and Wallpaper

This example demonstrates different coloring schemes and background effects.

This example demonstrates how to modify the coloring scheme using BaseChart.setColor, BaseChart.setColors and BaseChart.setColors2, and apply a background image to the chart using BaseChart.setWallpaper.

Source Code Listing

[File: cfdemo/colorpie.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// Function to create the demo charts
function createChart(img)
{
    // Declare local variables
    var data = 0;
    var labels = 0;
    var colors = 0;
    var c = 0;
    var ret = 0;

    // The data for the pie chart
    data = Array(25, 18, 15, 12, 8, 30, 35);

    // The labels for the pie chart
    labels = Array("Labor", "Licenses", "Taxes", "Legal", "Insurance", "Facilities",
        "Production");

    // Colors of the sectors if custom coloring is used
    colors = Array("0xb8bc9c", "0xecf0b9", "0x999966", "0x333366", "0xc3c3e6",
        "0x594330", "0xa0bdc4");

    // Create a PieChart object of size 280 x 240 pixels
    c = cd.PieChart(280, 240);

    // Set search path to current directory for loading icon images
    c.setSearchPath(GetPageContext());

    // Set the center of the pie at (140, 120) and the radius to 80 pixels
    c.setPieSize(140, 120, 80);

    // Draw the pie in 3D
    c.set3D();

    // Set the coloring schema
    if (img EQ "0") {
        c.addTitle("Custom Colors");
        // set the LineColor to light gray
        c.setColor(cd.LineColor, "0xc0c0c0");
        // use given color array as the data colors (sector colors)
        c.setColors2(cd.DataColor, colors);
    } else if (img EQ "1") {
        c.addTitle("Dark Background Colors");
        // use the standard white on black palette
        c.setColors(cd.whiteOnBlackPalette);
    } else if (img EQ "2") {
        c.addTitle("Wallpaper As Background");
        c.setWallpaper("bg.png");
    } else {
        c.addTitle("Transparent Colors");
        c.setWallpaper("bg.png");
        // use semi-transparent colors to allow the background to be seen
        c.setColors(cd.transparentPalette);
    }

    // Set the pie data and the pie labels
    c.setData(data, labels);

    // Explode the 1st sector (index = 0)
    c.setExplode(0);

    // Output the chart
    ret = StructNew();
    ret.imageURL = c.makeSession(GetPageContext(), "chart" & img, cd.GIF);

    // Include tool tip for the chart
    ret.imageMap = c.getHTMLImageMap("", "",
        "title='{label}: US${value}K ({percent}%)'");

    return ret;
}

chart0 = createChart(0);
chart1 = createChart(1);
chart2 = createChart(2);
chart3 = createChart(3);

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Coloring and Wallpaper
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart0.imageURL#" usemap="##map0" border="0" />
<map name="map0">#chart0.imageMap#</map>
<img src="getchart.cfm?#chart1.imageURL#" usemap="##map1" border="0" />
<map name="map1">#chart1.imageMap#</map>
<img src="getchart.cfm?#chart2.imageURL#" usemap="##map2" border="0" />
<map name="map2">#chart2.imageMap#</map>
<img src="getchart.cfm?#chart3.imageURL#" usemap="##map3" border="0" />
<map name="map3">#chart3.imageMap#</map>
</cfoutput>
</body>
</html>


3D Angle

3D Angle

This example demonstrates the effects of different 3D angles.

ChartDirector allows the 3D depth and angles to be configured using PieChart.set3D and PieChart.set3D2.

This example also demonstrates how to disable sector labels. This is setting their colors to Transparent using PieChart.setLabelStyle.

Source Code Listing

[File: cfdemo/threedanglepie.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// Function to create the demo charts
function createChart(img)
{
    // Declare local variables
    var angle = 0;
    var data = 0;
    var labels = 0;
    var c = 0;
    var ret = 0;

    // the tilt angle of the pie
    angle = Int(img) * 15;

    // The data for the pie chart
    data = Array(25, 18, 15, 12, 8, 30, 35);

    // The labels for the pie chart
    labels = Array("Labor", "Licenses", "Taxes", "Legal", "Insurance", "Facilities",
        "Production");

    // Create a PieChart object of size 100 x 110 pixels
    c = cd.PieChart(100, 110);

    // Set the center of the pie at (50, 55) and the radius to 38 pixels
    c.setPieSize(50, 55, 38);

    // Set the depth and tilt angle of the 3D pie (-1 means auto depth)
    c.set3D(-1, angle);

    // Add a title showing the tilt angle
    c.addTitle("Tilt = " & angle & " deg", "Arial", 8);

    // Set the pie data
    c.setData(data, labels);

    // Disable the sector labels by setting the color to Transparent
    c.setLabelStyle("", 8, cd.Transparent);

    // Output the chart
    ret = StructNew();
    ret.imageURL = c.makeSession(GetPageContext(), "chart" & img);

    // Include tool tip for the chart
    ret.imageMap = c.getHTMLImageMap("", "",
        "title='{label}: US${value}K ({percent}%)'");

    return ret;
}

chart0 = createChart(0);
chart1 = createChart(1);
chart2 = createChart(2);
chart3 = createChart(3);
chart4 = createChart(4);
chart5 = createChart(5);
chart6 = createChart(6);

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    3D Angle
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart0.imageURL#" usemap="##map0" border="0" />
<map name="map0">#chart0.imageMap#</map>
<img src="getchart.cfm?#chart1.imageURL#" usemap="##map1" border="0" />
<map name="map1">#chart1.imageMap#</map>
<img src="getchart.cfm?#chart2.imageURL#" usemap="##map2" border="0" />
<map name="map2">#chart2.imageMap#</map>
<img src="getchart.cfm?#chart3.imageURL#" usemap="##map3" border="0" />
<map name="map3">#chart3.imageMap#</map>
<img src="getchart.cfm?#chart4.imageURL#" usemap="##map4" border="0" />
<map name="map4">#chart4.imageMap#</map>
<img src="getchart.cfm?#chart5.imageURL#" usemap="##map5" border="0" />
<map name="map5">#chart5.imageMap#</map>
<img src="getchart.cfm?#chart6.imageURL#" usemap="##map6" border="0" />
<map name="map6">#chart6.imageMap#</map>
</cfoutput>
</body>
</html>


3D Depth

3D Depth

This example demonstrates the effects of different 3D depths.

ChartDirector allows the 3D depth and angles to be configured using PieChart.set3D and PieChart.set3D2.

Source Code Listing

[File: cfdemo/threeddepthpie.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// Function to create the demo charts
function createChart(img)
{
    // Declare local variables
    var depth = 0;
    var data = 0;
    var labels = 0;
    var c = 0;
    var ret = 0;

    // the tilt angle of the pie
    depth = Int(img) * 5 + 5;

    // The data for the pie chart
    data = Array(25, 18, 15, 12, 8, 30, 35);

    // The labels for the pie chart
    labels = Array("Labor", "Licenses", "Taxes", "Legal", "Insurance", "Facilities",
        "Production");

    // Create a PieChart object of size 100 x 110 pixels
    c = cd.PieChart(100, 110);

    // Set the center of the pie at (50, 55) and the radius to 38 pixels
    c.setPieSize(50, 55, 38);

    // Set the depth of the 3D pie
    c.set3D(depth);

    // Add a title showing the depth
    c.addTitle("Depth = " & depth & " pixels", "Arial", 8);

    // Set the pie data
    c.setData(data, labels);

    // Disable the sector labels by setting the color to Transparent
    c.setLabelStyle("", 8, cd.Transparent);

    // Output the chart
    ret = StructNew();
    ret.imageURL = c.makeSession(GetPageContext(), "chart" & img);

    // Include tool tip for the chart
    ret.imageMap = c.getHTMLImageMap("", "",
        "title='{label}: US${value}K ({percent}%)'");

    return ret;
}

chart0 = createChart(0);
chart1 = createChart(1);
chart2 = createChart(2);
chart3 = createChart(3);
chart4 = createChart(4);

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    3D Depth
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart0.imageURL#" usemap="##map0" border="0" />
<map name="map0">#chart0.imageMap#</map>
<img src="getchart.cfm?#chart1.imageURL#" usemap="##map1" border="0" />
<map name="map1">#chart1.imageMap#</map>
<img src="getchart.cfm?#chart2.imageURL#" usemap="##map2" border="0" />
<map name="map2">#chart2.imageMap#</map>
<img src="getchart.cfm?#chart3.imageURL#" usemap="##map3" border="0" />
<map name="map3">#chart3.imageMap#</map>
<img src="getchart.cfm?#chart4.imageURL#" usemap="##map4" border="0" />
<map name="map4">#chart4.imageMap#</map>
</cfoutput>
</body>
</html>


3D Shadow Mode

3D Shadow Mode

This example demonstrates an alternative 3D drawing method that uses shadows.

The standard way to draw a pie chart in 3D is to view the chart from an inclined angle. Using this method, the surface of a 3D pie will become an ellipse.

ChartDirector supports an alternative way to draw a pie chart in 3D - to draw the 3D portion like a shadow. The 3D pie will remain perfectly circular, and the sector areas will correctly reflect its percentages.

The 3D drawing method is configured using PieChart.set3D.

Source Code Listing

[File: cfdemo/shadowpie.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// Function to create the demo charts
function createChart(img)
{
    // Declare local variables
    var angle = 0;
    var data = 0;
    var labels = 0;
    var c = 0;
    var ret = 0;

    // the tilt angle of the pie
    angle = Int(img) * 90 + 45;

    // The data for the pie chart
    data = Array(25, 18, 15, 12, 8, 30, 35);

    // The labels for the pie chart
    labels = Array("Labor", "Licenses", "Taxes", "Legal", "Insurance", "Facilities",
        "Production");

    // Create a PieChart object of size 100 x 110 pixels
    c = cd.PieChart(100, 110);

    // Set the center of the pie at (50, 55) and the radius to 36 pixels
    c.setPieSize(50, 55, 36);

    // Set the depth, tilt angle and 3D mode of the 3D pie (-1 means auto depth,
    // "true" means the 3D effect is in shadow mode)
    c.set3D(-1, angle, True);

    // Add a title showing the shadow angle
    c.addTitle("Shadow @ " & angle & " deg", "Arial", 8);

    // Set the pie data
    c.setData(data, labels);

    // Disable the sector labels by setting the color to Transparent
    c.setLabelStyle("", 8, cd.Transparent);

    // Output the chart
    ret = StructNew();
    ret.imageURL = c.makeSession(GetPageContext(), "chart" & img);

    // Include tool tip for the chart
    ret.imageMap = c.getHTMLImageMap("", "",
        "title='{label}: US${value}K ({percent}%)'");

    return ret;
}

chart0 = createChart(0);
chart1 = createChart(1);
chart2 = createChart(2);
chart3 = createChart(3);

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    3D Shadow Mode
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart0.imageURL#" usemap="##map0" border="0" />
<map name="map0">#chart0.imageMap#</map>
<img src="getchart.cfm?#chart1.imageURL#" usemap="##map1" border="0" />
<map name="map1">#chart1.imageMap#</map>
<img src="getchart.cfm?#chart2.imageURL#" usemap="##map2" border="0" />
<map name="map2">#chart2.imageMap#</map>
<img src="getchart.cfm?#chart3.imageURL#" usemap="##map3" border="0" />
<map name="map3">#chart3.imageMap#</map>
</cfoutput>
</body>
</html>


Start Angle and Direction

Start Angle and Direction

This example demonstrates different sector layout angles and directions.

By default, ChartDirector positions sectors starting from the upward pointing position, and in clockwise direction.

The start angle and layout direction can be changed using PieChart.setStartAngle.

One common application for the PieChart.setStartAngle method is to facilitate layout of pie charts containing many small sectors. Please refer to Pie with Small Sectors.

Source Code Listing

[File: cfdemo/anglepie.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// Function to create the demo charts
function createChart(img)
{
    // Declare local variables
    var angle = 0;
    var clockwise = 0;
    var data = 0;
    var labels = 0;
    var c = 0;
    var ret = 0;

    // Determine the starting angle and direction based on input parameter
    angle = 0;
    clockwise = True;
    if (img NEQ "0") {
        angle = 90;
        clockwise = False;
    }

    // The data for the pie chart
    data = Array(25, 18, 15, 12, 8, 30, 35);

    // The labels for the pie chart
    labels = Array("Labor", "Licenses", "Taxes", "Legal", "Insurance", "Facilities",
        "Production");

    // Create a PieChart object of size 280 x 240 pixels
    c = cd.PieChart(280, 240);

    // Set the center of the pie at (140, 130) and the radius to 80 pixels
    c.setPieSize(140, 130, 80);

    // Add a title to the pie to show the start angle and direction
    if (clockwise) {
        c.addTitle("Start Angle = " & angle & " degrees<*br*>Direction = Clockwise");
    } else {
        c.addTitle("Start Angle = " & angle &
            " degrees<*br*>Direction = AntiClockwise");
    }

    // Set the pie start angle and direction
    c.setStartAngle(angle, clockwise);

    // Draw the pie in 3D
    c.set3D();

    // Set the pie data and the pie labels
    c.setData(data, labels);

    // Explode the 1st sector (index = 0)
    c.setExplode(0);

    // Output the chart
    ret = StructNew();
    ret.imageURL = c.makeSession(GetPageContext(), "chart" & img);

    // Include tool tip for the chart
    ret.imageMap = c.getHTMLImageMap("", "",
        "title='{label}: US${value}K ({percent}%)'");

    return ret;
}

chart0 = createChart(0);
chart1 = createChart(1);

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Start Angle and Direction
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart0.imageURL#" usemap="##map0" border="0" />
<map name="map0">#chart0.imageMap#</map>
<img src="getchart.cfm?#chart1.imageURL#" usemap="##map1" border="0" />
<map name="map1">#chart1.imageMap#</map>
</cfoutput>
</body>
</html>


Donut Width

Donut Width

This example demonstrates the effects of different donut widths.

Donut widths are configured by using different inner and outer radii when calling PieChart.setDonutSize.

Source Code Listing

[File: cfdemo/donutwidth.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// Function to create the demo charts
function createChart(img)
{
    // Declare local variables
    var donutRadius = 0;
    var data = 0;
    var labels = 0;
    var c = 0;
    var ret = 0;

    // Determine the donut inner radius (as percentage of outer radius) based on
    // input parameter
    donutRadius = Int(img) * 25;

    // The data for the pie chart
    data = Array(10, 10, 10, 10, 10);

    // The labels for the pie chart
    labels = Array("Marble", "Wood", "Granite", "Plastic", "Metal");

    // Create a PieChart object of size 150 x 120 pixels, with a grey (EEEEEE)
    // background, black border and 1 pixel 3D border effect
    c = cd.PieChart(150, 120, "0xeeeeee", "0x000000", 1);

    // Set donut center at (75, 65) and the outer radius to 50 pixels. Inner radius
    // is computed according donutWidth
    c.setDonutSize(75, 60, 50, Int(50 * donutRadius / 100));

    // Add a title to show the donut width
    c.addTitle("Inner Radius = " & donutRadius & " %", "Arial", 10).setBackground(
        "0xcccccc", 0);

    // Draw the pie in 3D
    c.set3D(12);

    // Set the pie data and the pie labels
    c.setData(data, labels);

    // Disable the sector labels by setting the color to Transparent
    c.setLabelStyle("", 8, cd.Transparent);

    // Output the chart
    ret = StructNew();
    ret.imageURL = c.makeSession(GetPageContext(), "chart" & img);

    // Include tool tip for the chart
    ret.imageMap = c.getHTMLImageMap("", "",
        "title='{label}: {value}kg ({percent}%)'");

    return ret;
}

chart0 = createChart(0);
chart1 = createChart(1);
chart2 = createChart(2);
chart3 = createChart(3);
chart4 = createChart(4);

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Donut Width
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart0.imageURL#" usemap="##map0" border="0" />
<map name="map0">#chart0.imageMap#</map>
<img src="getchart.cfm?#chart1.imageURL#" usemap="##map1" border="0" />
<map name="map1">#chart1.imageMap#</map>
<img src="getchart.cfm?#chart2.imageURL#" usemap="##map2" border="0" />
<map name="map2">#chart2.imageMap#</map>
<img src="getchart.cfm?#chart3.imageURL#" usemap="##map3" border="0" />
<map name="map3">#chart3.imageMap#</map>
<img src="getchart.cfm?#chart4.imageURL#" usemap="##map4" border="0" />
<map name="map4">#chart4.imageMap#</map>
</cfoutput>
</body>
</html>


XY Charts

XY Charts

In this section, we will discuss how to create XY Charts using ChartDirector through a number of examples.

In ChartDirector, XY Chart refers to any chart that has x and y axes. These include bar charts, line charts, spline line charts, stepline charts, scatter charts, bubble charts, trend line charts, area charts, high-low-open-close charts, candlestick charts, box-whisker charts, etc.

ChartDirector employs a layering architecture for XY charts. Each chart type is represented as a layer on a plot area. You can include multiple layers on the same plot area to create arbitrary combination charts.

For clarity and ease of understanding, this documentation is separated into sections to explain each layer type individually. Please note that each XY chart type is just a layer in the XY Chart, and you may freely combine them together to create any arbitrary combination charts.

In this section

Bar Charts
Demonstrates 2D and 3D bar charts, vertical and horizontal bar charts, multi-color bar charts, stacked bar charts, multi-bar charts, multi-stacked bar charts, depth bar charts, bar labels, and a number of chart formatting features.

Line Charts
Demonstrates 2D and 3D line charts, multi-line charts, spline line charts, step line charts, rotated line charts, data symbols, lines with error symbols, interline coloring, discontinuous lines, and a number of chart formatting features.

Trend and Curve Fitting
Demonstrates linear regression trending lines with confidence bands, and arbitrary curve fitting using LOWESS.

Scatter/Bubble Charts
Demonstrates scatter and bubble charts, custom scatter symbols and labels, non-circular bubbles and xy independently scaled bubbles.

Area Charts
Demonstrates 2D and 3D area charts, stacked area charts, depth area charts, percentage area charts, rotated area charts, and a number of chart formatting and area filling features.

Box-Whisker Charts
Demonstrates vertical and horizontal box-whisker charts, as well as simple gantt charts.

Finance Charts
Demonstrates creating full featured finance charts combining high-low-open-close charts, candlesticks charts, volume charts, moving averages, Bollinger bands, Donchian channels, RSI, MACD, Stochastic, etc, and using using ChartDirector's array manipulation utility class ArrayMath to compute various financial indicators.

Other XY Chart Features
Demonstrates various features common to all XY Charts, such as marks and zones, zone colors, dual x-axis, dual y-axis, text styles and coloring control, backgrounds and wallpapers, log scale axis, and other axis scaling control features.


Bar Charts

Bar Charts

Title | Description
Simple Bar Chart | Demonstrates the basic steps in creating bar charts.
Multi-Color Bar Chart | Demonstrates creating a multi-color bar chart, in which each bar has a different color. Also demonstrates metallic background colors and various 3D border effects.
Soft Bar Shading | Demonstrates using soft lighting effects for bars and gradient color for plot area background. Also demonstrates putting axis ticks in between axis labels, as opposed to at the axis labels.
Glass Bar Shading | Demonstrates using glass shading effect for bars and gradient color for plot area background. Also demonstrates putting axis labels on both sides of the plot area.
Cylinder Bar Shading | Demonstrates using cylinder shading effect for bars and gradient color for plot area background. Also demonstrates putting axis labels on both sides of the plot area.
3D Bar Chart | Demonstrates using Layer.set3D to set the bars to 3D style.
Cylinder Bar Shape | Demonstrates bars of cylinder shape.
Polygon Bar Shapes | Demonstrates bars of various polygonal shapes.
Stacked Bar Chart | Demonstrates creating a stacked bar chart, completed with bar labels and legend box.
Percentage Bar Chart | Demonstrates creating a percentage bar chart. Also demonstrates how to include icons in the legend box using CDML.
Multi-Bar Chart | Demonstrates a multi-bar chart, in which bars are clustered. Also demonstrates using alternative plot area background colors, and putting legends internal to the plot area.
Soft Multi-Bar Chart | Demonstrates a multi-bar chart with soft lighting effects for bars and gradient color for plot area background.
Glass Multi-Bar Chart | Demonstrates a multi-bar chart with glass shading effect for bars and gradient color for plot area background.
Multi-Cylinder Chart | Demonstrates a multi-bar chart with cylinder shading effects. Also demonstrates using dotted line style for grid lines.
Multi-Shape Bar Chart | Demonstrates a multi-bar chart in which each data set has a different bar shape.
Overlapping Bar Chart | Demonstrates a multi-bar chart in which the bars within a cluster overlaps.
Multi-Stacked Bar Chart | Demonstrates combining multi-bar style with stacked bar style. Also demonstrates drawing horizontal bar charts, using icons in axis labels with CDML, customizing legend and bar labels, controlling bar widths and centering legend box.
Depth Bar Chart | Demonstrates using multiple bar layers with semi-transparent colors to create a depth bar chart.
Positive Negative Bars | Demonstrates a bar chart containing positive and negative data, represented by different colors.
Borderless Bar Chart | Demonstrates a horizontal bar chart with no axes, grid lines or and plot area border. Also demonstrates using gradient colors for the bars, and a number of other ChartDirector features.
Dual Horizontal Bar Charts | Demonstrates combining two horizontal bar charts of opposite direction using a MultiChart, and a number of other ChartDirector features.
Pareto Chart | Demonstrates the pareto chart style.
Bar Gap | Demonstrates the effects of different bar gaps configured using BarLayer.setBarGap.


Simple Bar Chart

Simple Bar Chart

This example demonstrates the basic steps in creating bar charts.

  • Create an XYChart object using XYChart.XYChart.

  • Specify the plot area of the chart using XYChart.setPlotArea. The plot area is the rectangle bounded by the x and y axes. You should leave some margin on the outside of the plot area for axis labels, chart titles, etc.

  • Specify the labels on the x-axis using Axis.setLabels.

  • Add a bar layer and specify the data for the bars using XYChart.addBarLayer.

  • Generate the chart using BaseChart.makeSession.

  • Generate tool tips for the chart using BaseChart.getHTMLImageMap.

Source Code Listing

[File: cfdemo/simplebar.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the bar chart
data = Array(85, 156, 179.5, 211, 123);

// The labels for the bar chart
labels = Array("Mon", "Tue", "Wed", "Thu", "Fri");

// Create a XYChart object of size 250 x 250 pixels
c = cd.XYChart(250, 250);

// Set the plotarea at (30, 20) and of size 200 x 200 pixels
c.setPlotArea(30, 20, 200, 200);

// Add a bar chart layer using the given data
c.addBarLayer(data);

// Set the labels on the x axis.
c.xAxis().setLabels(labels);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "", "title='{xLabel}: US${value}K'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Simple Bar Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Multi-Color Bar Chart

Multi-Color Bar Chart

This example demonstrates creating a multi-color bar chart, in which each bar has a different color. It also demonstrates metallic background colors and various 3D border effects.

A multi-color bar layer is a bar layer in which each bar has a different color. It is created using XYChart.addBarLayer3. The colors can be specified explicitly (as is in this example), or can be taken automatically from the color palette.

  • Use ChartDirector.CFChart.goldColor to create a golden color. Set it as the background color with 3D border effects using XYChart.XYChart.

  • Use ChartDirector.CFChart.metalColor to create a metallic blue color. Set it as the chart title background color with 3D border effects by using Box.setBackground of the title TextBox object.

  • Use XYChart.addBarLayer2 to create a multi-color bar layer.

  • Set 3D border effects for the bars using Layer.setBorderColor.

Source Code Listing

[File: cfdemo/colorbar.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the bar chart
data = Array(85, 156, 179.5, 211, 123);

// The labels for the bar chart
labels = Array("Mon", "Tue", "Wed", "Thu", "Fri");

// The colors for the bar chart
colors = Array("0xb8bc9c", "0xa0bdc4", "0x999966", "0x333366", "0xc3c3e6");

// Create a XYChart object of size 300 x 220 pixels. Use golden background color. Use
// a 2 pixel 3D border.
c = cd.XYChart(300, 220, cd.goldColor(), -1, 2);

// Add a title box using 10 point Arial Bold font. Set the background color to
// metallic blue (9999FF) Use a 1 pixel 3D border.
c.addTitle("Daily Network Load", "Arial Bold", 10).setBackground(cd.metalColor(
    "0x9999ff"), -1, 1);

// Set the plotarea at (40, 40) and of 240 x 150 pixels in size
c.setPlotArea(40, 40, 240, 150);

// Add a multi-color bar chart layer using the given data and colors. Use a 1 pixel
// 3D border for the bars.
c.addBarLayer3(data, colors).setBorderColor(-1, 1);

// Set the labels on the x axis.
c.xAxis().setLabels(labels);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "", "title='{xLabel}: {value} GBytes'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Multi-Color Bar Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Soft Bar Shading

Soft Bar Shading

This example demonstrates using soft lighting effects for bars and gradient color for plot area background. It also demonstrates putting axis ticks in between axis labels, as opposed to at the axis labels.

Soft lighting is a special shading effect that look like gradient coloring. In this example, soft lighting effect is applied to the bars with the light coming from the left direction.

  • The gradient plot area background is configured by using BaseChart.linearGradientColor to define the gradient color, then use XYChart.setPlotArea to apply it to the plot area.

  • The XYChart.setPlotArea also sets the plot area border and grid line colors to white.

  • The soft lighting effect of the bars is defined using ChartDirector.CFChart.softLighting, then applied to the bars using Layer.setBorderColor.

  • The ticks in this example is offsetted by 0.5 units using Axis.setTickOffset. As a result, they are not center aligned with the axis labels, but are in between the labels.
See Soft Multi-Bar Chart for another example of soft lighting effect with the light coming from the top direction.

Source Code Listing

[File: cfdemo/softlightbar.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the bar chart
data = Array(450, 560, 630, 800, 1100, 1350, 1600, 1950, 2300, 2700);

// The labels for the bar chart
labels = Array("1996", "1997", "1998", "1999", "2000", "2001", "2002", "2003",
    "2004", "2005");

// Create a XYChart object of size 600 x 360 pixels
c = cd.XYChart(600, 360);

// Add a title to the chart using 18pts Times Bold Italic font
c.addTitle("Annual Revenue for Star Tech", "Times New Roman Bold Italic", 18);

// Set the plotarea at (60, 40) and of size 500 x 280 pixels. Use a vertical gradient
// color from light blue (eeeeff) to deep blue (0000cc) as background. Set border and
// grid lines to white (ffffff).
c.setPlotArea(60, 40, 500, 280, c.linearGradientColor(60, 40, 60, 280, "0xeeeeff",
    "0x0000cc"), -1, "0xffffff", "0xffffff");

// Add a multi-color bar chart layer using the supplied data. Use soft lighting
// effect with light direction from left.
c.addBarLayer3(data).setBorderColor(cd.Transparent, cd.softLighting(cd.Left));

// Set x axis labels using the given labels
c.xAxis().setLabels(labels);

// Draw the ticks between label positions (instead of at label positions)
c.xAxis().setTickOffset(0.5);

// Add a title to the y axis with 10pts Arial Bold font
c.yAxis().setTitle("USD (millions)", "Arial Bold", 10);

// Set axis label style to 8pts Arial Bold
c.xAxis().setLabelStyle("Arial Bold", 8);
c.yAxis().setLabelStyle("Arial Bold", 8);

// Set axis line width to 2 pixels
c.xAxis().setWidth(2);
c.yAxis().setWidth(2);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "", "title='Year {xLabel}: US$ {value}M'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Soft Bar Shading
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Glass Bar Shading

Glass Bar Shading

This example demonstrates using glass shading effect for bars and gradient color for plot area background. It also demonstrates putting axis labels on both sides of the plot area.

Glass lighting is a complex shading effect that gives a look and feel of tinted glass or semi-transparent plastic material. This effect involves glare and variation of lighting caused by reflection and refraction inside the material.

  • The gradient plot area background is configured by using BaseChart.linearGradientColor to define the gradient color, then use XYChart.setPlotArea to apply it to the plot area.

  • The XYChart.setPlotArea also sets the plot area border and grid line colors to white.

  • The glass shading effect of the bars is defined using ChartDirector.CFChart.glassEffect, then applied to the bars using Layer.setBorderColor.

  • In the example, the chart is configured using XYChart.syncYAxis to show two synchronized y-axes on both sides of the plot area.

  • The axes are invisible in this chart. Only the axis labels are visible. This is by using Axis.setColors to set the axes to Transparent.

  • The axis label fonts are set to Arial bold using Axis.setLabelStyle.

Source Code Listing

[File: cfdemo/glasslightbar.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the bar chart
data = Array(450, 560, 630, 800, 1100, 1350, 1600, 1950, 2300, 2700);

// The labels for the bar chart
labels = Array("1996", "1997", "1998", "1999", "2000", "2001", "2002", "2003",
    "2004", "2005");

// Create a XYChart object of size 600 x 360 pixels
c = cd.XYChart(600, 360);

// Set the plotarea at (60, 40) and of size 480 x 280 pixels. Use a vertical gradient
// color from light blue (eeeeff) to deep blue (0000cc) as background. Set border and
// grid lines to white (ffffff).
c.setPlotArea(60, 40, 480, 280, c.linearGradientColor(60, 40, 60, 280, "0xeeeeff",
    "0x0000cc"), -1, "0xffffff", "0xffffff");

// Add a title to the chart using 18pts Times Bold Italic font
c.addTitle("Annual Revenue for Star Tech", "Times New Roman Bold Italic", 18);

// Add a multi-color bar chart layer using the supplied data. Use glass lighting
// effect with light direction from the left.
c.addBarLayer3(data).setBorderColor(cd.Transparent, cd.glassEffect(cd.NormalGlare,
    cd.Left));

// Set the x axis labels
c.xAxis().setLabels(labels);

// Show the same scale on the left and right y-axes
c.syncYAxis();

// Set the left y-axis and right y-axis title using 10pt Arial Bold font
c.yAxis().setTitle("USD (millions)", "Arial Bold", 10);
c.yAxis2().setTitle("USD (millions)", "Arial Bold", 10);

// Set all axes to transparent
c.xAxis().setColors(cd.Transparent);
c.yAxis().setColors(cd.Transparent);
c.yAxis2().setColors(cd.Transparent);

// Set the label styles of all axes to 8pt Arial Bold font
c.xAxis().setLabelStyle("Arial Bold", 8);
c.yAxis().setLabelStyle("Arial Bold", 8);
c.yAxis2().setLabelStyle("Arial Bold", 8);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "", "title='Year {xLabel}: US$ {value}M'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Glass Bar Shading
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Cylinder Bar Shading

Cylinder Bar Shading

This example demonstrates using cylinder shading effect for bars and gradient color for plot area background. It also demonstrates putting axis labels on both sides of the plot area.

The cylinder shading effect is the result of using the cylinder bar shape in 2D.

  • The gradient plot area background is configured by using BaseChart.linearGradientColor to define the gradient color, then use XYChart.setPlotArea to apply it to the plot area.

  • The XYChart.setPlotArea also sets the plot area border and grid line colors to white.

  • The cylinder shading effect is configured by using BarLayer.setBarShape with CircleShape. In 2D, the circle shape is represented as cylinder shading.

  • In the example, the chart is configured using XYChart.syncYAxis to show two synchronized y-axes on both sides of the plot area.

  • The axes are invisible in this chart. Only the axis labels are visible. This is by using Axis.setColors to set the axes to Transparent.

  • The axis label fonts are set to Arial bold using Axis.setLabelStyle.

Source Code Listing

[File: cfdemo/cylinderlightbar.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the bar chart
data = Array(450, 560, 630, 800, 1100, 1350, 1600, 1950, 2300, 2700);

// The labels for the bar chart
labels = Array("1996", "1997", "1998", "1999", "2000", "2001", "2002", "2003",
    "2004", "2005");

// Create a XYChart object of size 600 x 360 pixels
c = cd.XYChart(600, 360);

// Add a title to the chart using 18pts Times Bold Italic font
c.addTitle("Annual Revenue for Star Tech", "Times New Roman Bold Italic", 18);

// Set the plotarea at (60, 40) and of size 480 x 280 pixels. Use a vertical gradient
// color from light green (eeffee) to dark green (008800) as background. Set border
// and grid lines to white (ffffff).
c.setPlotArea(60, 40, 480, 280, c.linearGradientColor(60, 40, 60, 280, "0xeeffee",
    "0x008800"), -1, "0xffffff", "0xffffff");

// Add a multi-color bar chart layer using the supplied data. Set cylinder bar shape.
c.addBarLayer3(data).setBarShape(cd.CircleShape);

// Set the labels on the x axis.
c.xAxis().setLabels(labels);

// Show the same scale on the left and right y-axes
c.syncYAxis();

// Set the left y-axis and right y-axis title using 10pt Arial Bold font
c.yAxis().setTitle("USD (millions)", "Arial Bold", 10);
c.yAxis2().setTitle("USD (millions)", "Arial Bold", 10);

// Set all axes to transparent
c.xAxis().setColors(cd.Transparent);
c.yAxis().setColors(cd.Transparent);
c.yAxis2().setColors(cd.Transparent);

// Set the label styles of all axes to 8pt Arial Bold font
c.xAxis().setLabelStyle("Arial Bold", 8);
c.yAxis().setLabelStyle("Arial Bold", 8);
c.yAxis2().setLabelStyle("Arial Bold", 8);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "", "title='Year {xLabel}: US$ {value}M'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Cylinder Bar Shading
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


3D Bar Chart

3D Bar Chart

This example demonstrates using Layer.set3D to set the bars to 3D style.

Source Code Listing

[File: cfdemo/threedbar.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the bar chart
data = Array(85, 156, 179.5, 211, 123);

// The labels for the bar chart
labels = Array("Mon", "Tue", "Wed", "Thu", "Fri");

// Create a XYChart object of size 300 x 280 pixels
c = cd.XYChart(300, 280);

// Set the plotarea at (45, 30) and of size 200 x 200 pixels
c.setPlotArea(45, 30, 200, 200);

// Add a title to the chart
c.addTitle("Weekly Server Load");

// Add a title to the y axis
c.yAxis().setTitle("MBytes");

// Add a title to the x axis
c.xAxis().setTitle("Work Week 25");

// Add a bar chart layer with green (0x00ff00) bars using the given data
c.addBarLayer(data, "0x00ff00").set3D();

// Set the labels on the x axis.
c.xAxis().setLabels(labels);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "", "title='{xLabel}: {value} MBytes'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    3D Bar Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Cylinder Bar Shape

Cylinder Bar Shape

This example demonstrates bars of cylinder shape.

ChartDirector supports bars in cylindrical or arbitrary polygonal shapes. The shape are specified using BarLayer.setBarShape or BarLayer.setBarShape2. In this example, the cylindrical shape is illustrated.

See Shape Specification on how built-in and custom shapes are defined in ChartDirector.

Source Code Listing

[File: cfdemo/cylinderbar.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the bar chart
data = Array(85, 156, 179.5, 211, 123);

// The labels for the bar chart
labels = Array("Mon", "Tue", "Wed", "Thu", "Fri");

// Create a XYChart object of size 400 x 240 pixels.
c = cd.XYChart(400, 240);

// Add a title to the chart using 14 pts Times Bold Italic font
c.addTitle("Weekly Server Load", "Times New Roman Bold Italic", 14);

// Set the plotarea at (45, 40) and of 300 x 160 pixels in size. Use alternating
// light grey (f8f8f8) / white (ffffff) background.
c.setPlotArea(45, 40, 300, 160, "0xf8f8f8", "0xffffff");

// Add a multi-color bar chart layer
layer = c.addBarLayer3(data);

// Set layer to 3D with 10 pixels 3D depth
layer.set3D(10);

// Set bar shape to circular (cylinder)
layer.setBarShape(cd.CircleShape);

// Set the labels on the x axis.
c.xAxis().setLabels(labels);

// Add a title to the y axis
c.yAxis().setTitle("MBytes");

// Add a title to the x axis
c.xAxis().setTitle("Work Week 25");

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "", "title='{xLabel}: {value} MBytes'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Cylinder Bar Shape
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Polygon Bar Shapes

Polygon Bar Shapes

This example demonstrates bars of various polygonal shapes.

ChartDirector supports bars in cylindrical or arbitrary polygonal shapes. This is specified by using BarLayer.setBarShape and BarLayer.setBarShape2. In this example, various polygonal shapes are illustrated.

See Shape Specification on how built-in and custom shapes are defined in ChartDirector.

For demonstration, in this example each bar is of a different shape. BarLayer.setBarShape and BarLayer.setBarShape2 also supports setting the bar shapes based on data groups (or data sets) or data item position. For an example, see Multi-Shape Bar Chart.

Source Code Listing

[File: cfdemo/polygonbar.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the bar chart
data = Array(85, 156, 179.5, 211, 123, 176, 195);

// The labels for the bar chart
labels = Array("Square", "Star(8)", "Polygon(6)", "Cross", "Cross2", "Diamond",
    "Custom");

// Create a XYChart object of size 500 x 280 pixels.
c = cd.XYChart(500, 280);

// Set the plotarea at (50, 40) with alternating light grey (f8f8f8) / white (ffffff)
// background
c.setPlotArea(50, 40, 400, 200, "0xf8f8f8", "0xffffff");

// Add a title to the chart using 14 pts Arial Bold Italic font
c.addTitle("    Bar Shape Demonstration", "Arial Bold Italic", 14);

// Add a multi-color bar chart layer
layer = c.addBarLayer3(data);

// Set layer to 3D with 10 pixels 3D depth
layer.set3D(10);

// Set bar shape to circular (cylinder)
layer.setBarShape(cd.CircleShape);

// Set the first bar (index = 0) to square shape
layer.setBarShape(cd.SquareShape, 0, 0);

// Set the second bar to 8-pointed star
layer.setBarShape(cd.StarShape(8), 0, 1);

// Set the third bar to 6-sided polygon
layer.setBarShape(cd.PolygonShape(6), 0, 2);

// Set the next 3 bars to cross shape, X shape and diamond shape
layer.setBarShape(cd.CrossShape(), 0, 3);
layer.setBarShape(cd.Cross2Shape(), 0, 4);
layer.setBarShape(cd.DiamondShape, 0, 5);

// Set the last bar to a custom shape, specified as an array of (x, y) points in
// normalized coordinates
layer.setBarShape2(Array(-500, 0, 0, 500, 500, 0, 500, 1000, 0, 500, -500, 1000), 0,
    6);

// Set the labels on the x axis.
c.xAxis().setLabels(labels);

// Add a title to the y axis
c.yAxis().setTitle("Frequency");

// Add a title to the x axis
c.xAxis().setTitle("Shapes");

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "", "title='{xLabel}: {value}'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Polygon Bar Shapes
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Stacked Bar Chart

Stacked Bar Chart

This example demonstrates creating a stacked bar chart, completed with bar labels and legend box.

The key features demonstrated in this example are:

  • Add a legend to the chart using BaseChart.addLegend.

  • Add a title to the y-axis using Axis.setTitle, and draw the title upright using TextBox.setFontAngle (the default for y-axis is to draw the title rotated by 90 degrees). Note the y-axis title can contain multiple lines by including the line break character.

  • Add a stacked bar layer using XYChart.addBarLayer2 with the Stack predefined constant.

  • Add multiple data sets to the bar layer using Layer.addDataSet.

  • Include labels for the whole bar using Layer.setAggregateLabelStyle.

  • Include labels for the bar segments within a stacked bar using Layer.setDataLabelStyle.
For bar labels, Layer.setDataLabelStyle and Layer.setAggregateLabelStyle control the styles (fonts, colors, backgrounds, etc), while Layer.setDataLabelFormat and Layer.setAggregateLabelFormat control the formats (the contents of the label, number of decimal points in numbers, etc). You may also add custom labels to the bars using Layer.addCustomDataLabel and Layer.addCustomAggregateLabel and Layer.addCustomGroupLabel.

Source Code Listing

[File: cfdemo/stackedbar.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the bar chart
data0 = Array(100, 125, 245, 147, 67);
data1 = Array(85, 156, 179, 211, 123);
data2 = Array(97, 87, 56, 267, 157);

// The labels for the bar chart
labels = Array("Mon", "Tue", "Wed", "Thu", "Fri");

// Create a XYChart object of size 500 x 320 pixels
c = cd.XYChart(500, 320);

// Set the plotarea at (100, 40) and of size 280 x 240 pixels
c.setPlotArea(100, 40, 280, 240);

// Add a legend box at (400, 100)
c.addLegend(400, 100);

// Add a title to the chart using 14 points Times Bold Itatic font
c.addTitle("Weekday Network Load", "Times New Roman Bold Italic", 14);

// Add a title to the y axis. Draw the title upright (font angle = 0)
c.yAxis().setTitle("Average<*br*>Workload<*br*>(MBytes<*br*>Per Hour)").setFontAngle(
    0);

// Set the labels on the x axis
c.xAxis().setLabels(labels);

// Add a stacked bar layer and set the layer 3D depth to 8 pixels
layer = c.addBarLayer2(cd.Stack, 8);

// Add the three data sets to the bar layer
layer.addDataSet(data0, "0xff8080", "Server ## 1");
layer.addDataSet(data1, "0x80ff80", "Server ## 2");
layer.addDataSet(data2, "0x8080ff", "Server ## 3");

// Enable bar label for the whole bar
layer.setAggregateLabelStyle();

// Enable bar label for each segment of the stacked bar
layer.setDataLabelStyle();

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName} on {xLabel}: {value} MBytes/hour'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Stacked Bar Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Percentage Bar Chart

Percentage Bar Chart

This example demonstrates creating a percentage bar chart. It also demonstrates how to include icons in the legend box using CDML.

A percentage bar chart is like a stacked bar chart, except the bars are individually scaled so that they stacked up to 100.

Note that in this example, the legend box contains icons. This is achieved by including the icons in the data set name using CDML.

The key features demonstrated in this example are:

  • Add a legend to the chart using BaseChart.addLegend, and set the key size (the color box to the right of each legend entry) to 16 x 32 pixels using LegendBox.setKeySize. This is to better match the size of the icons.

  • Reverse the legend box entries using Layer.setLegend, so that the last data set name is on top in the legend box. This is useful for a vertical legend box in a vertical stacked chart with purely positive data. In such case, the last data set will be stacked to the top. Reversing the legend box will make the legend keys visually consistent with the stacking order of the chart.

  • Add a percentage bar layer using XYChart.addBarLayer2 with the Percentage predefined constant.

  • Add multiple data sets to the bar layer using Layer.addDataSet, with data set names expressed using CDML to include icons.

  • Include labels for the bar segments using Layer.setDataLabelStyle, with center alignment configured using TextBox.setAlignment.
Note that by default, the data label format is {percent}% (showing the percentage) for a percentage bar layer, as opposed to {value} (showing the data value) for other types of bar layer. The data label format can be modified using Layer.setDataLabelFormat.

Source Code Listing

[File: cfdemo/percentbar.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the bar chart
data0 = Array(100, 125, 245, 147, 67);
data1 = Array(85, 156, 179, 211, 123);
data2 = Array(97, 87, 56, 267, 157);

// The labels for the bar chart
labels = Array("Mon", "Tue", "Wed", "Thu", "Fri");

// Create a XYChart object of size 500 x 280 pixels, using 0xffffcc as background
// color, with a black border, and 1 pixel 3D border effect
c = cd.XYChart(500, 280, "0xffffcc", 0, 1);

// Set search path to current directory for loading icon images
c.setSearchPath(GetPageContext());

// Set the plotarea at (50, 45) and of size 320 x 200 pixels. Use white (0xffffff)
// color as background.
c.setPlotArea(50, 45, 320, 200, "0xffffff");

// Add a legend box at (370, 45) using vertical layout and 8 points Arial Bold font.
legendBox = c.addLegend(370, 45, True, "Arial Bold", 8);

// Set the legend box background and border to transparent
legendBox.setBackground(cd.Transparent, cd.Transparent);

// Set the legend box icon size to 16 x 32 pixels to match with custom icon size
legendBox.setKeySize(16, 32);

// Add a title to the chart using 14 points Times Bold Itatic font and white font
// color, and 0x804020 as the background color
c.addTitle("Weekly Product Sales", "Times New Roman Bold Italic", 14, "0xffffff"
    ).setBackground("0x804020");

// Set the labels on the x axis
c.xAxis().setLabels(labels);

// Add a percentage bar layer and set the layer 3D depth to 8 pixels
layer = c.addBarLayer2(cd.Percentage);

// Add the three data sets to the bar layer, using icons images with labels as data
// set names
layer.addDataSet(data0, "0xddaa77",
    "<*block,valign=absmiddle*><*img=service.png*> Service<*/*>");
layer.addDataSet(data1, "0xaadd77",
    "<*block,valign=absmiddle*><*img=software.png*> Software<*/*>");
layer.addDataSet(data2, "0xaa77dd",
    "<*block,valign=absmiddle*><*img=computer.png*> Hardware<*/*>");

// Disable bar borders by setting their colors to transparent
layer.setBorderColor(cd.Transparent);

// Enable data label at the middle of the the bar
layer.setDataLabelStyle().setAlignment(cd.Center);

// For a vertical stacked chart with positive data only, the last data set is always
// on top. However, in a vertical legend box, the last data set is at the bottom.
// This can be reversed by using the setLegend method.
layer.setLegend(cd.ReverseLegend);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName} revenue on {xLabel}: US${value}K ({percent}%)'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Percentage Bar Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Multi-Bar Chart

Multi-Bar Chart

This example demonstrates a multi-bar chart, in which bars are clustered. It also demonstrates using alternative plot area background colors, and putting legends internal to the plot area.

A multi-bar chart is a bar chart in which multiple data sets are represented by drawing the bars side by side in a cluster. The multi-bar layer is created by using XYChart.addBarLayer2 with the Side predefined constant.

In this example, the two alternative background colors in the plot area is achieved by specifying two background colors in PlotArea.setBackground. ChartDirector also supports another method PlotArea.setAltBgColor that can be used for both horizontal and vertical alternative background colors.

Note that in this example, a margin is configured at the top of the plot area for the legend keys. This is achieved by using Axis.setMargin.

Source Code Listing

[File: cfdemo/multibar.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the bar chart
data0 = Array(100, 125, 245, 147, 67);
data1 = Array(85, 156, 179, 211, 123);
data2 = Array(97, 87, 56, 267, 157);
labels = Array("Mon", "Tue", "Wed", "Thu", "Fri");

// Create a XYChart object of size 400 x 240 pixels
c = cd.XYChart(400, 240);

// Add a title to the chart using 10 pt Arial font
c.addTitle("         Average Weekday Network Load", "", 10);

// Set the plot area at (50, 25) and of size 320 x 180. Use two alternative
// background colors (0xffffc0 and 0xffffe0)
c.setPlotArea(50, 25, 320, 180, "0xffffc0", "0xffffe0");

// Add a legend box at (55, 18) using horizontal layout. Use 8 pt Arial font, with
// transparent background
c.addLegend(55, 18, False, "", 8).setBackground(cd.Transparent);

// Add a title to the y-axis
c.yAxis().setTitle("Throughput (MBytes Per Hour)");

// Reserve 20 pixels at the top of the y-axis for the legend box
c.yAxis().setTopMargin(20);

// Set the x axis labels
c.xAxis().setLabels(labels);

// Add a multi-bar layer with 3 data sets and 3 pixels 3D depth
layer = c.addBarLayer2(cd.Side, 3);
layer.addDataSet(data0, "0xff8080", "Server ##1");
layer.addDataSet(data1, "0x80ff80", "Server ##2");
layer.addDataSet(data2, "0x8080ff", "Server ##3");

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName} on {xLabel}: {value} MBytes/hour'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Multi-Bar Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Soft Multi-Bar Chart

Soft Multi-Bar Chart

This example demonstrates a multi-bar chart with soft lighting effects for bars and gradient color for plot area background.

Soft lighting is a special shading effect that look like gradient coloring. In this example, soft lighting effect is applied to the bars with the light coming from the left direction.

  • The gradient plot area background is configured by using BaseChart.linearGradientColor to define the gradient color, then use XYChart.setPlotArea to apply it to the plot area.

  • The XYChart.setPlotArea also sets the plot area border and grid line colors to white.

  • The soft lighting effect of the bars is defined using ChartDirector.CFChart.softLighting, then applied to the bars using Layer.setBorderColor.
See Soft Bar Shading for another example of soft lighting effect with the light coming from the left direction.

Source Code Listing

[File: cfdemo/softmultibar.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the bar chart
data0 = Array(100, 125, 245, 147, 67);
data1 = Array(85, 156, 179, 211, 123);
data2 = Array(97, 87, 56, 267, 157);
labels = Array("Mon", "Tue", "Wed", "Thur", "Fri");

// Create a XYChart object of size 540 x 375 pixels
c = cd.XYChart(540, 375);

// Add a title to the chart using 18 pts Times Bold Italic font
c.addTitle("Average Weekly Network Load", "Times New Roman Bold Italic", 18);

// Set the plotarea at (50, 55) and of 440 x 280 pixels in size. Use a vertical
// gradient color from light red (ffdddd) to dark red (880000) as background. Set
// border and grid lines to white (ffffff).
c.setPlotArea(50, 55, 440, 280, c.linearGradientColor(0, 55, 0, 335, "0xffdddd",
    "0x880000"), -1, "0xffffff", "0xffffff");

// Add a legend box at (50, 25) using horizontal layout. Use 10pts Arial Bold as
// font, with transparent background.
c.addLegend(50, 25, False, "Arial Bold", 10).setBackground(cd.Transparent);

// Set the x axis labels
c.xAxis().setLabels(labels);

// Draw the ticks between label positions (instead of at label positions)
c.xAxis().setTickOffset(0.5);

// Set axis label style to 8pts Arial Bold
c.xAxis().setLabelStyle("Arial Bold", 8);
c.yAxis().setLabelStyle("Arial Bold", 8);

// Set axis line width to 2 pixels
c.xAxis().setWidth(2);
c.yAxis().setWidth(2);

// Add axis title
c.yAxis().setTitle("Throughput (MBytes Per Hour)");

// Add a multi-bar layer with 3 data sets and 4 pixels 3D depth
layer = c.addBarLayer2(cd.Side, 4);
layer.addDataSet(data0, "0xffff00", "Server ##1");
layer.addDataSet(data1, "0x00ff00", "Server ##2");
layer.addDataSet(data2, "0x9999ff", "Server ##3");

// Set bar border to transparent. Use soft lighting effect with light direction from
// top.
layer.setBorderColor(cd.Transparent, cd.softLighting(cd.Top));

// Configure the bars within a group to touch each others (no gap)
layer.setBarGap(0.2, cd.TouchBar);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName} on {xLabel}: {value} MBytes/hour'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Soft Multi-Bar Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Glass Multi-Bar Chart

Glass Multi-Bar Chart

This example demonstrates a multi-bar chart with glass shading effect for bars and gradient color for plot area background.

Glass lighting is a complex shading effect that gives a look and feel of tinted glass or semi-transparent plastic material. This effect involves glare and variation of lighting caused by reflection and refraction inside the material.

  • The gradient plot area background is configured by using BaseChart.linearGradientColor to define the gradient color, then use XYChart.setPlotArea to apply it to the plot area.

  • The XYChart.setPlotArea also sets the plot area border and grid line colors to white.

  • The glass shading effect of the bars is defined using ChartDirector.CFChart.glassEffect, then applied to the bars using Layer.setBorderColor.

Source Code Listing

[File: cfdemo/glassmultibar.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the bar chart
data0 = Array(100, 125, 245, 147, 67);
data1 = Array(85, 156, 179, 211, 123);
data2 = Array(97, 87, 56, 267, 157);
labels = Array("Mon", "Tue", "Wed", "Thur", "Fri");

// Create a XYChart object of size 540 x 375 pixels
c = cd.XYChart(540, 375);

// Add a title to the chart using 18 pts Times Bold Italic font
c.addTitle("Average Weekly Network Load", "Times New Roman Bold Italic", 18);

// Set the plotarea at (50, 55) and of 440 x 280 pixels in size. Use a vertical
// gradient color from light blue (f9f9ff) to blue (6666ff) as background. Set border
// and grid lines to white (ffffff).
c.setPlotArea(50, 55, 440, 280, c.linearGradientColor(0, 55, 0, 335, "0xf9f9ff",
    "0x6666ff"), -1, "0xffffff", "0xffffff");

// Add a legend box at (50, 28) using horizontal layout. Use 10pts Arial Bold as
// font, with transparent background.
c.addLegend(50, 28, False, "Arial Bold", 10).setBackground(cd.Transparent);

// Set the x axis labels
c.xAxis().setLabels(labels);

// Draw the ticks between label positions (instead of at label positions)
c.xAxis().setTickOffset(0.5);

// Set axis label style to 8pts Arial Bold
c.xAxis().setLabelStyle("Arial Bold", 8);
c.yAxis().setLabelStyle("Arial Bold", 8);

// Set axis line width to 2 pixels
c.xAxis().setWidth(2);
c.yAxis().setWidth(2);

// Add axis title
c.yAxis().setTitle("Throughput (MBytes Per Hour)");

// Add a multi-bar layer with 3 data sets
layer = c.addBarLayer2(cd.Side);
layer.addDataSet(data0, "0xff0000", "Server ##1");
layer.addDataSet(data1, "0x00ff00", "Server ##2");
layer.addDataSet(data2, "0xff8800", "Server ##3");

// Set bar border to transparent. Use glass lighting effect with light direction from
// left.
layer.setBorderColor(cd.Transparent, cd.glassEffect(cd.NormalGlare, cd.Left));

// Configure the bars within a group to touch each others (no gap)
layer.setBarGap(0.2, cd.TouchBar);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName} on {xLabel}: {value} MBytes/hour'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Glass Multi-Bar Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Multi-Cylinder Chart

Multi-Cylinder Chart

This example demonstrates a multi-bar chart with cylinder shading effects. It also demonstrates using dotted line style for grid lines.

The cylinder shading effect is the result of using the cylinder bar shape in 2D. This is by using BarLayer.setBarShape with CircleShape.

The dotted grid lines in this example is configured by using BaseChart.dashLineColor to define the dotted line color, then use it in XYChart.setPlotArea as the the grid line color.

Source Code Listing

[File: cfdemo/multicylinder.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// Data for the chart
data0 = Array(100, 125, 245, 147, 67, 96, 160, 145, 97, 167, 220, 125);
data1 = Array(85, 156, 179, 211, 123, 225, 127, 99, 111, 260, 175, 156);
data2 = Array(97, 87, 56, 267, 157, 157, 67, 156, 77, 87, 197, 87);
labels = Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct",
    "Nov", "Dec");

// Create a XYChart object of size 560 x 280 pixels.
c = cd.XYChart(560, 280);

// Add a title to the chart using 14 pts Arial Bold Italic font
c.addTitle("     Average Weekly Network Load", "Arial Bold Italic", 14);

// Set the plotarea at (50, 50) and of 500 x 200 pixels in size. Use alternating
// light grey (f8f8f8) / white (ffffff) background. Set border to transparent and use
// grey (CCCCCC) dotted lines as horizontal and vertical grid lines
c.setPlotArea(50, 50, 500, 200, "0xffffff", "0xf8f8f8", cd.Transparent,
    c.dashLineColor("0xcccccc", cd.DotLine), c.dashLineColor("0xcccccc", cd.DotLine))
    ;

// Add a legend box at (50, 22) using horizontal layout. Use 10 pt Arial Bold Italic
// font, with transparent background
c.addLegend(50, 22, False, "Arial Bold Italic", 10).setBackground(cd.Transparent);

// Set the x axis labels
c.xAxis().setLabels(labels);

// Draw the ticks between label positions (instead of at label positions)
c.xAxis().setTickOffset(0.5);

// Add axis title
c.yAxis().setTitle("Throughput (MBytes Per Hour)");

// Set axis line width to 2 pixels
c.xAxis().setWidth(2);
c.yAxis().setWidth(2);

// Add a multi-bar layer with 3 data sets
layer = c.addBarLayer2(cd.Side);
layer.addDataSet(data0, "0xff0000", "Server ##1");
layer.addDataSet(data1, "0x00ff00", "Server ##2");
layer.addDataSet(data2, "0x0000ff", "Server ##3");

// Set bar shape to circular (cylinder)
layer.setBarShape(cd.CircleShape);

// Configure the bars within a group to touch each others (no gap)
layer.setBarGap(0.2, cd.TouchBar);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName} on {xLabel}: {value} MBytes/hour'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Multi-Cylinder Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Multi-Shape Bar Chart

Multi-Shape Bar Chart

This example demonstrates a multi-bar chart in which each data set has a different bar shape.

The bar shapes are specified using BarLayer.setBarShape. See Shape Specification on how built-in and custom shapes are defined in ChartDirector.

Source Code Listing

[File: cfdemo/multishapebar.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the bar chart
data0 = Array(100, 125, 245, 147);
data1 = Array(85, 156, 179, 211);
data2 = Array(97, 87, 56, 267);
labels = Array("1st Quarter", "2nd Quarter", "3rd Quarter", "4th Quarter");

// Create a XYChart object of size 600 x 350 pixels
c = cd.XYChart(600, 350);

// Add a title to the chart using 14 pts Arial Bold Italic font
c.addTitle("Annual Product Revenue", "Arial Bold Italic", 14);

// Set the plot area at (50, 60) and of size 500 x 240. Use two alternative
// background colors (f8f8f8 and ffffff)
c.setPlotArea(50, 60, 500, 240, "0xf8f8f8", "0xffffff");

// Add a legend box at (55, 22) using horizontal layout, with transparent background
c.addLegend(55, 22, False).setBackground(cd.Transparent);

// Set the x axis labels
c.xAxis().setLabels(labels);

// Draw the ticks between label positions (instead of at label positions)
c.xAxis().setTickOffset(0.5);

// Add a multi-bar layer with 3 data sets and 9 pixels 3D depth
layer = c.addBarLayer2(cd.Side, 9);
layer.addDataSet(data0, -1, "Product A");
layer.addDataSet(data1, -1, "Product B");
layer.addDataSet(data2, -1, "Product C");

// Set data set 1 to use a bar shape of a 6-pointed star
layer.setBarShape(cd.StarShape(6), 0);

// Set data set 2 to use a bar shapre of a 6-sided polygon
layer.setBarShape(cd.PolygonShape(6), 1);

// Set data set 3 to use an X bar shape
layer.setBarShape(cd.Cross2Shape(), 2);

// Add a title to the y-axis
c.yAxis().setTitle("Revenue (USD in millions)");

// Add a title to the x axis
c.xAxis().setTitle("Year 2005");

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName}: {xLabel} Revenue = {value} millions'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Multi-Shape Bar Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Overlapping Bar Chart

Overlapping Bar Chart

This example demonstrates a multi-bar chart in which the bars within a cluster overlaps.

The overlapping effect is configured using BarLayer.setOverlapRatio. This method allows you to specify overlapping ratio and order. In this example, the overlapping ratio is 0.5, while the default overlapping order is used. The default order is that the first data set will stay on top of the second data set, and so on.

Source Code Listing

[File: cfdemo/overlapbar.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the bar chart
data0 = Array(100, 125, 156, 147, 87, 124, 178, 109, 140, 106, 192, 122);
data1 = Array(122, 156, 179, 211, 198, 177, 160, 220, 190, 188, 220, 270);
data2 = Array(167, 190, 213, 267, 250, 320, 212, 199, 245, 267, 240, 310);
labels = Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct",
    "Nov", "Dec");

// Create a XYChart object of size 580 x 280 pixels
c = cd.XYChart(580, 280);

// Add a title to the chart using 14 pts Arial Bold Italic font
c.addTitle("Product Revenue For Last 3 Years", "Arial Bold Italic", 14);

// Set the plot area at (50, 50) and of size 500 x 200. Use two alternative
// background colors (f8f8f8 and ffffff)
c.setPlotArea(50, 50, 500, 200, "0xf8f8f8", "0xffffff");

// Add a legend box at (50, 25) using horizontal layout. Use 8pts Arial as font, with
// transparent background.
c.addLegend(50, 25, False, "Arial", 8).setBackground(cd.Transparent);

// Set the x axis labels
c.xAxis().setLabels(labels);

// Draw the ticks between label positions (instead of at label positions)
c.xAxis().setTickOffset(0.5);

// Add a multi-bar layer with 3 data sets
layer = c.addBarLayer2(cd.Side);
layer.addDataSet(data0, "0xff8080", "Year 2003");
layer.addDataSet(data1, "0x80ff80", "Year 2004");
layer.addDataSet(data2, "0x8080ff", "Year 2005");

// Set 50% overlap between bars
layer.setOverlapRatio(0.5);

// Add a title to the y-axis
c.yAxis().setTitle("Revenue (USD in millions)");

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='{xLabel} Revenue on {dataSetName}: {value} millions'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Overlapping Bar Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Multi-Stacked Bar Chart

Multi-Stacked Bar Chart

This example demonstrates combining multi-bar style with stacked bar style. It also demonstrates drawing horizontal bar charts, using icons in axis labels with CDML, customizing legend and bar labels, controlling bar widths and centering legend box.

A multi-stacked bar chart combines the multi-bar style with the stacked bar style by allowing each bar in a multi-bar chart to be a stacked bar. This provides two levels of data grouping. The data from the data sets are clusters based on their index position. Within each cluster, the data are grouped again to form stack bars.

The standard multi-bar chart provides the first level of grouping. The Layer.addDataGroup method is used to provide the second level of grouping.

The key features demonstrated in this example are:

  • Use Layer.addDataGroup to start a new data group. All subsequent data sets added to the layer will belong to that group. The group ends when Layer.addDataGroup is called again to start another new group.

  • Embed icons in axis labels by using CDML to encode the labels.

  • Set the bar border to Transparent using Layer.setBorderColor.

  • Set a 20% bar gap between the bar clusters and 0% (no gap) for bars within a bar cluster by using BarLayer.setBarGap.

  • Swap the x and y axes to create a horizontal bar chart using XYChart.swapXY.

  • Reserve 20% space at the right side of the plot area for the bar labels by using Axis.setAutoScale.

  • Customize the aggregate bar labels by using Layer.setAggregateLabelFormat.

  • Customize the legend entries by using TextBox.setText of the LegendBox object.

  • Center the legend box under the plot area by using TextBox.setAlignment of the LegendBox object.

Source Code Listing

[File: cfdemo/multistackbar.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the bar chart
data0 = Array(44, 55, 100);
data1 = Array(97, 87, 167);
data2 = Array(156, 78, 147);
data3 = Array(125, 118, 211);

// The labels for the bar chart. The labels contains embedded images as icons.
labels = Array("<*img=service.png*><*br*>Service",
    "<*img=software.png*><*br*>Software", "<*img=computer.png*><*br*>Hardware");

// Create a XYChart object of size 600 x 350 pixels, using 0xe0e0ff as the background
// color, 0xccccff as the border color, with 1 pixel 3D border effect.
c = cd.XYChart(600, 350, "0xe0e0ff", "0xccccff", 1);

// Set search path to current directory for loading icon images
c.setSearchPath(GetPageContext());

// Add a title to the chart using 14 points Times Bold Itatic font and light blue
// (0x9999ff) as the background color
c.addTitle("Business Results 2001 vs 2002", "Times New Roman Bold Italic", 14
    ).setBackground("0x9999ff");

// Set the plotarea at (60, 45) and of size 500 x 210 pixels, using white (0xffffff)
// as the background
c.setPlotArea(60, 45, 500, 210, "0xffffff");

// Swap the x and y axes to create a horizontal bar chart
c.swapXY();

// Add a title to the y axis using 11 pt Times Bold Italic as font
c.yAxis().setTitle("Revenue (millions)", "Times New Roman Bold Italic", 11);

// Set the labels on the x axis
c.xAxis().setLabels(labels);

// Disable x-axis ticks by setting the tick length to 0
c.xAxis().setTickLength(0);

// Add a stacked bar layer to the chart
layer = c.addBarLayer2(cd.Stack);

// Add the first two data sets to the chart as a stacked bar group
layer.addDataGroup("2001");
layer.addDataSet(data0, "0xaaaaff", "Local");
layer.addDataSet(data1, "0x6666ff", "International");

// Add the remaining data sets to the chart as another stacked bar group
layer.addDataGroup("2002");
layer.addDataSet(data2, "0xffaaaa", "Local");
layer.addDataSet(data3, "0xff6666", "International");

// Set the sub-bar gap to 0, so there is no gap between stacked bars with a group
layer.setBarGap(0.2, 0);

// Set the bar border to transparent
layer.setBorderColor(cd.Transparent);

// Set the aggregate label format
layer.setAggregateLabelFormat("Year {dataGroupName}<*br*>{value} millions");

// Set the aggregate label font to 8 point Arial Bold Italic
layer.setAggregateLabelStyle("Arial Bold Italic", 8);

// Reverse 20% space at the right during auto-scaling to allow space for the
// aggregate bar labels
c.yAxis().setAutoScale(0.2);

// Add a legend box at (310, 300) using TopCenter alignment, with 2 column grid
// layout, and use 8 pts Arial Bold Italic as font
legendBox = c.addLegend2(310, 300, 2, "Arial Bold Italic", 8);
legendBox.setAlignment(cd.TopCenter);

// Set the format of the text displayed in the legend box
legendBox.setText("Year {dataGroupName} {dataSetName} Revenue");

// Set the background and border of the legend box to transparent
legendBox.setBackground(cd.Transparent, cd.Transparent);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='Year {dataGroupName} {dataSetName} {xLabel} Revenue: {value} millions'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Multi-Stacked Bar Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Depth Bar Chart

Depth Bar Chart

This example demonstrates using multiple bar layers with semi-transparent colors to create a depth bar chart.

ChartDirector allows an XYChart to containing multiple layers of the same or different types. In this example, all layers are 3D bar layers. The bars are drawn in semi-transparent colors to avoid the bars on the front hiding the bars at the back.

Source Code Listing

[File: cfdemo/depthbar.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the bar chart
data0 = Array(100, 125, 245, 147, 67);
data1 = Array(85, 156, 179, 211, 123);
data2 = Array(97, 87, 56, 267, 157);

// The labels for the bar chart
labels = Array("Mon", "Tue", "Wed", "Thu", "Fri");

// Create a XYChart object of size 500 x 320 pixels
c = cd.XYChart(500, 320);

// Set the plotarea at (100, 40) and of size 280 x 240 pixels
c.setPlotArea(100, 40, 280, 240);

// Add a legend box at (405, 100)
c.addLegend(405, 100);

// Add a title to the chart
c.addTitle("Weekday Network Load");

// Add a title to the y axis. Draw the title upright (font angle = 0)
c.yAxis().setTitle("Average<*br*>Workload<*br*>(MBytes<*br*>Per Hour)").setFontAngle(
    0);

// Set the labels on the x axis
c.xAxis().setLabels(labels);

// Add three bar layers, each representing one data set. The bars are drawn in
// semi-transparent colors.
c.addBarLayer(data0, "0x808080ff", "Server ## 1", 5);
c.addBarLayer(data1, "0x80ff0000", "Server ## 2", 5);
c.addBarLayer(data2, "0x8000ff00", "Server ## 3", 5);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName} on {xLabel}: {value} MBytes/hour'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Depth Bar Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Positive Negative Bars

Positive Negative Bars

This example demonstrates a bar chart containing positive and negative data, represented by different colors.

In this example, the two colors of the plot area background are configured using background zones, while the bar colors are configured by splitting the bars into two layers.

  • Use XYChart.addBarLayer2 with Overlay to add an overlay bar layer to the chart.

  • Use ArrayMath.selectGEZ to select the data values greater than or equal to zero and use Layer.addDataSet to add them as the blue data set.

  • Use ArrayMath.selectLTZ to select the data values less than zero and use Layer.addDataSet to add them as the orange data set.

  • Use Layer.yZoneColor to create a y-zone color, which is blue for y >= 0 and orange for y < 0, and use Layer.setAggregateLabelStyle to apply it as the bar label color.

  • Use Axis.addZone to add two background zones for y >= 0 and y < 0.

Source Code Listing

[File: cfdemo/posnegbar.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the bar chart
data = Array(-6.3, 2.3, 0.7, -3.4, 2.2, -2.9, -0.1, -0.1, 3.3, 6.2, 4.3, 1.6);

// The labels for the bar chart
labels = Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct",
    "Nov", "Dec");

// Create a XYChart object of size 500 x 320 pixels
c = cd.XYChart(500, 320);

// Add a title to the chart using Arial Bold Italic font
c.addTitle("Productivity Change - Year 2005", "Arial Bold Italic");

// Set the plotarea at (50, 30) and of size 400 x 250 pixels
c.setPlotArea(50, 30, 400, 250);

// Add a bar layer to the chart using the Overlay data combine method
layer = c.addBarLayer2(cd.Overlay);

// Select positive data and add it as data set with blue (6666ff) color
layer.addDataSet(cd.ArrayMath(data).selectGEZ(Array(), cd.NoValue).result(),
    "0x6666ff");

// Select negative data and add it as data set with orange (ff6600) color
layer.addDataSet(cd.ArrayMath(data).selectLTZ(Array(), cd.NoValue).result(),
    "0xff6600");

// Add labels to the top of the bar using 8 pt Arial Bold font. The font color is
// configured to be red (0xcc3300) below zero, and blue (0x3333ff) above zero.
layer.setAggregateLabelStyle("Arial Bold", 8, layer.yZoneColor(0, "0xcc3300",
    "0x3333ff"));

// Set the labels on the x axis and use Arial Bold as the label font
c.xAxis().setLabels(labels).setFontStyle("Arial Bold");

// Draw the y axis on the right of the plot area
c.setYAxisOnRight(True);

// Use Arial Bold as the y axis label font
c.yAxis().setLabelStyle("Arial Bold");

// Add a title to the y axis
c.yAxis().setTitle("Percentage");

// Add a light blue (0xccccff) zone for positive part of the plot area
c.yAxis().addZone(0, 9999, "0xccccff");

// Add a pink (0xffffcc) zone for negative part of the plot area
c.yAxis().addZone(-9999, 0, "0xffcccc");

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "", "title='{xLabel}: {value}%'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Positive Negative Bars
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Borderless Bar Chart

Borderless Bar Chart

This example demonstrates a horizontal bar chart with no axes, grid lines or and plot area border. It also demonstrates using gradient colors for the bars, and a number of other ChartDirector features.

The key features demonstrated in this example are:

  • Swap the x and y axes to create a horizontal bar chart using XYChart.swapXY.

  • Create a gradient color that changes smoothly from dark green to white along a horizontal direction using BaseChart.gradientColor, then use it as the bar color in XYChart.addBarLayer.

  • Set the plot area background, border and grid line colors to Transparent using XYChart.setPlotArea.

  • Set the x-axis, y-axis and y-axis labels to Transparent using Axis.setColors.

  • Set the x-axis font style to deep red 10 points Arial Bold Italic by using the TextBox.setFontStyle and TextBox.setFontColor of the TextBox object that represents the x-axis label prototype (obtained using Axis.setLabels).

  • Set the aggregate bar label style to deep red 10 points Times Bold Italic using Layer.setAggregateLabelStyle.

  • Customize the aggregate bar labels by using Layer.setAggregateLabelFormat.

Source Code Listing

[File: cfdemo/hbar.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the bar chart
data = Array(3.9, 8.1, 10.9, 14.2, 18.1, 19.0, 21.2, 23.2, 25.7, 36);

// The labels for the bar chart
labels = Array("Bastic Group", "Simpa", "YG Super", "CID", "Giga Tech",
    "Indo Digital", "Supreme", "Electech", "THP Thunder", "Flash Light");

// Create a XYChart object of size 600 x 250 pixels
c = cd.XYChart(600, 250);

// Add a title to the chart using Arial Bold Italic font
c.addTitle("Revenue Estimation - Year 2002", "Arial Bold Italic");

// Set the plotarea at (100, 30) and of size 400 x 200 pixels. Set the plotarea
// border, background and grid lines to Transparent
c.setPlotArea(100, 30, 400, 200, cd.Transparent, cd.Transparent, cd.Transparent,
    cd.Transparent, cd.Transparent);

// Add a bar chart layer using the given data. Use a gradient color for the bars,
// where the gradient is from dark green (0x008000) to white (0xffffff)
layer = c.addBarLayer(data, c.gradientColor(100, 0, 500, 0, "0x008000", "0xffffff"));

// Swap the axis so that the bars are drawn horizontally
c.swapXY(True);

// Set the bar gap to 10%
layer.setBarGap(0.1);

// Use the format "US$ xxx millions" as the bar label
layer.setAggregateLabelFormat("US$ {value} millions");

// Set the bar label font to 10 pts Times Bold Italic/dark red (0x663300)
layer.setAggregateLabelStyle("Times New Roman Bold Italic", 10, "0x663300");

// Set the labels on the x axis
textbox = c.xAxis().setLabels(labels);

// Set the x axis label font to 10pt Arial Bold Italic
textbox.setFontStyle("Arial Bold Italic");
textbox.setFontSize(10);

// Set the x axis to Transparent, with labels in dark red (0x663300)
c.xAxis().setColors(cd.Transparent, "0x663300");

// Set the y axis and labels to Transparent
c.yAxis().setColors(cd.Transparent, cd.Transparent);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "", "title='{xLabel}: US${value} millions'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Borderless Bar Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Dual Horizontal Bar Charts

Dual Horizontal Bar Charts

This example demonstrates combining two horizontal bar charts of opposite direction using a MultiChart, and a number of other ChartDirector features.

  • The bar charts are created as XYChart objects with Transparent backgrounds. This ensures they will not block each others when put into the MultiChart.

  • The bars are configured with 3D border effects using Layer.setBorderColor.

  • The bars are configured with to touch each others (no gap in between) by using BarLayer.setBarGap with the TouchBar predefined constant.

  • Custom Male/Female labels are added to the internal corners of the plot areas as custom texts, using BaseChart.addText.

  • Both male and female data are added to both bar charts. This technique ensures the same y-axis scale on both charts. (This example uses auto-scaling, so if the charts containing different data, the axis scales can be different.) On the right chart, the male data is configured to be Transparent, so only the female data can be seen. The opposite is done for the left chart.

  • The left bar chart is configured to use a reversed y-axis (horizontal axis) that points from right to left. This is by using Axis.setReverse.

  • The axis labels between the bar charts belong to the right chart. They are configured to have a width equal to the gap between the charts, with Center alignment. This is by using the TextBox object that represents the prototype of the axis labels, obtained during Axis.setLabels.

  • A MultiChart object is created, and the two bar charts are added to it using MultiChart.addChart. The titles at the top and bottom of the chart belong to the MultiChart, created using BaseChart.addTitle and BaseChart.addTitle2.

Source Code Listing

[File: cfdemo/dualhbar.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The age groups
labels = Array("0 - 4", "5 - 9", "10 - 14", "15 - 19", "20 - 24", "24 - 29",
    "30 - 34", "35 - 39", "40 - 44", "44 - 49", "50 - 54", "55 - 59", "60 - 64",
    "65 - 69", "70 - 74", "75 - 79", "80+");

// The male population (in thousands)
male = Array(215, 238, 225, 236, 235, 260, 286, 340, 363, 305, 259, 164, 135, 127,
    102, 68, 66);

// The female population (in thousands)
female = Array(194, 203, 201, 220, 228, 271, 339, 401, 384, 304, 236, 137, 116, 122,
    112, 85, 110);

//=============================================================
//    Draw the right bar chart
//=============================================================

// Create a XYChart object of size 320 x 300 pixels
c = cd.XYChart(320, 300);

// Set the plotarea at (50, 0) and of size 250 x 255 pixels. Use pink (0xffdddd) as
// the background.
c.setPlotArea(50, 0, 250, 255, "0xffdddd");

// Add a custom text label at the top right corner of the right bar chart
c.addText(300, 0, "Female", "Times New Roman Bold Italic", 12, "0xa07070"
    ).setAlignment(cd.TopRight);

// Add the pink (0xf0c0c0) bar chart layer using the female data
femaleLayer = c.addBarLayer(female, "0xf0c0c0", "Female");

// Swap the axis so that the bars are drawn horizontally
c.swapXY(True);

// Set the bar to touch each others
femaleLayer.setBarGap(cd.TouchBar);

// Set the border style of the bars to 1 pixel 3D border
femaleLayer.setBorderColor(-1, 1);

// Add a Transparent line layer to the chart using the male data. As it is
// Transparent, only the female bar chart can be seen. We need to put both male and
// female data in both left and right charts, because we want auto-scaling to produce
// the same scale for both chart.
c.addLineLayer(male, cd.Transparent);

// Set the y axis label font to Arial Bold
c.yAxis().setLabelStyle("Arial Bold");

// Set the labels between the two bar charts, which can be considered as the x-axis
// labels for the right chart
tb = c.xAxis().setLabels(labels);

// Use a fix width of 50 for the labels (height = automatic) with center alignment
tb.setSize(50, 0);
tb.setAlignment(cd.Center);

// Set the label font to Arial Bold
tb.setFontStyle("Arial Bold");

// Disable ticks on the x-axis by setting the tick length to 0
c.xAxis().setTickLength(0);

//=============================================================
//    Draw the left bar chart
//=============================================================

// Create a XYChart object of size 280 x 300 pixels with a transparent background.
c2 = cd.XYChart(280, 300, cd.Transparent);

// Set the plotarea at (20, 0) and of size 250 x 255 pixels. Use pale blue (0xddddff)
// as the background.
c2.setPlotArea(20, 0, 250, 255, "0xddddff");

// Add a custom text label at the top left corner of the left bar chart
c2.addText(20, 0, "Male", "Times New Roman Bold Italic", 12, "0x7070a0");

// Add the pale blue (0xaaaaff) bar chart layer using the male data
maleLayer = c2.addBarLayer(male, "0xaaaaff", "Male");

// Swap the axis so that the bars are drawn horizontally
c2.swapXY(True);

// Reverse the direction of the y-axis so it runs from right to left
c2.yAxis().setReverse();

// Set the bar to touch each others
maleLayer.setBarGap(cd.TouchBar);

// Set the border style of the bars to 1 pixel 3D border
maleLayer.setBorderColor(-1, 1);

// Add a Transparent line layer to the chart using the female data. As it is
// Transparent, only the male bar chart can be seen. We need to put both male and
// female data in both left and right charts, because we want auto-scaling to produce
// the same scale for both chart.
c2.addLineLayer(female, cd.Transparent);

// Set the y axis label font to Arial Bold
c2.yAxis().setLabelStyle("Arial Bold");

// Set the x-axis labels for tool tip purposes.
c2.xAxis().setLabels(labels);

// Hide the x-axis labels by setting them to Transparent. We only need to display the
// x-axis labels for the right chart.
c2.xAxis().setColors("0x000000", cd.Transparent, -1, cd.Transparent);

//=============================================================
//    Use a MultiChart to contain both bar charts
//=============================================================

// Create a MultiChart object of size 590 x 320 pixels.
m = cd.MultiChart(590, 320);

// Add a title to the chart using Arial Bold Italic font
m.addTitle("Demographics Hong Kong Year 2002", "Arial Bold Italic");

// Add another title at the bottom using Arial Bold Italic font
m.addTitle2(cd.Bottom, "Population (in thousands)", "Arial Bold Italic", 10);

// Put the right chart at (270, 25)
m.addChart(270, 25, c);

// Put the left chart at (0, 25)
m.addChart(0, 25, c2);

// Output the chart
chart1URL = m.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = m.getHTMLImageMap("", "",
    "title='{dataSetName} (Age {xLabel}): Population {value}K'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Dual Horizontal Bar Charts
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Pareto Chart

Pareto Chart

This example demonstrates the pareto chart style.

A pareto chart is a bar chart with the data sorted in descending order, together with a line chart showing the same data in accumulated form. In the current example, the data is shown as both percentages and values on the two y-axes.

The chart in this example is composed of two layers - a BarLayer created using XYChart.addBarLayer, and a LineLayer created using XYChart.addLineLayer.

This example employs the ArrayMath utility class for computing the accumulated line, obtaining the scaling factor between the two y-axes, and re-scaling the line data as percentages.

The two y-axes are synchronized using XYChart.syncYAxis.

Source Code Listing

[File: cfdemo/pareto.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the chart
data = Array(40, 15, 7, 5, 2);

// The labels for the chart
labels = Array("Hard Disk", "PCB", "Printer", "CDROM", "Keyboard");

// Create a XYChart object of size 400 x 225 pixels. Use golden background color,
// with a 2 pixel 3D border.
c = cd.XYChart(400, 225, cd.goldColor(), -1, 2);

// Add a title box using Arial Bold/11 pt font. Set the background color to metallic
// blue (9999FF). Use a 1 pixel 3D border.
c.addTitle("Hardware Defects", "Arial Bold", 11).setBackground(cd.metalColor(
    "0x9999ff"), -1, 1);

// Set the plotarea at (50, 40) and of 300 x 150 pixels in size, with a silver
// background color.
c.setPlotArea(50, 40, 300, 150, cd.silverColor());

// Add a line layer for the pareto line
lineLayer = c.addLineLayer();

// Compute the pareto line by accumulating the data
lineData = cd.ArrayMath(data);
lineData.acc();

// Set a scaling factor such as the maximum point of the line is scaled to 100
scaleFactor = 100 / lineData.max();

// Add the pareto line using the scaled data. Use deep blue (0x80) as the line color,
// with light blue (0x9999ff) diamond symbols
lineLayer.addDataSet(lineData.mul2(scaleFactor).result(), "0x000080").setDataSymbol(
    cd.DiamondSymbol, 9, "0x9999ff");

// Set the line width to 2 pixel
lineLayer.setLineWidth(2);

// Tool tip for the line layer
lineLayer.setHTMLImageMap("", "", "title='Top {={x}+1} items: {value|2}%'");

// Add a multi-color bar layer using the given data.
barLayer = c.addBarLayer3(data);

// Bind the layer to the secondary (right) y-axis.
barLayer.setUseYAxis2();

// Set soft lighting for the bars with light direction from the right
barLayer.setBorderColor(cd.Transparent, cd.softLighting(cd.Right));

// Tool tip for the bar layer
barLayer.setHTMLImageMap("", "", "title='{xLabel}: {value} pieces'");

// Set the labels on the x axis.
c.xAxis().setLabels(labels);

// Set the primary y-axis scale as 0 - 100 with a tick every 20 units
c.yAxis().setLinearScale(0, 100, 20);

// Set the label format of the y-axis label to include a percentage sign
c.yAxis().setLabelFormat("{value}%");

// Add a title to the secondary y-axis
c.yAxis2().setTitle("Frequency");

// Set the secondary y-axis label foramt to show no decimal point
c.yAxis2().setLabelFormat("{value|0}");

// Set the relationship between the two y-axes, which only differ by a scaling factor
c.syncYAxis(1 / scaleFactor);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Pareto Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Bar Gap

Bar Gap

This example demonstrates the effects of different bar gaps configured using BarLayer.setBarGap.

Source Code Listing

[File: cfdemo/gapbar.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// Function to create the demo charts
function createChart(img)
{
    // Declare local variables
    var bargap = 0;
    var data = 0;
    var labels = 0;
    var c = 0;
    var ret = 0;

    bargap = Int(img) * 0.25 - 0.25;

    // The data for the bar chart
    data = Array(100, 125, 245, 147, 67);

    // The labels for the bar chart
    labels = Array("Mon", "Tue", "Wed", "Thu", "Fri");

    // Create a XYChart object of size 150 x 150 pixels
    c = cd.XYChart(150, 150);

    // Set the plotarea at (27, 20) and of size 120 x 100 pixels
    c.setPlotArea(27, 20, 120, 100);

    // Set the labels on the x axis
    c.xAxis().setLabels(labels);

    if (bargap GTE 0) {
        // Add a title to display to bar gap using 8 pts Arial font
        c.addTitle("      Bar Gap = " & bargap, "Arial", 8);
    } else {
        // Use negative value to mean TouchBar
        c.addTitle("      Bar Gap = TouchBar", "Arial", 8);
        bargap = cd.TouchBar;
    }

    // Add a bar chart layer using the given data and set the bar gap
    c.addBarLayer(data).setBarGap(bargap);

    // Output the chart
    ret = StructNew();
    ret.imageURL = c.makeSession(GetPageContext(), "chart" & img);

    // Include tool tip for the chart
    ret.imageMap = c.getHTMLImageMap("", "",
        "title='Production on {xLabel}: {value} kg'");

    return ret;
}

chart0 = createChart(0);
chart1 = createChart(1);
chart2 = createChart(2);
chart3 = createChart(3);
chart4 = createChart(4);
chart5 = createChart(5);

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Bar Gap
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart0.imageURL#" usemap="##map0" border="0" />
<map name="map0">#chart0.imageMap#</map>
<img src="getchart.cfm?#chart1.imageURL#" usemap="##map1" border="0" />
<map name="map1">#chart1.imageMap#</map>
<img src="getchart.cfm?#chart2.imageURL#" usemap="##map2" border="0" />
<map name="map2">#chart2.imageMap#</map>
<img src="getchart.cfm?#chart3.imageURL#" usemap="##map3" border="0" />
<map name="map3">#chart3.imageMap#</map>
<img src="getchart.cfm?#chart4.imageURL#" usemap="##map4" border="0" />
<map name="map4">#chart4.imageMap#</map>
<img src="getchart.cfm?#chart5.imageURL#" usemap="##map5" border="0" />
<map name="map5">#chart5.imageMap#</map>
</cfoutput>
</body>
</html>


Line Charts

Line Charts

Title | Description
Simple Line Chart | Demonstrates the basic steps in creating line charts.
Compact Line Chart | Extends the Simple Line Chart example by decorating the chart using a number of chart formatting features.
3D Line Chart | Demonstrates setting the line to 3D by using Layer.set3D.
Multi-Line Chart | Demonstrates a chart with multiple lines of different styles. Also demonstrates using frame with rounded corners, title with glass shading effect, both vertical and horizontal grid lines, and a legend at the top of the plot area.
Symbol Line Chart | Demonstrates using symbols to represent data points, and putting data labels on top of the symbols.
Symbol Line Chart (2) | Demonstrates using symbols to represent data points and using gradient color for plot area background.
Spline Line Chart | Demonstrates using spline curves to join data points, title with soft lighting effect, as well as a number of chart formatting techniques.
Step Line Chart | Demonstrates joining data points with steps. Also demonstrates irregularly spaced data points on an auto-scaled true date/time axis.
Line Comparison | Demonstrates filling the area between two lines or curves, as well as a number of advanced chart formatting techniques.
Line with Error Symbols | Demonstrates combining a line layer with a box-whisker layer to draw a line with error symbols.
Multi-Symbol Line Chart | Demonstrates a line with different symbols for different data points. Also demonstrates irregularly spaced data points on an auto-scaled true date/time axis.
Custom Symbols | Demonstrates loading external image files as data symbols by using DataSet.setDataSymbol2.
Rotated Line Chart | Demonstrates swapping the x and y axes to produce a rotated line chart in which the line goes from top to bottom (instead of left to right).
Arbitrary XY Line Chart | Demonstrates drawing a line chart with arbitrary x coordinates (not increasing or decreasing in one direction), and adding custom data labels to data points.
Discontinuous Lines | Demonstrates using NoValue to represent lines with missing data points. Also demonstrates vertical zones and custom text boxes.


Simple Line Chart

Simple Line Chart

This example demonstrates the basic steps in creating line charts.

  • Create an XYChart object using XYChart.XYChart.

  • Specify the plot area of the chart using XYChart.setPlotArea. The plot area is the rectangle bounded by the x and y axes. You should leave some margin on the outside of the plot area for axis labels, chart titles, etc.

  • Specify the labels on the x-axis using Axis.setLabels.

  • A line chart may contain many points and therefore many x-axis labels. In this example, Axis.setLabelStep is used to specify showing only a subset of the labels on the x-axis to avoid over-crowding.

  • Add a line layer and specify the data for the line using XYChart.addLineLayer.

  • Generate the chart using BaseChart.makeSession.

  • Generate tool tips for the chart using BaseChart.getHTMLImageMap.

Source Code Listing

[File: cfdemo/simpleline.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the line chart
data = Array(30, 28, 40, 55, 75, 68, 54, 60, 50, 62, 75, 65, 75, 91, 60, 55, 53, 35,
    50, 66, 56, 48, 52, 65, 62);

// The labels for the line chart
labels = Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12",
    "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24");

// Create a XYChart object of size 250 x 250 pixels
c = cd.XYChart(250, 250);

// Set the plotarea at (30, 20) and of size 200 x 200 pixels
c.setPlotArea(30, 20, 200, 200);

// Add a line chart layer using the given data
c.addLineLayer(data);

// Set the labels on the x axis.
c.xAxis().setLabels(labels);

// Display 1 out of 3 labels on the x-axis.
c.xAxis().setLabelStep(3);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "", "title='Hour {xLabel}: Traffic {value} GBytes'"
    );

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Simple Line Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Compact Line Chart

Compact Line Chart

This example extends the Simple Line Chart example by decorating the chart using a number of chart formatting features.

In this example, random data is used. They are generated using a ChartDirector utility class RanTable. RanTable simulates a database table with the cells filled with random numbers. The columns of the table can be retrieved as arrays using RanTable.getCol.

  • Create an XYChart object with background color using XYChart.XYChart.

  • Add title boxes on top and bottom using BaseChart.addTitle and BaseChart.addTitle2.

  • Set the background color of the plot area using PlotArea.setBackground.

  • Add custom text at the top right corner of the plot area using BaseChart.addText.

  • Distribute the text labels on the x-axis evenly using Axis.setLinearScale

  • Set the label fonts on the axes using Axis.setLabelStyle.

Source Code Listing

[File: cfdemo/compactline.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

//
//    We use a random number generator to simulate the data from 9:30am to 4:30pm
//    with one data point every 4 minutes. The total number of points during that
//    period is 106.  (7 hours x 15 points/hour + 1)
//
noOfPoints = 106;

// Assume we have not reached the end of the day yet, and only 85 points are
// available. Create a random table object of 1 col x 85 rows, using 9 as seed.
rantable = cd.RanTable(9, 1, 85);

// Set the 1st column to start with 1800 and with random delta from -5 to 5.
rantable.setCol(0, 1800, -5, 5);

// Get the data as the 1st column of the random table
data = rantable.getCol(0);

// The x-axis labels for the chart
labels = Array("-", "10am", "-", " ", "-", "12am", "-", " ", "-", "2pm", "-", " ",
    "-", "4pm", "-");

//
//    Now we obtain the data into arrays, we can start to draw the chart using
//    ChartDirector
//

// Create a XYChart object of size 180 x 180 pixels with a blue background (0x9c9cce)
c = cd.XYChart(180, 180, "0x9c9cce");

// Add titles to the top and bottom of the chart using 7.5pt Arial font. The text is
// white 0xffffff on a deep blue 0x31319C background.
c.addTitle2(cd.Top, "STAR TECH INDEX  2003-01-28", "Arial", 7.5, "0xffffff",
    "0x31319c");
c.addTitle2(cd.Bottom, "LATEST  STI:1809.41 (+14.51)", "Arial", 7.5, "0xffffff",
    "0x31319c");

// Set the plotarea at (31, 21) and of size 145 x 124 pixels, with a pale yellow
// (0xffffc8) background.
c.setPlotArea(31, 21, 145, 124, "0xffffc8");

// Add custom text at (176, 21) (top right corner of plotarea) using 11pt Times Bold
// Italic font/red (0xc09090) color
c.addText(176, 21, "Chart Demo", "Times New Roman Bold Italic", 11, "0xc09090"
    ).setAlignment(cd.TopRight);

// Use 7.5 pts Arial as the y axis label font
c.yAxis().setLabelStyle("", 7.5);

// Set the labels on the x axis by spreading the labels evenly between the first
// point (index = 0) and the last point (index = noOfPoints - 1)
c.xAxis().setLinearScale(0, noOfPoints - 1, labels);

// Use 7.5 pts Arial as the x axis label font
c.xAxis().setLabelStyle("", 7.5);

// Add a deep blue (0x000080) line layer to the chart
c.addLineLayer(data, "0x000080");

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart. The chart starts at 9:30am and each point spans
// 240 seconds, so we can compute the time as {x}*240+9.5*3600.
imageMap1 = c.getHTMLImageMap("", "", "title='{={x}*240+9.5*3600|h:nna}: {value|2}'")
    ;

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Compact Line Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


3D Line Chart

3D Line Chart

This example demonstrates setting the line to 3D by using Layer.set3D.

Source Code Listing

[File: cfdemo/threedline.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the line chart
data = Array(30, 28, 40, 55, 75, 68, 54, 60, 50, 62, 75, 65, 75, 91, 60, 55, 53, 35,
    50, 66, 56, 48, 52, 65, 62);

// The labels for the line chart
labels = Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12",
    "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24");

// Create a XYChart object of size 300 x 280 pixels
c = cd.XYChart(300, 280);

// Set the plotarea at (45, 30) and of size 200 x 200 pixels
c.setPlotArea(45, 30, 200, 200);

// Add a title to the chart using 12 pts Arial Bold Italic font
c.addTitle("Daily Server Utilization", "Arial Bold Italic", 12);

// Add a title to the y axis
c.yAxis().setTitle("MBytes");

// Add a title to the x axis
c.xAxis().setTitle("June 12, 2001");

// Add a blue (0x6666ff) 3D line chart layer using the give data
c.addLineLayer(data, "0x6666ff").set3D();

// Set the labels on the x axis.
c.xAxis().setLabels(labels);

// Display 1 out of 3 labels on the x-axis.
c.xAxis().setLabelStep(3);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "", "title='Hour {xLabel}: {value} MBytes'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    3D Line Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Multi-Line Chart

Multi-Line Chart

This example demonstrates a chart with multiple lines of different styles. It also demonstrates using frame with rounded corners, title with glass shading effect, both vertical and horizontal grid lines, and a legend at the top of the plot area.

  • The rounded frame is configured using BaseChart.setRoundedFrame.

  • The glass shading effect of the title is defined using ChartDirector.CFChart.glassEffect, then applied to the title using Box.setBackground of the title TextBox object.

  • Enable both vertical and horizontal grid lines using XYChart.setPlotArea.

  • Add a legend at the top of the chart using BaseChart.addLegend.

  • Add an empty line layer using XYChart.addLineLayer2

  • Add multiple data sets to the line layer using Layer.addDataSet.

  • For the last line, the line color is a dash line color creating using BaseChart.dashLineColor.

  • Set the line width for all lines in the layer using Layer.setLineWidth. (To set the line width for one particular line, use DataSet.setLineWidth.)

Source Code Listing

[File: cfdemo/multiline.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the line chart
data0 = Array(42, 49, 33, 38, 51, 46, 29, 41, 44, 57, 59, 52, 37, 34, 51, 56, 56, 60,
    70, 76, 63, 67, 75, 64, 51);
data1 = Array(50, 55, 47, 34, 42, 49, 63, 62, 73, 59, 56, 50, 64, 60, 67, 67, 58, 59,
    73, 77, 84, 82, 80, 84, 98);
data2 = Array(36, 28, 25, 33, 38, 20, 22, 30, 25, 33, 30, 24, 28, 15, 21, 26, 46, 42,
    48, 45, 43, 52, 64, 60, 70);

// The labels for the line chart
labels = Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12",
    "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24");

// Create an XYChart object of size 600 x 300 pixels, with a light blue (EEEEFF)
// background, black border, 1 pxiel 3D border effect and rounded corners
c = cd.XYChart(600, 300, "0xeeeeff", "0x000000", 1);
c.setRoundedFrame();

// Set the plotarea at (55, 58) and of size 520 x 195 pixels, with white background.
// Turn on both horizontal and vertical grid lines with light grey color (0xcccccc)
c.setPlotArea(55, 58, 520, 195, "0xffffff", -1, -1, "0xcccccc", "0xcccccc");

// Add a legend box at (50, 30) (top of the chart) with horizontal layout. Use 9 pts
// Arial Bold font. Set the background and border color to Transparent.
c.addLegend(50, 30, False, "Arial Bold", 9).setBackground(cd.Transparent);

// Add a title box to the chart using 15 pts Times Bold Italic font, on a light blue
// (CCCCFF) background with glass effect. white (0xffffff) on a dark red (0x800000)
// background, with a 1 pixel 3D border.
c.addTitle("Application Server Throughput", "Times New Roman Bold Italic", 15
    ).setBackground("0xccccff", "0x000000", cd.glassEffect());

// Add a title to the y axis
c.yAxis().setTitle("MBytes per hour");

// Set the labels on the x axis.
c.xAxis().setLabels(labels);

// Display 1 out of 3 labels on the x-axis.
c.xAxis().setLabelStep(3);

// Add a title to the x axis
c.xAxis().setTitle("Jun 12, 2006");

// Add a line layer to the chart
layer = c.addLineLayer2();

// Set the default line width to 2 pixels
layer.setLineWidth(2);

// Add the three data sets to the line layer. For demo purpose, we use a dash line
// color for the last line
layer.addDataSet(data0, "0xff0000", "Server ##1");
layer.addDataSet(data1, "0x008800", "Server ##2");
layer.addDataSet(data2, c.dashLineColor("0x3333ff", cd.DashLine), "Server ##3");

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='[{dataSetName}] Hour {xLabel}: {value} MBytes'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Multi-Line Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Symbol Line Chart

Symbol Line Chart

This example demonstrates using symbols to represent data points, and putting data labels on top of the symbols.

Note that in this example, the chart title background is not a solid color but a 1 x 2 pixels pattern.

  • Set background color and 3D border for the chart using XYChart.XYChart.

  • Enable both vertical and horizontal grid lines using XYChart.setPlotArea.

  • Create a pattern color with a 1 x 2 pixel in-memory pattern using BaseChart.patternColor. Set it as the background color of the title box using Box.setBackground.

  • Enable symbols for the data points using DataSet.setDataSymbol.

  • Add labels on top of the symbols using Layer.setDataLabelFormat.

Source Code Listing

[File: cfdemo/symbolline.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the line chart
data0 = Array(60.2, 51.7, 81.3, 48.6, 56.2, 68.9, 52.8);
data1 = Array(30.0, 32.7, 33.9, 29.5, 32.2, 28.4, 29.8);
labels = Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");

// Create a XYChart object of size 300 x 180 pixels, with a pale yellow (0xffffc0)
// background, a black border, and 1 pixel 3D border effect.
c = cd.XYChart(300, 180, "0xffffc0", "0x000000", 1);

// Set the plotarea at (45, 35) and of size 240 x 120 pixels, with white background.
// Turn on both horizontal and vertical grid lines with light grey color (0xc0c0c0)
c.setPlotArea(45, 35, 240, 120, "0xffffff", -1, -1, "0xc0c0c0", -1);

// Add a legend box at (45, 12) (top of the chart) using horizontal layout and 8 pts
// Arial font Set the background and border color to Transparent.
c.addLegend(45, 12, False, "", 8).setBackground(cd.Transparent);

// Add a title to the chart using 9 pts Arial Bold/white font. Use a 1 x 2 bitmap
// pattern as the background.
c.addTitle("Server Load (Jun 01 - Jun 07)", "Arial Bold", 9, "0xffffff"
    ).setBackground(c.patternColor(Array("0x004000", "0x008000"), 2));

// Set the y axis label format to nn%
c.yAxis().setLabelFormat("{value}%");

// Set the labels on the x axis
c.xAxis().setLabels(labels);

// Add a line layer to the chart
layer = c.addLineLayer();

// Add the first line. Plot the points with a 7 pixel square symbol
layer.addDataSet(data0, "0xcf4040", "Peak").setDataSymbol(cd.SquareSymbol, 7);

// Add the second line. Plot the points with a 9 pixel dismond symbol
layer.addDataSet(data1, "0x40cf40", "Average").setDataSymbol(cd.DiamondSymbol, 9);

// Enable data label on the data points. Set the label format to nn%.
layer.setDataLabelFormat("{value|0}%");

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "", "title='{xLabel}: {dataSetName} {value}%'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Symbol Line Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Symbol Line Chart (2)

Symbol Line Chart (2)

This example demonstrates using symbols to represent data points and using gradient color for plot area background.

  • The gradient plot area background is configured by using BaseChart.linearGradientColor to define the gradient color, then use XYChart.setPlotArea to apply it to the plot area.

  • The XYChart.setPlotArea also sets the plot area border and grid line colors to white.

  • Use BaseChart.addLegend to add a legend at the top of the chart.

  • Use DataSet.setDataSymbol to configure symbols for the data points.

  • Set the line width for all lines in the layer using Layer.setLineWidth. (To set the line width for one particular line, use DataSet.setLineWidth.)

Source Code Listing

[File: cfdemo/symbolline2.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the line chart
data0 = Array(42, 49, 33, 38, 64, 56, 29, 41, 44, 57, 59, 42);
data1 = Array(65, 75, 47, 34, 42, 49, 73, 62, 90, 69, 66, 78);
data2 = Array(36, 28, 25, 28, 38, 20, 22, 30, 25, 33, 30, 24);
labels = Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct",
    "Nov", "Dec");

// Create a XYChart object of size 600 x 375 pixels
c = cd.XYChart(600, 375);

// Add a title to the chart using 18 pts Times Bold Italic font
c.addTitle("Product Line Global Revenue", "Times New Roman Bold Italic", 18);

// Set the plotarea at (50, 55) and of 500 x 280 pixels in size. Use a vertical
// gradient color from light blue (f9f9ff) to sky blue (aaccff) as background. Set
// border to transparent and grid lines to white (ffffff).
c.setPlotArea(50, 55, 500, 280, c.linearGradientColor(0, 55, 0, 335, "0xf9fcff",
    "0xaaccff"), -1, cd.Transparent, "0xffffff");

// Add a legend box at (50, 28) using horizontal layout. Use 10pts Arial Bold as
// font, with transparent background.
c.addLegend(50, 28, False, "Arial Bold", 10).setBackground(cd.Transparent);

// Set the x axis labels
c.xAxis().setLabels(labels);

// Set y-axis tick density to 30 pixels. ChartDirector auto-scaling will use this as
// the guideline when putting ticks on the y-axis.
c.yAxis().setTickDensity(30);

// Set axis label style to 8pts Arial Bold
c.xAxis().setLabelStyle("Arial Bold", 8);
c.yAxis().setLabelStyle("Arial Bold", 8);

// Set axis line width to 2 pixels
c.xAxis().setWidth(2);
c.yAxis().setWidth(2);

// Add axis title using 10pts Arial Bold Italic font
c.yAxis().setTitle("Revenue in US millions", "Arial Bold Italic", 10);

// Add a line layer to the chart
layer = c.addLineLayer2();

// Set the line width to 3 pixels
layer.setLineWidth(3);

// Add the three data sets to the line layer, using circles, diamands and X shapes as
// symbols
layer.addDataSet(data0, "0xff0000", "Quantum Computer").setDataSymbol(
    cd.CircleSymbol, 9);
layer.addDataSet(data1, "0x00ff00", "Atom Synthesizer").setDataSymbol(
    cd.DiamondSymbol, 11);
layer.addDataSet(data2, "0xff6600", "Proton Cannon").setDataSymbol(cd.Cross2Shape(),
    11);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='Revenue of {dataSetName} in {xLabel}: US$ {value}M'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Symbol Line Chart (2)
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Spline Line Chart

Spline Line Chart

This example demonstrates using spline curves to join data points, title with soft lighting effect, as well as a number of chart formatting techniques.

  • Add a spline layer to the chart using XYChart.addSplineLayer.

  • Set the shapes, sizes and colors of the data symbols using DataSet.setDataSymbol.

  • The soft lighting effect of the title is defined using ChartDirector.CFChart.softLighting, then applied to the title using Box.setBackground of the title TextBox object.

  • Set the background, border and grid colors of the plot area using XYChart.setPlotArea.

  • Control the line width of the axes using Axis.setWidth.

  • Include icon images in chart and axis titles using CDML.

  • Add a logo at the bottom right corner of the plot area as custom text using BaseChart.addText with BottomRight alignment. The logo includes images and text encoded using CDML.

Source Code Listing

[File: cfdemo/splineline.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the chart
data0 = Array(32, 39, 23, 28, 41, 38, 26, 35, 29);
data1 = Array(50, 55, 47, 34, 47, 53, 38, 40, 51);

// The labels for the chart
labels = Array("0", "1", "2", "3", "4", "5", "6", "7", "8");

// Create a XYChart object of size 600 x 300 pixels, with a pale red (ffdddd)
// background, black border, 1 pixel 3D border effect and rounded corners.
c = cd.XYChart(600, 300, "0xffdddd", "0x000000", 1);
c.setRoundedFrame();

// Set search path to current directory for loading icon images
c.setSearchPath(GetPageContext());

// Set the plotarea at (55, 58) and of size 520 x 195 pixels, with white (ffffff)
// background. Set horizontal and vertical grid lines to grey (cccccc).
c.setPlotArea(55, 58, 520, 195, "0xffffff", -1, -1, "0xcccccc", "0xcccccc");

// Add a legend box at (55, 32) (top of the chart) with horizontal layout. Use 9 pts
// Arial Bold font. Set the background and border color to Transparent.
c.addLegend(55, 32, False, "Arial Bold", 9).setBackground(cd.Transparent);

// Add a title box to the chart using 15 pts Times Bold Italic font. The title is in
// CDML and includes embedded images for highlight. The text is white (ffffff) on a
// dark red (880000) background, with soft lighting effect from the right side.
c.addTitle(
    "<*block,valign=absmiddle*><*img=star.png*><*img=star.png*> Performance " &
    "Enhancer <*img=star.png*><*img=star.png*><*/*>", "Times New Roman Bold Italic",
    15, "0xffffff").setBackground("0x880000", -1, cd.softLighting(cd.Right));

// Add a title to the y axis
c.yAxis().setTitle("Energy Concentration (KJ per liter)");

// Set the labels on the x axis
c.xAxis().setLabels(labels);

// Add a title to the x axis using CMDL
c.xAxis().setTitle(
    "<*block,valign=absmiddle*><*img=clock.png*>  Elapsed Time (hour)<*/*>");

// Set the axes width to 2 pixels
c.xAxis().setWidth(2);
c.yAxis().setWidth(2);

// Add a spline layer to the chart
layer = c.addSplineLayer();

// Set the default line width to 2 pixels
layer.setLineWidth(2);

// Add a data set to the spline layer, using blue (0000c0) as the line color, with
// yellow (ffff00) circle symbols.
layer.addDataSet(data1, "0x0000c0", "Target Group").setDataSymbol(cd.CircleSymbol, 9,
    "0xffff00");

// Add a data set to the spline layer, using brown (982810) as the line color, with
// pink (f040f0) diamond symbols.
layer.addDataSet(data0, "0x982810", "Control Group").setDataSymbol(cd.DiamondSymbol,
    11, "0xf040f0");

// Add a custom CDML text at the bottom right of the plot area as the logo
c.addText(575, 250,
    "<*block,valign=absmiddle*><*img=small_molecule.png*> <*block*><*font=Times " &
    "New Roman Bold Italic,size=10,color=804040*>Molecular<*br*>Engineering<*/*>"
    ).setAlignment(cd.BottomRight);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName} at t = {xLabel} hour: {value} KJ/liter'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Spline Line Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Step Line Chart

Step Line Chart

This example demonstrates joining data points with steps. It also demonstrates irregularly spaced data points on an auto-scaled true date/time axis.

The step line layer is created using XYChart.addStepLineLayer.

Most of the sample charts in this document use enumerated x-axes. In this axis type, the data points are assumed to be evenly spread on the x-direction, so it is not necessary to supply the x values of the data points. The x-axis is treated as a series of text labels using Axis.setLabels or Axis.setLabels2. The labels can be dates/times, numbers, names, or any arbitrary text in any format. Enumerated x-axis is an easy to use yet extremely flexible axis type that is suitable for most charts.

However, for charts with data points not regularly spaced, it is necessary to supply the x values of the data points using Layer.setXData. In this case, ChartDirector can automatically determine the type and scale on the x-axis (auto-scaling).

For date/time axis, in many cases one may need to control the date/time label format. This can be done using Axis.setDateScale3.

Source Code Listing

[File: cfdemo/stepline.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the chart
dataY0 = Array(4, 4.5, 5, 5.25, 5.75, 5.25, 5, 4.5, 4, 3, 2.5, 2.5);
dataX0 = Array(CreateDate(1997, 1, 1), CreateDate(1998, 6, 25), CreateDate(1999, 9, 6
    ), CreateDate(2000, 2, 6), CreateDate(2000, 9, 21), CreateDate(2001, 3, 4),
    CreateDate(2001, 6, 8), CreateDate(2002, 2, 4), CreateDate(2002, 5, 19),
    CreateDate(2002, 8, 16), CreateDate(2002, 12, 1), CreateDate(2003, 1, 1));

dataY1 = Array(7, 6.5, 6, 5, 6.5, 7, 6, 5.5, 5, 4, 3.5, 3.5);
dataX1 = Array(CreateDate(1997, 1, 1), CreateDate(1997, 7, 1), CreateDate(1997, 12, 1
    ), CreateDate(1999, 1, 15), CreateDate(1999, 6, 9), CreateDate(2000, 3, 3),
    CreateDate(2000, 8, 13), CreateDate(2001, 5, 5), CreateDate(2001, 9, 16),
    CreateDate(2002, 3, 16), CreateDate(2002, 6, 1), CreateDate(2003, 1, 1));

// Create a XYChart object of size 500 x 270 pixels, with a pale blue (e0e0ff)
// background, black border, 1 pixel 3D border effect and rounded corners
c = cd.XYChart(600, 300, "0xe0e0ff", "0x000000", 1);
c.setRoundedFrame();

// Set the plotarea at (55, 60) and of size 520 x 200 pixels, with white (ffffff)
// background. Set horizontal and vertical grid lines to grey (cccccc).
c.setPlotArea(50, 60, 525, 200, "0xffffff", -1, -1, "0xcccccc", "0xcccccc");

// Add a legend box at (55, 32) (top of the chart) with horizontal layout. Use 9 pts
// Arial Bold font. Set the background and border color to Transparent.
c.addLegend(55, 32, False, "Arial Bold", 9).setBackground(cd.Transparent);

// Add a title box to the chart using 15 pts Times Bold Italic font. The text is
// white (ffffff) on a deep blue (000088) background, with soft lighting effect from
// the right side.
c.addTitle("Long Term Interest Rates", "Times New Roman Bold Italic", 15, "0xffffff"
    ).setBackground("0x000088", -1, cd.softLighting(cd.Right));

// Set the y axis label format to display a percentage sign
c.yAxis().setLabelFormat("{value}%");

// Add a red (ff0000) step line layer to the chart and set the line width to 2 pixels
layer0 = c.addStepLineLayer(dataY0, "0xff0000", "Country AAA");
layer0.setXData(dataX0);
layer0.setLineWidth(2);

// Add a blue (0000ff) step line layer to the chart and set the line width to 2
// pixels
layer1 = c.addStepLineLayer(dataY1, "0x0000ff", "Country BBB");
layer1.setXData(dataX1);
layer1.setLineWidth(2);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName} change to {value}% on {x|mmm dd, yyyy}'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Step Line Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Line Comparison

Line Comparison

This example demonstrates filling the area between two lines or curves, as well as a number of advanced chart formatting techniques.

ChartDirector supports filling the area between two lines. The lines can be from a LineLayer, SplineLayer, StepLineLayer, TrendLayer or from an axis Mark. Two colors can be used for filling, depending on which line is on top.

The effects in this example is achieved using the following methods:

  • Add the purple spline curve to the chart using XYChart.addSplineLayer.

  • Add the two green lines to the chart using XYChart.addLineLayer and Layer.addDataSet.

  • Color the region between the two green lines with semi-transparent green using XYChart.addInterLineLayer.

  • Color the region between the spline curve and the upper green line using XYChart.addInterLineLayer. The fill color is set to red if the spline line is above the upper green line, otherwise it is Transparent.

  • Color the region between the spline curve and the lower green line using XYChart.addInterLineLayer. The fill color is set to blue if the spline line is below the lower green line, otherwise it is Transparent.

Source Code Listing

[File: cfdemo/linecompare.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the upper and lower bounding lines
upperY = Array(60, 60, 100, 100, 60, 60);
lowerY = Array(40, 40, 80, 80, 40, 40);
zoneX = Array(0, 2.5, 3.5, 5.5, 6.5, 10);

// The data for the spline curve
curveY = Array(50, 44, 54, 48, 58, 50, 90, 85, 104, 82, 96, 90, 74, 52, 35, 58, 46,
    54, 48, 52, 50);
curveX = Array(0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6, 6.5, 7, 7.5, 8,
    8.5, 9, 9.5, 10);

// Create a XYChart object of size 600 x 300 pixels, with a light grey (cccccc)
// background, black border, and 1 pixel 3D border effect.
c = cd.XYChart(600, 300, "0xcccccc", "0x000000", 1);

// Set search path to current directory for loading icon images
c.setSearchPath(GetPageContext());

// Set the plotarea at (55, 58) and of size 520 x 195 pixels, with white background.
// Turn on both horizontal and vertical grid lines with light grey color (cccccc)
c.setPlotArea(55, 58, 520, 195, "0xffffff", -1, -1, "0xcccccc", "0xcccccc");

// Add a legend box at (55, 32) (top of the chart) with horizontal layout. Use 9 pts
// Arial Bold font. Set the background and border color to Transparent.
c.addLegend(55, 32, False, "Arial Bold", 9).setBackground(cd.Transparent);

// Add a title box to the chart using 15 pts Times Bold Italic font. The title is in
// CDML and includes embedded images for highlight. The text is white (ffffff) on a
// black background, with a 1 pixel 3D border.
c.addTitle(
    "<*block,valign=absmiddle*><*img=star.png*><*img=star.png*> Performance " &
    "Enhancer <*img=star.png*><*img=star.png*><*/*>", "Times New Roman Bold Italic",
    15, "0xffffff").setBackground("0x000000", -1, 1);

// Add a title to the y axis
c.yAxis().setTitle("Temperature");

// Add a title to the x axis using CMDL
c.xAxis().setTitle(
    "<*block,valign=absmiddle*><*img=clock.png*>  Elapsed Time (hour)<*/*>");

// Set the axes width to 2 pixels
c.xAxis().setWidth(2);
c.yAxis().setWidth(2);

// Add a purple (800080) spline layer to the chart with a line width of 2 pixels
splineLayer = c.addSplineLayer(curveY, "0x800080", "Molecular Temperature");
splineLayer.setXData(curveX);
splineLayer.setLineWidth(2);

// Add a line layer to the chart with two dark green (338033) data sets, and a line
// width of 2 pixels
lineLayer = c.addLineLayer2();
lineLayer.addDataSet(upperY, "0x338033", "Target Zone");
lineLayer.addDataSet(lowerY, "0x338033");
lineLayer.setXData(zoneX);
lineLayer.setLineWidth(2);

// Color the zone between the upper zone line and lower zone line as semi-transparent
// light green (8099ff99)
c.addInterLineLayer(lineLayer.getLine(0), lineLayer.getLine(1), "0x8099ff99",
    "0x8099ff99");

// If the spline line gets above the upper zone line, color to area between the lines
// red (ff0000)
c.addInterLineLayer(splineLayer.getLine(0), lineLayer.getLine(0), "0xff0000",
    cd.Transparent);

// If the spline line gets below the lower zone line, color to area between the lines
// blue (0000ff)
c.addInterLineLayer(splineLayer.getLine(0), lineLayer.getLine(1), cd.Transparent,
    "0x0000ff");

// Add a custom CDML text at the bottom right of the plot area as the logo
c.addText(575, 250,
    "<*block,valign=absmiddle*><*img=small_molecule.png*> <*block*><*font=Times " &
    "New Roman Bold Italic,size=10,color=804040*>Molecular<*br*>Engineering<*/*>"
    ).setAlignment(cd.BottomRight);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "", "title='Temperature at hour {x}: {value} C'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Line Comparison
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Line with Error Symbols

Line with Error Symbols

This example demonstrates combining a line layer with a box-whisker layer to draw a line with error symbols.

The blue line and the yellow diamond symbols are from the line layer, created using XYChart.addLineLayer2, Layer.addDataSet, and DataSet.setDataSymbol.

The error symbols come from the box-whisker layer, created using XYChart.addBoxWhiskerLayer. In this example, the "box" parts of the box- whisker symbols are disabled by setting the data for the box and median to empty arrays. As a result, only the "whisker" parts of the box-whisker symbols are visible and they become the error symbols.

The maximum and minimum marks in this example is computed by adding/subtracting the error value to/from the data value using a ChartDirector utility class ArrayMath.

Source Code Listing

[File: cfdemo/errline.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data with error information
data = Array(42, 49, 33, 38, 51, 46, 29, 41, 44, 57, 59, 52, 37, 34, 51, 56, 56, 60,
    70, 76, 63, 67, 75, 64, 51);
errData = Array(5, 6, 5.1, 6.5, 6.6, 8, 5.4, 5.1, 4.6, 5.0, 5.2, 6.0, 4.9, 5.6, 4.8,
    6.2, 7.4, 7.1, 6.0, 6.6, 7.1, 5.3, 5.5, 7.9, 6.1);

// The labels for the chart
labels = Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12",
    "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24");

// Create a XYChart object of size 600 x 300 pixels, with a light grey (eeeeee)
// background, black border, 1 pixel 3D border effect and rounded corners.
c = cd.XYChart(600, 300, "0xeeeeee", "0x000000", 1);
c.setRoundedFrame();

// Set search path to current directory for loading icon images
c.setSearchPath(GetPageContext());

// Set the plotarea at (55, 55) and of size 520 x 195 pixels, with white (ffffff)
// background. Set horizontal and vertical grid lines to grey (cccccc).
c.setPlotArea(55, 55, 520, 195, "0xffffff", -1, -1, "0xcccccc", "0xcccccc");

// Add a title box to the chart using 15 pts Times Bold Italic font. The title is in
// CDML and includes embedded images for highlight. The text is on a light grey
// (dddddd) background, with glass lighting effect.
c.addTitle(
    "<*block,valign=absmiddle*><*img=star.png*><*img=star.png*> Molecular " &
    "Temperature Control <*img=star.png*><*img=star.png*><*/*>",
    "Times New Roman Bold Italic", 15).setBackground("0xdddddd", 0, cd.glassEffect())
    ;

// Add a title to the y axis
c.yAxis().setTitle("Temperature");

// Add a title to the x axis using CMDL
c.xAxis().setTitle(
    "<*block,valign=absmiddle*><*img=clock.png*>  Elapsed Time (hour)<*/*>");

// Set the labels on the x axis.
c.xAxis().setLabels(labels);

// Display 1 out of 3 labels on the x-axis. Show minor ticks for remaining labels.
c.xAxis().setLabelStep(3, 1);

// Set the axes width to 2 pixels
c.xAxis().setWidth(2);
c.yAxis().setWidth(2);

// Add a line layer to the chart
lineLayer = c.addLineLayer2();

// Add a blue (0xff) data set to the line layer, with yellow (0xffff80) diamond
// symbols
lineLayer.addDataSet(data, "0x0000ff").setDataSymbol(cd.DiamondSymbol, 12, "0xffff80"
    );

// Set the line width to 2 pixels
lineLayer.setLineWidth(2);

// Add a box whisker layer to the chart. Use the upper and lower mark of the box
// whisker layer to act as error zones. The upper and lower marks are computed using
// the ArrayMath object.
errLayer = c.addBoxWhiskerLayer(Array(), Array(), cd.ArrayMath(data).add(errData
    ).result(), cd.ArrayMath(data).sub(errData).result(), data, cd.Transparent,
    "0xbb6633");

// Set the line width to 2 pixels
errLayer.setLineWidth(2);

// Set the error zone to occupy half the space between the symbols
errLayer.setDataGap(0.5);

// Add a custom CDML text at the bottom right of the plot area as the logo
c.addText(575, 247,
    "<*block,valign=absmiddle*><*img=small_molecule.png*> <*block*><*font=Times " &
    "New Roman Bold Italic,size=10,color=804040*>Molecular<*br*>Engineering<*/*>"
    ).setAlignment(cd.BottomRight);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart. We only need to show the tool tip for the box
// whisker layer.
imageMap1 = errLayer.getHTMLImageMap("", "",
    "title='Temperature at hour {xLabel}: {med} +/- {={med}-{min}} C'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Line with Error Symbols
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Multi-Symbol Line Chart

Multi-Symbol Line Chart

This example demonstrates a line with different symbols for different data points. It also demonstrates irregularly spaced data points on an auto-scaled true date/time axis.

This chart is created by using a line layer for the line, and using multiple scatter layers for different types of symbols. The scatter layers are created first using XYChart.addScatterLayer first, followed by the line layer using XYChart.addLineLayer. This ensures the symbols stays on top of the line.

In this example, the ArrayMath utility, through the ArrayMath.selectEQZ and ArrayMath.sub methods, is used to select the subset of data to be used for various symbols.

Note that in this example, the data points are irregularly spaced, and the x coordinates are real date/time. The x coordinates are set into the scatter layer as the first parameter of XYChart.addScatterLayer, and into the line layer using Layer.setXData. As the x-axis scale is not configured, ChartDirector auto-scales the x-axis to fit the data in the x-coordinates.

Source Code Listing

[File: cfdemo/multisymbolline.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// In this example, the data points are unevenly spaced on the x-axis
dataY = Array(4.7, 4.7, 6.6, 2.2, 4.7, 4.0, 4.0, 5.1, 4.5, 4.5, 6.8, 4.5, 4, 2.1, 3,
    2.5, 2.5, 3.1);
dataX = Array(CreateDate(1999, 7, 1), CreateDate(2000, 1, 1), CreateDate(2000, 2, 1),
    CreateDate(2000, 4, 1), CreateDate(2000, 5, 8), CreateDate(2000, 7, 5),
    CreateDate(2001, 3, 5), CreateDate(2001, 4, 7), CreateDate(2001, 5, 9),
    CreateDate(2002, 2, 4), CreateDate(2002, 4, 4), CreateDate(2002, 5, 8),
    CreateDate(2002, 7, 7), CreateDate(2002, 8, 30), CreateDate(2003, 1, 2),
    CreateDate(2003, 2, 16), CreateDate(2003, 11, 6), CreateDate(2004, 1, 4));

// Data points are assigned different symbols based on point type
pointType = Array(0, 1, 0, 1, 2, 1, 0, 0, 1, 1, 2, 2, 1, 0, 2, 1, 2, 0);

// Create a XYChart object of size 600 x 300 pixels, with a light purple (ffccff)
// background, black border, 1 pixel 3D border effect and rounded corners.
c = cd.XYChart(600, 300, "0xffccff", "0x000000", 1);
c.setRoundedFrame();

// Set the plotarea at (55, 58) and of size 520 x 195 pixels, with white (ffffff)
// background. Set horizontal and vertical grid lines to grey (cccccc).
c.setPlotArea(55, 58, 520, 195, "0xffffff", -1, -1, "0xcccccc", "0xcccccc");

// Add a legend box at (55, 30) (top of the chart) with horizontal layout. Use 10 pts
// Arial Bold Italic font. Set the background and border color to Transparent.
c.addLegend(55, 30, False, "Arial Bold Italic", 10).setBackground(cd.Transparent);

// Add a title box to the chart using 15 pts Times Bold Italic font. The text is
// white (ffffff) on a purple (400040) background, with soft lighting effect from the
// right side.
c.addTitle("Multi-Symbol Line Chart Demo", "Times New Roman Bold Italic", 15,
    "0xffffff").setBackground("0x400040", -1, cd.softLighting(cd.Right));

// Set the y axis label format to display a percentage sign
c.yAxis().setLabelFormat("{value}%");

// Set axis titles to use 9pt Arial Bold Italic font
c.yAxis().setTitle("Axis Title Placeholder", "Arial Bold Italic", 9);
c.xAxis().setTitle("Axis Title Placeholder", "Arial Bold Italic", 9);

// Set axis labels to use Arial Bold font
c.yAxis().setLabelStyle("Arial Bold");
c.xAxis().setLabelStyle("Arial Bold");

// We add the different data symbols using scatter layers. The scatter layers are
// added before the line layer to make sure the data symbols stay on top of the line
// layer.

// We select the points with pointType = 0 (the non-selected points will be set to
// NoValue), and use yellow (ffff00) 15 pixels high 5 pointed star shape symbols for
// the points. (This example uses both x and y coordinates. For charts that have no x
// explicitly coordinates, use an empty array as dataX.)
c.addScatterLayer(dataX, cd.ArrayMath(dataY).selectEQZ(pointType, cd.NoValue).result(
    ), "Point Type 0", cd.StarShape(5), 15, "0xffff00");

// Similar to above, we select the points with pointType - 1 = 0 and use green (ff00)
// 13 pixels high six-sided polygon as symbols.
c.addScatterLayer(dataX, cd.ArrayMath(dataY).selectEQZ(cd.ArrayMath(pointType).sub(1
    ).result(), cd.NoValue).result(), "Point Type 1", cd.PolygonShape(6), 13,
    "0x00ff00");

// Similar to above, we select the points with pointType - 2 = 0 and use red (ff0000)
// 13 pixels high X shape as symbols.
c.addScatterLayer(dataX, cd.ArrayMath(dataY).selectEQZ(cd.ArrayMath(pointType).sub(2
    ).result(), cd.NoValue).result(), "Point Type 2", cd.Cross2Shape(), 13,
    "0xff0000");

// Finally, add a blue (0000ff) line layer with line width of 2 pixels
layer = c.addLineLayer(dataY, "0x0000ff");
layer.setXData(dataX);
layer.setLineWidth(2);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "", "title='{x|mmm dd, yyyy}: {value}%'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Multi-Symbol Line Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Custom Symbols

Custom Symbols

This example demonstrates loading external image files as data symbols by using DataSet.setDataSymbol2.

Source Code Listing

[File: cfdemo/customsymbolline.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the chart
data0 = Array(600, 800, 1200, 1500, 1800, 1900, 2000, 1950);
data1 = Array(300, 450, 500, 1000, 1500, 1600, 1650, 1600);

// The labels for the chart
labels = Array("1995", "1996", "1997", "1998", "1999", "2000", "2001", "2002");

// Create a XYChart object of size 450 x 250 pixels, with a pale yellow (0xffffc0)
// background, a black border, and 1 pixel 3D border effect.
c = cd.XYChart(450, 250, "0xffffc0", 0, 1);

// Set search path to current directory for loading icon images
c.setSearchPath(GetPageContext());

// Set the plotarea at (60, 45) and of size 360 x 170 pixels, using white (0xffffff)
// as the plot area background color. Turn on both horizontal and vertical grid lines
// with light grey color (0xc0c0c0)
c.setPlotArea(60, 45, 360, 170, "0xffffff", -1, -1, "0xc0c0c0", -1);

// Add a legend box at (60, 20) (top of the chart) with horizontal layout. Use 8 pts
// Arial Bold font. Set the background and border color to Transparent.
c.addLegend(60, 20, False, "Arial Bold", 8).setBackground(cd.Transparent);

// Add a title to the chart using 12 pts Arial Bold/white font. Use a 1 x 2 bitmap
// pattern as the background.
c.addTitle("Information Resource Usage", "Arial Bold", 12, "0xffffff").setBackground(
    c.patternColor(Array("0x000040", "0x000080"), 2));

// Set the labels on the x axis
c.xAxis().setLabels(labels);

// Reserve 8 pixels margins at both side of the x axis to avoid the first and last
// symbols drawing outside of the plot area
c.xAxis().setMargin(8, 8);

// Add a title to the y axis
c.yAxis().setTitle("Population");

// Add a line layer to the chart
layer = c.addLineLayer2();

// Add the first line using small_user.png as the symbol.
layer.addDataSet(data0, "0xcf4040", "Users").setDataSymbol2("small_user.png");

// Add the first line using small_computer.png as the symbol.
layer.addDataSet(data1, "0x40cf40", "Computers").setDataSymbol2("small_computer.png")
    ;

// Set the line width to 3 pixels
layer.setLineWidth(3);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='Number of {dataSetName} at {xLabel}: {value}'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Custom Symbols
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Rotated Line Chart

Rotated Line Chart

This example demonstrates swapping the x and y axes to produce a rotated line chart in which the line goes from top to bottom (instead of left to right).

The x and y axes in the example are configured as follows:

  • Initially, the x-axis is horizontal from left to right at the bottom of the plot area, while the y-axis is vertical from bottom to top at the left side of the plot area.

  • Swap the x and y axes using XYChart.swapXY. Now the x-axis is vertical from bottom to top at the left side of the chart, while the y-axis is horizontal from left to right at the bottom of the chart.

  • Use XYChart.setYAxisOnRight to move the y-axis to the opposite side of the plot area, so that the y-axis is at the top of the plot area. (Note: the "right" word on setYAxisOnRight means the "right" side before "swapXY" rotation. After rotation, the right side will become to top side.)

  • Use Axis.setReverse to reverse the direction of the x-axis, so that the x-axis is vertical from top to bottom (instead of from bottom to top).
For demo purposes, this example uses RanTable to simulate a database table with 4 columns, in which one is a date/time column and the remaining three are data columns. The date/time column is passed to ChartDirector as the x values using Layer.setXData, while the data columns are passed to ChartDirector as y values using Layer.addDataSet.

Source Code Listing

[File: cfdemo/rotatedline.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

//
//    We use a random table to simulate generating 12 months of data
//

// Create the random table object with 4 cols * 12 rows, using 3 as seed
rantable = cd.RanTable(3, 4, 12);

// Set the 1st column to be the 12 months of year 2002
rantable.setDateCol(0, CreateDate(2002, 1, 1), 86400 * 30);

// Set the 2nd, 3rd and 4th columns to be random numbers starting from 125, 75, and
// 100 respectively. The change between rows is set to -35 to + 35. The minimum value
// of any cell is 0.
rantable.setCol(1, 125, -35, 35, 0);
rantable.setCol(2, 75, -35, 35, 0);
rantable.setCol(3, 100, -35, 35, 0);

// Get the 1st column (time) as the x data
dataX = rantable.getCol(0);

// Get the 2nd, 3rd and 4th columns as 3 data sets
dataY0 = rantable.getCol(1);
dataY1 = rantable.getCol(2);
dataY2 = rantable.getCol(3);

// Create a XYChart object of size 360 x 400 pixels
c = cd.XYChart(360, 400);

// Add a title to the chart
c.addTitle("<*underline=2*>Rotated Line Chart Demo", "Times New Roman Bold Italic",
    14);

// Set the plotarea at (60, 75) and of size 190 x 320 pixels. Turn on both horizontal
// and vertical grid lines with light grey color (0xc0c0c0)
c.setPlotArea(60, 75, 190, 320).setGridColor("0xc0c0c0", "0xc0c0c0");

// Add a legend box at (270, 75)
c.addLegend(270, 75);

// Swap the x and y axis to become a rotated chart
c.swapXY();

// Set the y axis on the top side (right + rotated = top)
c.setYAxisOnRight();

// Add a title to the y axis
c.yAxis().setTitle("Throughput (MBytes)");

// Reverse the x axis so it is pointing downwards
c.xAxis().setReverse();

// Add a line chart layer using the given data
layer = c.addLineLayer2();
layer.setXData(dataX);
layer.addDataSet(dataY0, "0xff0000", "Server A");
layer.addDataSet(dataY1, "0x338033", "Server B");
layer.addDataSet(dataY2, "0x0000ff", "Server C");

// Set the line width to 2 pixels
layer.setLineWidth(2);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='[{dataSetName}] {x|mm/yyyy}: {value|0} MByte'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Rotated Line Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Arbitrary XY Line Chart

Arbitrary XY Line Chart

This example demonstrates drawing a line chart with arbitrary x coordinates (not increasing or decreasing in one direction), and adding custom data labels to data points.

The x values of the data points are set into the chart using Layer.setXData. ChartDirector merely joins the points together with lines. It does not require the points to following any particular direction.

Note that this example has special labels for the start and end points of the lines. They are created using Layer.addCustomDataLabel.

Source Code Listing

[File: cfdemo/xyline.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The (x, y) data for the first line
dataX0 = Array(20, 90, 40, 30, 12);
dataY0 = Array(10, 40, 75, 54, 20);

// The (x, y) data for the second line
dataX1 = Array(10, 40, 75, 54, 60);
dataY1 = Array(50, 90, 40, 30, 10);

// Create a XYChart object of size 450 x 450 pixels
c = cd.XYChart(450, 450);

// Set the plotarea at (55, 65) and of size 350 x 300 pixels, with white background
// and a light grey border (0xc0c0c0). Turn on both horizontal and vertical grid
// lines with light grey color (0xc0c0c0)
c.setPlotArea(55, 65, 350, 300, "0xffffff", -1, "0xc0c0c0", "0xc0c0c0", -1);

// Add a legend box at (50, 30) (top of the chart) with horizontal layout. Use 12 pts
// Times Bold Italic font. Set the background and border color to Transparent.
c.addLegend(50, 30, False, "Times New Roman Bold Italic", 12).setBackground(
    cd.Transparent);

// Add a title to the chart using 18 pts Times Bold Itatic font
c.addTitle("Reaction Path", "Times New Roman Bold Italic", 18);

// Add a title to the y axis using 12 pts Arial Bold Italic font
c.yAxis().setTitle("Temperature (Celcius)", "Arial Bold Italic", 12);

// Set the y axis line width to 3 pixels
c.yAxis().setWidth(3);

// Add a title to the x axis using 12 pts Arial Bold Italic font
c.xAxis().setTitle("Pressure (Pa)", "Arial Bold Italic", 12);

// Set the x axis line width to 3 pixels
c.xAxis().setWidth(3);

// Add a red (0xff3333) line layer using dataX0 and dataY0
layer1 = c.addLineLayer(dataY0, "0xff3333", "Compound AAA");
layer1.setXData(dataX0);

// Set the line width to 3 pixels
layer1.setLineWidth(3);

// Use 9 pixel square symbols for the data points
layer1.getDataSet(0).setDataSymbol(cd.SquareSymbol, 9);

// Add custom text labels to the first and last point on the scatter plot using Arial
// Bold font
layer1.addCustomDataLabel(0, 0, "Start", "Arial Bold");
layer1.addCustomDataLabel(0, 4, "End", "Arial Bold");

// Add a green (0x33ff33) line layer using dataX1 and dataY1
layer2 = c.addLineLayer(dataY1, "0x33ff33", "Compound BBB");
layer2.setXData(dataX1);

// Set the line width to 3 pixels
layer2.setLineWidth(3);

// Use 11 pixel diamond symbols for the data points
layer2.getDataSet(0).setDataSymbol(cd.DiamondSymbol, 11);

// Add custom text labels to the first and last point on the scatter plot using Arial
// Bold font
layer2.addCustomDataLabel(0, 0, "Start", "Arial Bold");
layer2.addCustomDataLabel(0, 4, "End", "Arial Bold");

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='[{dataSetName}] Pressure = {x} Pa, Temperature = {value} C'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Arbitrary XY Line Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Discontinuous Lines

Discontinuous Lines

This example demonstrates using NoValue to represent lines with missing data points. It also demonstrates vertical zones and custom text boxes.

In ChartDirector, a special predefined constant NoValue is used to denote missing data points. The methods to handle missing data points depend on chart types.

For line charts, a NoValue data point is handled by jumping over it, that is, by connecting the previous data point to the next data point. However, the line color and style for jumping over NoValue data points can be different from the normal line color. The default is Transparent, so the jump over line will be invisible. Therefore, a NoValue point will result in a discontinuous line.

You can modify the color and style of the jump over line by using LineLayer.setGapColor.

A common design is to use dash lines as jump over lines. This can be achieved by using dash line colors (created with BaseChart.dashLineColor) as jump over line colors.

If you want the jump over line to be the same color as the original line, use SameAsMainColor as the jump over line color.

In this example, there are grey vertical zones on the chart. These are created using Axis.addZone.

The custom text boxes that label weeks are created using BaseChart.addText, with their coordinates are obtained dynamically using Layer.getXCoor.

Note that BaseChart.layout needs to be call first to auto-scale and finalize the axes before using Layer.getXCoor.

Source Code Listing

[File: cfdemo/discontline.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

//===================================================================
//    For demo purpose, use random numbers as data for the chart
//===================================================================

// Use a random table to create the data. The random table contains 4 cols x 31 rows,
// using 9 as seed.
rantable = cd.RanTable(9, 4, 31);

// Set the 1st col to be the series 1, 2, 3, ....
rantable.setCol(0, 1, 1, 1);

// Set the 2nd, 3rd and 4th col to be random number starting from 40, 50 and 60. The
// change between rows is set to -5 to 5. The minimum value of any cell is 0.
rantable.setCol(1, 40, -5, 5, 0);
rantable.setCol(2, 50, -5, 5, 0);
rantable.setCol(3, 60, -5, 5, 0);

// Use the 1st col as the axis label
labels = rantable.getCol(0);

// Use the 2nd, 3rd and 4th columns for 3 lines
data0 = rantable.getCol(1);
data1 = rantable.getCol(2);
data2 = rantable.getCol(3);

// Simulate some data points have no data value
for (i = 1; i LT 30; i = i + 7) {
    data0[i + 1] = cd.NoValue;
    data1[i + 1] = cd.NoValue;
    data2[i + 1] = cd.NoValue;
}

//===================================================================
//    Now we have the data ready. Actually drawing the chart.
//===================================================================

// Create a XYChart object of size 600 x 220 pixels
c = cd.XYChart(600, 220);

// Set the plot area at (100, 25) and of size 450 x 150 pixels. Enabled both vertical
// and horizontal grids by setting their colors to light grey (0xc0c0c0)
c.setPlotArea(100, 25, 450, 150).setGridColor("0xc0c0c0", "0xc0c0c0");

// Add a legend box (92, 0) (top of plot area) using horizontal layout. Use 8 pts
// Arial font. Disable bounding box (set border to transparent).
c.addLegend(92, 0, False, "", 8).setBackground(cd.Transparent);

// Add a title to the y axis. Draw the title upright (font angle = 0)
c.yAxis().setTitle("Average<*br*>Utilization<*br*>(MBytes)").setFontAngle(0);

// Use manually scaling of y axis from 0 to 100, with ticks every 10 units
c.yAxis().setLinearScale(0, 100, 10);

// Set the labels on the x axis
c.xAxis().setLabels2(labels);

// Set the title on the x axis
c.xAxis().setTitle("Jun - 2001");

// Add x axis (vertical) zones to indicate Saturdays and Sundays
for (i = 0; i LT 29; i = i + 7) {
    c.xAxis().addZone(i, i + 2, "0xc0c0c0");
}

// Add a line layer to the chart
layer = c.addLineLayer();

// Set the default line width to 2 pixels
layer.setLineWidth(2);

// Add the three data sets to the line layer
layer.addDataSet(data0, "0xcf4040", "Server ##1");
layer.addDataSet(data1, "0x40cf40", "Server ##2");
layer.addDataSet(data2, "0x4040cf", "Server ##3");

// Layout the chart to fix the y axis scaling. We can then use getXCoor and getYCoor
// to determine the position of custom objects.
c.layout();

// Add the "week n" custom text boxes at the top of the plot area.
for (i = 0; i LT 4; i = i + 1) {
    // Add the "week n" text box using 8 pt Arial font with top center alignment.
    textbox = c.addText(layer.getXCoor(i * 7 + 2), 25, "Week " & i, "Arial Bold", 8,
        "0x000000", cd.TopCenter);

    // Set the box width to cover five days
    textbox.setSize(layer.getXCoor(i * 7 + 7) - layer.getXCoor(i * 7 + 2) + 1, 0);

    // Set box background to pale yellow 0xffff80, with a 1 pixel 3D border
    textbox.setBackground("0xffff80", cd.Transparent, 1);
}

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='[{dataSetName}] {xLabel} Jun 2001: {value|2} MBytes'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Discontinuous Lines
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Trending and Curve Fitting

Trending and Curve Fitting

Title | Description
Trend Line Chart | Demonstrates linear regression trend line fitting. Also demonstrates rotating the x-axis labels by 90 degrees to save axis space.
Scatter Trend Chart | Demonstrates linear regression trend line fitting together with scatter layers.
Confidence Band | Demonstrates adding confidence bands to a trend line. Also demonstrates how to display linear regression parameters on the chart.
General Curve Fitting | Demonstrates the LOWESS general purpose curve fitting that is built into ChartDirector.


Trend Line Chart

Trend Line Chart

This example demonstrates linear regression trend line fitting. It also demonstrates rotating the x-axis labels by 90 degrees to save axis space.

A trend line is a straight line that fits a number of data points computed using linear regression (the least square method).

In ChartDirector, a trend line is created by adding a trend line layer using XYChart.addTrendLayer or XYChart.addTrendLayer2 method.

Typically, a trend line layer is used with other layers for the data points. In this example, two layers are used. A line chart layer draws the line that joins the data points. The trend line layer draws a straight line that best fit the same data points.

Note that the x-axis labels on the above chart are rotated by 90 degrees to save space. This is achieved by using TextBox.setFontAngle of the TextBox object that represents the x-axis label prototype.

Source Code Listing

[File: cfdemo/trendline.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the line chart
data = Array(50, 55, 47, 34, 42, 49, 63, 62, 73, 59, 56, 50, 64, 60, 67, 67, 58, 59,
    73, 77, 84, 82, 80, 91);

// The labels for the line chart
labels = Array("Jan 2000", "Feb 2000", "Mar 2000", "Apr 2000", "May 2000",
    "Jun 2000", "Jul 2000", "Aug 2000", "Sep 2000", "Oct 2000", "Nov 2000",
    "Dec 2000", "Jan 2001", "Feb 2001", "Mar 2001", "Apr 2001", "May 2001",
    "Jun 2001", "Jul 2001", "Aug 2001", "Sep 2001", "Oct 2001", "Nov 2001",
    "Dec 2001");

// Create a XYChart object of size 500 x 320 pixels, with a pale purpule (0xffccff)
// background, a black border, and 1 pixel 3D border effect.
c = cd.XYChart(500, 320, "0xffccff", "0x000000", 1);

// Set the plotarea at (55, 45) and of size 420 x 210 pixels, with white background.
// Turn on both horizontal and vertical grid lines with light grey color (0xc0c0c0)
c.setPlotArea(55, 45, 420, 210, "0xffffff", -1, -1, "0xc0c0c0", -1);

// Add a legend box at (55, 25) (top of the chart) with horizontal layout. Use 8 pts
// Arial font. Set the background and border color to Transparent.
c.addLegend(55, 22, False, "", 8).setBackground(cd.Transparent);

// Add a title box to the chart using 13 pts Times Bold Italic font. The text is
// white (0xffffff) on a purple (0x800080) background, with a 1 pixel 3D border.
c.addTitle("Long Term Server Load", "Times New Roman Bold Italic", 13, "0xffffff"
    ).setBackground("0x800080", -1, 1);

// Add a title to the y axis
c.yAxis().setTitle("MBytes");

// Set the labels on the x axis. Rotate the font by 90 degrees.
c.xAxis().setLabels(labels).setFontAngle(90);

// Add a line layer to the chart
lineLayer = c.addLineLayer();

// Add the data to the line layer using light brown color (0xcc9966) with a 7 pixel
// square symbol
lineLayer.addDataSet(data, "0xcc9966", "Server Utilization").setDataSymbol(
    cd.SquareSymbol, 7);

// Set the line width to 2 pixels
lineLayer.setLineWidth(2);

// tool tip for the line layer
lineLayer.setHTMLImageMap("", "", "title='{xLabel}: {value} MBytes'");

// Add a trend line layer using the same data with a dark green (0x008000) color. Set
// the line width to 2 pixels
trendLayer = c.addTrendLayer(data, "0x008000", "Trend Line");
trendLayer.setLineWidth(2);

// tool tip for the trend layer
trendLayer.setHTMLImageMap("", "", "title='Change rate: {slope|2} MBytes/per month'")
    ;

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// include tool tip for the chart
imageMap1 = c.getHTMLImageMap("");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Trend Line Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Scatter Trend Chart

Scatter Trend Chart

This example demonstrates linear regression trend line fitting together with scatter layers.

The chart in this example composed of four layers - 2 scatter layers created using XYChart.addScatterLayer, and two trend line layer created using XYChart.addTrendLayer2.

Source Code Listing

[File: cfdemo/scattertrend.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The XY data of the first data series
dataX0 = Array(50, 55, 37, 24, 42, 49, 63, 72, 83, 59);
dataY0 = Array(3.6, 2.8, 2.5, 2.3, 3.8, 3.0, 3.8, 5.0, 6.0, 3.3);

// The XY data of the second data series
dataX1 = Array(50, 55, 37, 24, 42, 49, 63, 72, 83, 59);
dataY1 = Array(1.6, 1.8, 0.8, 0.5, 1.3, 1.5, 2.3, 2.4, 2.9, 1.5);

// Tool tip formats for data points and trend lines
scatterToolTip = "title='{dataSetName}: Response time at {x} TPS: {value} sec'";
trendToolTip = "title='Slope = {slope|4} sec/TPS; Intercept = {intercept|4} sec'";

// Create a XYChart object of size 450 x 420 pixels
c = cd.XYChart(450, 420);

// Set the plotarea at (55, 65) and of size 350 x 300 pixels, with white background
// and a light grey border (0xc0c0c0). Turn on both horizontal and vertical grid
// lines with light grey color (0xc0c0c0)
c.setPlotArea(55, 65, 350, 300, "0xffffff", -1, "0xc0c0c0", "0xc0c0c0", -1);

// Add a legend box at (50, 30) (top of the chart) with horizontal layout. Use 12 pts
// Times Bold Italic font. Set the background and border color to Transparent.
c.addLegend(50, 30, False, "Times New Roman Bold Italic", 12).setBackground(
    cd.Transparent);

// Add a title to the chart using 18 point Times Bold Itatic font.
c.addTitle("Server Performance", "Times New Roman Bold Italic", 18);

// Add a title to the y axis using 12 pts Arial Bold Italic font
c.yAxis().setTitle("Response Time (sec)", "Arial Bold Italic", 12);

// Set the y axis line width to 3 pixels
c.yAxis().setWidth(3);

// Set the y axis label format to show 1 decimal point
c.yAxis().setLabelFormat("{value|1}");

// Add a title to the x axis using 12 pts Arial Bold Italic font
c.xAxis().setTitle("Server Load (TPS)", "Arial Bold Italic", 12);

// Set the x axis line width to 3 pixels
c.xAxis().setWidth(3);

// Add a scatter layer using (dataX0, dataY0)
scatter1 = c.addScatterLayer(dataX0, dataY0, "Server AAA", cd.DiamondSymbol, 11,
    "0x008000");
scatter1.setHTMLImageMap("", "", scatterToolTip);

// Add a trend line layer for (dataX0, dataY0)
trend1 = c.addTrendLayer2(dataX0, dataY0, "0x008000");
trend1.setLineWidth(3);
trend1.setHTMLImageMap("", "", trendToolTip);

// Add a scatter layer for (dataX1, dataY1)
scatter2 = c.addScatterLayer(dataX1, dataY1, "Server BBB", cd.TriangleSymbol, 9,
    "0x6666ff");
scatter2.setHTMLImageMap("", "", scatterToolTip);

// Add a trend line layer for (dataX1, dataY1)
trend2 = c.addTrendLayer2(dataX1, dataY1, "0x6666ff");
trend2.setLineWidth(3);
trend2.setHTMLImageMap("", "", trendToolTip);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// include tool tip for the chart
imageMap1 = c.getHTMLImageMap("");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Scatter Trend Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Confidence Band

Confidence Band

This example demonstrates adding confidence bands to a trend line. It also demonstrates how to display linear regression parameters on the chart.

In linear regression, the data points are assumed to be related by:

y = m * x + c + err

where m and c are constants, and err is a random variable. Linear regression estimates m, c and err based on available data.

As m and c are estimated values, the trend line y = m * x + c may be inaccurate. In ChartDirector, the uncertainties can be represented as a confidence band using TrendLayer.addConfidenceBand. For example, the 95% confidence band means there are 95% probability that the "real" trend line is in that band.

To predict a data point (infer y given x), we use y = m * x + c + err. As m, c and err are estimated values, the predicted data point may be inaccurate. In ChartDirector, the uncertainties can be represented as a prediction band using TrendLayer.addPredictionBand.

Note that the prediction band is always wider than the confidence band because of the extra uncertainties contributed by the err term.

In ChartDirector, the linear regression parameters slope, intercept, correlation coefficient and standard error can be obtained by using TrendLayer.getSlope, TrendLayer.getIntercept, TrendLayer.getCorrelation and TrendLayer.getStdError. (Please refer to appropriate statistics text books for explanation of these values.)

In this example, the linear regression parameters are formatted into a table using CDML, which is then added to the chart as custom text box using BaseChart.addText.

Source Code Listing

[File: cfdemo/confidenceband.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The XY data of the first data series
dataX = Array(50, 55, 37, 24, 42, 49, 63, 72, 83, 59);
dataY = Array(3.6, 2.8, 2.5, 2.3, 3.8, 3.0, 3.8, 5.0, 6.0, 3.3);

// Create a XYChart object of size 450 x 420 pixels
c = cd.XYChart(450, 420);

// Set the plotarea at (55, 65) and of size 350 x 300 pixels, with white background
// and a light grey border (0xc0c0c0). Turn on both horizontal and vertical grid
// lines with light grey color (0xc0c0c0)
c.setPlotArea(55, 65, 350, 300, "0xffffff", -1, "0xc0c0c0", "0xc0c0c0", -1);

// Add a title to the chart using 18 point Times Bold Itatic font.
c.addTitle("Server Performance", "Times New Roman Bold Italic", 18);

// Add a title to the y axis using 12 pts Arial Bold Italic font
c.yAxis().setTitle("Response Time (sec)", "Arial Bold Italic", 12);

// Set the y axis line width to 3 pixels
c.yAxis().setWidth(3);

// Set the y axis label format to show 1 decimal point
c.yAxis().setLabelFormat("{value|1}");

// Add a title to the x axis using 12 pts Arial Bold Italic font
c.xAxis().setTitle("Server Load (TPS)", "Arial Bold Italic", 12);

// Set the x axis line width to 3 pixels
c.xAxis().setWidth(3);

// Add a scatter layer using (dataX, dataY)
scatterLayer = c.addScatterLayer(dataX, dataY, "", cd.DiamondSymbol, 11, "0x008000");

// tool tip for scatter layer
scatterLayer.setHTMLImageMap("", "", "title='Response time at {x} TPS: {value} sec'")
    ;

// Add a trend line layer for (dataX, dataY)
trendLayer = c.addTrendLayer2(dataX, dataY, "0x008000");

// Set the line width to 3 pixels
trendLayer.setLineWidth(3);

// Add a 95% confidence band for the line
trendLayer.addConfidenceBand(0.95, "0x806666ff");

// Add a 95% confidence band (prediction band) for the points
trendLayer.addPredictionBand(0.95, "0x8066ff66");

// tool tip for trend layer
trendLayer.setHTMLImageMap("", "",
    "title='Slope = {slope|4} sec/TPS; Intercept = {intercept|4} sec'");

// Add a legend box at (50, 30) (top of the chart) with horizontal layout. Use 10 pts
// Arial Bold Italic font. Set the background and border color to Transparent.
legendBox = c.addLegend(50, 30, False, "Arial Bold Italic", 10);
legendBox.setBackground(cd.Transparent);

// Add entries to the legend box
legendBox.addKey("95% Line Confidence", "0x806666ff");
legendBox.addKey("95% Point Confidence", "0x8066ff66");

// Display the trend line parameters as a text table formatted using CDML
textbox = c.addText(56, 65,
    "<*block*>Slope<*br*>Intercept<*br*>Correlation<*br*>Std Error<*/*>   <*block*>"
     & NumberFormat(trendLayer.getSlope(), ".9999") & " sec/tps<*br*>" &
    NumberFormat(trendLayer.getIntercept(), ".9999") & " sec<*br*>" & NumberFormat(
    trendLayer.getCorrelation(), ".9999") & "<*br*>" & NumberFormat(
    trendLayer.getStdError(), ".9999") & " sec<*/*>", "Arial Bold", 8);

// Set the background of the text box to light grey, with a black border, and 1 pixel
// 3D border
textbox.setBackground("0xc0c0c0", 0, 1);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// include tool tip for the chart
imageMap1 = c.getHTMLImageMap("");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Confidence Band
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


General Curve Fitting

General Curve Fitting

This example demonstrates the LOWESS general purpose curve fitting that is built into ChartDirector.

In linear regression, the relationship among the x and y coordinates are assumed to be linear.

However, in many applications, that relationship cannot be assumed to be linear. It can be polynomial, exponential, logarithmic, gaussian, sinusoidal, etc. In many cases, the relationship is not even known.

To solve this kind of problems, ChartDirector supports a general curve fitting algorithm known as LOWESS using ArrayMath.lowess and ArrayMath.lowess2.

LOWESS works by assuming a small segment of any curve can be approximated by a straight line. For each data point, LOWESS performs a weighted linear regression using nearby points. It then adjusts the data point using the result of the linear regression. The adjusted data points should lie on the smooth curve reflecting the underlying relationship. For further details, please refer to ArrayMath.lowess.

The LOWESS algorithm only adjusts the points to smoothen them. They still need to be joined together. In this example, the adjusted points are joined with a spline layer using XYChart.addSplineLayer.

Source Code Listing

[File: cfdemo/curvefitting.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// Use random table to generate a random series. The random table is set to 1 col x
// 51 rows, with 9 as the seed
rantable = cd.RanTable(9, 1, 51);

// Set the 1st column to start from 100, with changes between rows from -5 to +5
rantable.setCol(0, 100, -5, 5);

// Get the 1st column of the random table as the data set
data = rantable.getCol(0);

// Create a XYChart object of size 600 x 300 pixels
c = cd.XYChart(600, 300);

// Set the plotarea at (50, 35) and of size 500 x 240 pixels. Enable both the
// horizontal and vertical grids by setting their colors to grey (0xc0c0c0)
c.setPlotArea(50, 35, 500, 240).setGridColor("0xc0c0c0", "0xc0c0c0");

// Add a title to the chart using 18 point Times Bold Itatic font.
c.addTitle("LOWESS Generic Curve Fitting Algorithm", "Times New Roman Bold Italic",
    18);

// Set the y axis line width to 3 pixels
c.yAxis().setWidth(3);

// Add a title to the x axis using 12 pts Arial Bold Italic font
c.xAxis().setTitle("Server Load (TPS)", "Arial Bold Italic", 12);

// Set the x axis line width to 3 pixels
c.xAxis().setWidth(3);

// Set the x axis scale from 0 - 50, with major tick every 5 units and minor tick
// every 1 unit
c.xAxis().setLinearScale(0, 50, 5, 1);

// Add a blue layer to the chart
layer = c.addLineLayer2();

// Add a red (0x80ff0000) data set to the chart with square symbols
layer.addDataSet(data, "0x80ff0000").setDataSymbol(cd.SquareSymbol);

// Set the line width to 2 pixels
layer.setLineWidth(2);

// Use lowess for curve fitting, and plot the fitted data using a spline layer with
// line width set to 3 pixels
c.addSplineLayer(cd.ArrayMath(data).lowess().result(), "0x0000ff").setLineWidth(3);

// Set zero affinity to 0 to make sure the line is displayed in the most detail scale
c.yAxis().setAutoScale(0, 0, 0);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "", "title='({x}, {value|2})'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    General Curve Fitting
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Scatter/Bubble/Vector Charts

Scatter/Bubble/Vector Charts

Title | Description
Scatter Chart | Demonstrates a scatter chart created using XYChart.addScatterLayer.
Built-In Symbols | Demonstrates the built-in symbols supported by ChartDirector.
Custom Scatter Symbols | Demonstrates using external image files as scatter symbols.
Custom Scatter Labels | Demonstrates adding custom labels to data points.
Bubble Chart | Demonstrates how to create a bubble chart.
Bubble XY Scaling | Demonstrates a bubble chart with independent x and y bubble sizes and non-circular bubbles.
Vector Chart | Demonstrates a vector chart.


Scatter Chart

Scatter Chart

This example demonstrates a scatter chart created using XYChart.addScatterLayer.

Source Code Listing

[File: cfdemo/scatter.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The XY points for the scatter chart
dataX0 = Array(10, 15, 6, 12, 14, 8, 13, 13, 16, 12, 10.5);
dataY0 = Array(130, 150, 80, 110, 110, 105, 130, 115, 170, 125, 125);

dataX1 = Array(6, 12, 4, 3.5, 7, 8, 9, 10, 12, 11, 8);
dataY1 = Array(65, 80, 40, 45, 70, 80, 80, 90, 100, 105, 60);

// Create a XYChart object of size 450 x 420 pixels
c = cd.XYChart(450, 420);

// Set the plotarea at (55, 65) and of size 350 x 300 pixels, with a light grey
// border (0xc0c0c0). Turn on both horizontal and vertical grid lines with light grey
// color (0xc0c0c0)
c.setPlotArea(55, 65, 350, 300, -1, -1, "0xc0c0c0", "0xc0c0c0", -1);

// Add a legend box at (50, 30) (top of the chart) with horizontal layout. Use 12 pts
// Times Bold Italic font. Set the background and border color to Transparent.
c.addLegend(50, 30, False, "Times New Roman Bold Italic", 12).setBackground(
    cd.Transparent);

// Add a title to the chart using 18 pts Times Bold Itatic font.
c.addTitle("Genetically Modified Predator", "Times New Roman Bold Italic", 18);

// Add a title to the y axis using 12 pts Arial Bold Italic font
c.yAxis().setTitle("Length (cm)", "Arial Bold Italic", 12);

// Add a title to the x axis using 12 pts Arial Bold Italic font
c.xAxis().setTitle("Weight (kg)", "Arial Bold Italic", 12);

// Set the axes line width to 3 pixels
c.xAxis().setWidth(3);
c.yAxis().setWidth(3);

// Add an orange (0xff9933) scatter chart layer, using 13 pixel diamonds as symbols
c.addScatterLayer(dataX0, dataY0, "Genetically Engineered", cd.DiamondSymbol, 13,
    "0xff9933");

// Add a green (0x33ff33) scatter chart layer, using 11 pixel triangles as symbols
c.addScatterLayer(dataX1, dataY1, "Natural", cd.TriangleSymbol, 11, "0x33ff33");

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='[{dataSetName}] Weight = {x} kg, Length = {value} cm'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Scatter Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Built-In Symbols

Built-In Symbols

This example demonstrates the built-in symbols supported by ChartDirector.

Source Code Listing

[File: cfdemo/builtinsymbols.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// Some ChartDirector built-in symbols
symbols = Array(cd.SquareSymbol, cd.DiamondSymbol, cd.TriangleSymbol,
    cd.RightTriangleSymbol, cd.LeftTriangleSymbol, cd.InvertedTriangleSymbol,
    cd.CircleSymbol, cd.StarShape(3), cd.StarShape(4), cd.StarShape(5), cd.StarShape(
    6), cd.StarShape(7), cd.StarShape(8), cd.StarShape(9), cd.StarShape(10),
    cd.PolygonShape(5), cd.Polygon2Shape(5), cd.PolygonShape(6), cd.Polygon2Shape(6),
    cd.PolygonShape(7), cd.PolygonShape(8), cd.CrossShape(0.1), cd.CrossShape(0.2),
    cd.CrossShape(0.3), cd.CrossShape(0.4), cd.CrossShape(0.5), cd.CrossShape(0.6),
    cd.CrossShape(0.7), cd.Cross2Shape(0.1), cd.Cross2Shape(0.2), cd.Cross2Shape(0.3
    ), cd.Cross2Shape(0.4), cd.Cross2Shape(0.5), cd.Cross2Shape(0.6), cd.Cross2Shape(
    0.7));

// Create a XYChart object of size 450 x 400 pixels
c = cd.XYChart(450, 400);

// Set search path to current directory for loading icon images
c.setSearchPath(GetPageContext());

// Set the plotarea at (55, 40) and of size 350 x 300 pixels, with a light grey
// border (0xc0c0c0). Turn on both horizontal and vertical grid lines with light grey
// color (0xc0c0c0)
c.setPlotArea(55, 40, 350, 300, -1, -1, "0xc0c0c0", "0xc0c0c0", -1);

// Add a title to the chart using 18 pts Times Bold Itatic font.
c.addTitle("Built-in Symbols", "Times New Roman Bold Italic", 18);

// Set the axes line width to 3 pixels
c.xAxis().setWidth(3);
c.yAxis().setWidth(3);

// Add each symbol as a separate scatter layer.
for (i = 0; i LT ArrayLen(symbols); i = i + 1) {
    c.addScatterLayer(Array(i Mod 5 + 1), Array(Int(i / 5 + 1)), "", symbols[i + 1],
        15);
}

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "", "title='(x, y) = ({x}, {value})'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Built-in Symbols
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Custom Scatter Symbols

Custom Scatter Symbols

This example demonstrates using external image files as scatter symbols.

The chart in this example is created as 5 scatter layers using XYChart.addScatterLayer, with each layer containing one point.

The symbols for the scatter layers come from external image files. They are loaded using DataSet.setDataSymbol2.

Source Code Listing

[File: cfdemo/scattersymbols.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The XY points for the scatter chart
dataX = Array(200, 400, 300, 250, 500);
dataY = Array(40, 100, 50, 150, 250);

// The custom symbols for the points
symbols = Array("robot1.png", "robot2.png", "robot3.png", "robot4.png", "robot5.png")
    ;

// Create a XYChart object of size 450 x 400 pixels
c = cd.XYChart(450, 400);

// Set search path to current directory for loading icon images
c.setSearchPath(GetPageContext());

// Set the plotarea at (55, 40) and of size 350 x 300 pixels, with a light grey
// border (0xc0c0c0). Turn on both horizontal and vertical grid lines with light grey
// color (0xc0c0c0)
c.setPlotArea(55, 40, 350, 300, -1, -1, "0xc0c0c0", "0xc0c0c0", -1);

// Add a title to the chart using 18 pts Times Bold Itatic font.
c.addTitle("Battle Robots", "Times New Roman Bold Italic", 18);

// Add a title to the y axis using 12 pts Arial Bold Italic font
c.yAxis().setTitle("Speed (km/s)", "Arial Bold Italic", 12);

// Add a title to the y axis using 12 pts Arial Bold Italic font
c.xAxis().setTitle("Range (km)", "Arial Bold Italic", 12);

// Set the axes line width to 3 pixels
c.xAxis().setWidth(3);
c.yAxis().setWidth(3);

// Add each point of the data as a separate scatter layer, so that they can have a
// different symbol
for (i = 0; i LT ArrayLen(dataX); i = i + 1) {
    c.addScatterLayer(Array(dataX[i + 1]), Array(dataY[i + 1])).getDataSet(0
        ).setDataSymbol2(symbols[i + 1]);
}

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "", "title='Range = {x} km, Speed = {value} km/s'")
    ;

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Custom Scatter Symbols
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Custom Scatter Labels

Custom Scatter Labels

This example demonstrates adding custom labels to data points.

  • The red circles in this example comes from a scatter layer created using XYChart.addScatterLayer.

  • The custom labels in this example is contained in an array variable, and is added as an extra field to the chart using Layer.addExtraField.

  • The data label format is set using Layer.setDataLabelFormat to show the extra field.

  • The font for the data labels is set to 8 points Arial Bold using Layer.setDataLabelStyle.

  • Layer.setDataLabelStyle returns a TextBox object representing the prototype of the data labels. In this example, the TextBox object is used to customize the background colors, 3D borders, position offsets and alignments of the data labels.

Source Code Listing

[File: cfdemo/scatterlabels.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The XY points for the scatter chart
dataX = Array(150, 400, 300, 1500, 800);
dataY = Array(0.6, 8, 5.4, 2, 4);

// The labels for the points
labels = Array("Nano<*br*>100", "SpeedTron<*br*>200 Lite", "SpeedTron<*br*>200",
    "Marathon<*br*>Extra", "Marathon<*br*>2000");

// Create a XYChart object of size 450 x 400 pixels
c = cd.XYChart(450, 400);

// Set the plotarea at (55, 40) and of size 350 x 300 pixels, with a light grey
// border (0xc0c0c0). Turn on both horizontal and vertical grid lines with light grey
// color (0xc0c0c0)
c.setPlotArea(55, 40, 350, 300, "0xffffff", -1, "0xc0c0c0", "0xc0c0c0", -1);

// Add a title to the chart using 18 pts Times Bold Itatic font.
c.addTitle("Product Comparison Chart", "Times New Roman Bold Italic", 18);

// Add a title to the y axis using 12 pts Arial Bold Italic font
c.yAxis().setTitle("Capacity (tons)", "Arial Bold Italic", 12);

// Add a title to the x axis using 12 pts Arial Bold Italic font
c.xAxis().setTitle("Range (miles)", "Arial Bold Italic", 12);

// Set the axes line width to 3 pixels
c.xAxis().setWidth(3);
c.yAxis().setWidth(3);

// Add the data as a scatter chart layer, using a 15 pixel circle as the symbol
layer = c.addScatterLayer(dataX, dataY, "Server BBB", cd.CircleSymbol, 15,
    "0xff3333", "0xff3333");

// Add labels to the chart as an extra field
layer.addExtraField(labels);

// Set the data label format to display the extra field
layer.setDataLabelFormat("{field0}");

// Use 8pts Arial Bold to display the labels
textbox = layer.setDataLabelStyle("Arial Bold", 8);

// Set the background to purple with a 1 pixel 3D border
textbox.setBackground("0xcc99ff", cd.Transparent, 1);

// Put the text box 4 pixels to the right of the data point
textbox.setAlignment(cd.Left);
textbox.setPos(4, 0);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='Range = {x} miles, Capacity = {value} tons'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Custom Scatter Labels
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Bubble Chart

Bubble Chart

This example demonstrates how to create a bubble chart.

In ChartDirector, a bubble chart can be created as a scatter layer with circles as symbols using XYChart.addScatterLayer. The sizes of the symbols are then controlled by another data series (z data) using LineLayer.setSymbolScale. This creates circles of different sizes.

By default, ChartDirector handles z data using pixel units. That means a z value of 50 will result in a symbol size of 50 pixels. If your z data are too small or too large, you may re-scale them using ArrayMath.mul before passing them to LineLayer.setSymbolScale.

ChartDirector also supports handling the z data using the same scale as the y (or x) axis by supplying additional arguments to LineLayer.setSymbolScale. This is useful if the symbol sizes reflect some features of the y (or x) data, such as the standard deviation or confidence of the y (or x) value.

Source Code Listing

[File: cfdemo/bubble.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The XYZ points for the bubble chart
dataX0 = Array(150, 300, 1000, 1700);
dataY0 = Array(12, 60, 25, 65);
dataZ0 = Array(20, 50, 50, 85);

dataX1 = Array(500, 1000, 1300);
dataY1 = Array(35, 50, 75);
dataZ1 = Array(30, 55, 95);

// Create a XYChart object of size 450 x 420 pixels
c = cd.XYChart(450, 420);

// Set the plotarea at (55, 65) and of size 350 x 300 pixels, with a light grey
// border (0xc0c0c0). Turn on both horizontal and vertical grid lines with light grey
// color (0xc0c0c0)
c.setPlotArea(55, 65, 350, 300, -1, -1, "0xc0c0c0", "0xc0c0c0", -1);

// Add a legend box at (50, 30) (top of the chart) with horizontal layout. Use 12 pts
// Times Bold Italic font. Set the background and border color to Transparent.
c.addLegend(50, 30, False, "Times New Roman Bold Italic", 12).setBackground(
    cd.Transparent);

// Add a title to the chart using 18 pts Times Bold Itatic font.
c.addTitle("Product Comparison Chart", "Times New Roman Bold Italic", 18);

// Add a title to the y axis using 12 pts Arial Bold Italic font
c.yAxis().setTitle("Capacity (tons)", "Arial Bold Italic", 12);

// Add a title to the x axis using 12 pts Arial Bold Italic font
c.xAxis().setTitle("Range (miles)", "Arial Bold Italic", 12);

// Set the axes line width to 3 pixels
c.xAxis().setWidth(3);
c.yAxis().setWidth(3);

// Add (dataX0, dataY0) as a scatter layer with semi-transparent red (0x80ff3333)
// circle symbols, where the circle size is modulated by dataZ0. This creates a
// bubble effect.
c.addScatterLayer(dataX0, dataY0, "Technology AAA", cd.CircleSymbol, 9, "0x80ff3333",
    "0x80ff3333").setSymbolScale(dataZ0);

// Add (dataX1, dataY1) as a scatter layer with semi-transparent green (0x803333ff)
// circle symbols, where the circle size is modulated by dataZ1. This creates a
// bubble effect.
c.addScatterLayer(dataX1, dataY1, "Technology BBB", cd.CircleSymbol, 9, "0x803333ff",
    "0x803333ff").setSymbolScale(dataZ1);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='[{dataSetName}] Range = {x} miles, Capacity = {value} tons, Length = " &
    "{z} meters'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Bubble Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Bubble XY Scaling

Bubble XY Scaling

This example demonstrates a bubble chart with independent x and y bubble sizes and non-circular bubbles.

In ChartDirector, a bubble chart in general is a scatter layer with the symbol sizes controlled by some other data series.

ChartDirector supports using arbitrary symbols as bubbles. Thus bubble shape is not limited to circle but can be any shapes.

Furthermore, ChartDirector supports independent x and y sizes for bubbles. This is useful for creating charts in which the bubbles reflect some features of the data points, such as its confidence zone, x and y errors, x and y standard deviations, etc.

Source Code Listing

[File: cfdemo/bubblescale.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The XY points for the bubble chart. The bubble chart has independent bubble size
// on the X and Y direction.
dataX0 = Array(1000, 1500, 1700);
dataY0 = Array(25, 20, 65);
dataZX0 = Array(500, 200, 600);
dataZY0 = Array(15, 30, 20);

dataX1 = Array(500, 1000, 1300);
dataY1 = Array(35, 50, 75);
dataZX1 = Array(800, 300, 500);
dataZY1 = Array(8, 27, 25);

dataX2 = Array(150, 300);
dataY2 = Array(20, 60);
dataZX2 = Array(160, 400);
dataZY2 = Array(30, 20);

// Create a XYChart object of size 450 x 420 pixels
c = cd.XYChart(450, 420);

// Set the plotarea at (55, 65) and of size 350 x 300 pixels, with a light grey
// border (0xc0c0c0). Turn on both horizontal and vertical grid lines with light grey
// color (0xc0c0c0)
c.setPlotArea(55, 65, 350, 300, -1, -1, "0xc0c0c0", "0xc0c0c0", -1);

// Add a legend box at (50, 30) (top of the chart) with horizontal layout. Use 12 pts
// Times Bold Italic font. Set the background and border color to Transparent.
c.addLegend(50, 30, False, "Times New Roman Bold Italic", 12).setBackground(
    cd.Transparent);

// Add a title to the chart using 18 pts Times Bold Itatic font.
c.addTitle("Plasma Battery Comparison", "Times New Roman Bold Italic", 18);

// Add titles to the axes using 12 pts Arial Bold Italic font
c.yAxis().setTitle("Operating Current", "Arial Bold Italic", 12);
c.xAxis().setTitle("Operating Voltage", "Arial Bold Italic", 12);

// Set the axes line width to 3 pixels
c.xAxis().setWidth(3);
c.yAxis().setWidth(3);

// Add (dataX0, dataY0) as a standard scatter layer, and also as a "bubble" scatter
// layer, using circles as symbols. The "bubble" scatter layer has symbol size
// modulated by (dataZX0, dataZY0) using the scale on the x and y axes.
c.addScatterLayer(dataX0, dataY0, "Vendor A", cd.CircleSymbol, 9, "0xff3333",
    "0xff3333");
c.addScatterLayer(dataX0, dataY0, "", cd.CircleSymbol, 9, "0x80ff3333", "0x80ff3333"
    ).setSymbolScale(dataZX0, cd.XAxisScale, dataZY0, cd.YAxisScale);

// Add (dataX1, dataY1) as a standard scatter layer, and also as a "bubble" scatter
// layer, using squares as symbols. The "bubble" scatter layer has symbol size
// modulated by (dataZX1, dataZY1) using the scale on the x and y axes.
c.addScatterLayer(dataX1, dataY1, "Vendor B", cd.SquareSymbol, 7, "0x3333ff",
    "0x3333ff");
c.addScatterLayer(dataX1, dataY1, "", cd.SquareSymbol, 9, "0x803333ff", "0x803333ff"
    ).setSymbolScale(dataZX1, cd.XAxisScale, dataZY1, cd.YAxisScale);

// Add (dataX2, dataY2) as a standard scatter layer, and also as a "bubble" scatter
// layer, using diamonds as symbols. The "bubble" scatter layer has symbol size
// modulated by (dataZX2, dataZY2) using the scale on the x and y axes.
c.addScatterLayer(dataX2, dataY2, "Vendor C", cd.DiamondSymbol, 9, "0x00ff00",
    "0x00ff00");
c.addScatterLayer(dataX2, dataY2, "", cd.DiamondSymbol, 9, "0x8033ff33", "0x8033ff33"
    ).setSymbolScale(dataZX2, cd.XAxisScale, dataZY2, cd.YAxisScale);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='Voltage = {x} +/- {={zx}/2} V, Current = {value} +/- {={zy}/2} A'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Bubble XY Scaling
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Vector Chart

Vector Chart

This example demonstrates a vector chart.

A vector chart is like a scatter chart, but the symbols are arrows which can be of arbitrary lengths pointing to arbitrary directions. Thus each symbol in a vector chart is specified by 4 values - the x and y coordinates, the length and the direction.

In ChartDirector, an XY vector layer is created using XYChart.addVectorLayer.

Source Code Listing

[File: cfdemo/vector.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The (x, y) coordinates of the starting point of the vectors
dataX = Array(20, 40, 60, 80, 100, 20, 40, 60, 80, 100, 20, 40, 58, 62, 80, 100, 20,
    40, 60, 80, 100, 20, 40, 60, 80, 100);
dataY = Array(20, 20, 20, 20, 20, 40, 40, 40, 40, 40, 60, 60, 60, 60, 60, 60, 80, 80,
    80, 80, 80, 100, 100, 100, 100, 100);

// The lengths (radii) and directions (angles) of the vectors
dataR = Array(6, 6, 9, 6, 6, 6, 9, 12, 9, 6, 9, 12, 12, 12, 12, 9, 6, 9, 12, 9, 6, 6,
    6, 9, 6, 6);
dataA = Array(-45, -30, 0, 30, 45, -60, -45, 0, 45, 60, -90, -90, -90, 90, 90, 90,
    -120, -135, 180, 135, 120, -135, -150, 180, 150, 135);

// Create a XYChart object of size 450 x 390 pixels
c = cd.XYChart(450, 390);

// Set the plotarea at (55, 40) and of size 350 x 300 pixels, with a light grey
// border (0xc0c0c0). Turn on both horizontal and vertical grid lines with light grey
// color (0xc0c0c0)
c.setPlotArea(55, 40, 350, 300, -1, -1, "0xc0c0c0", "0xc0c0c0", -1);

// Add a title to the chart using 18 pts Times Bold Itatic font.
c.addTitle("Vector Chart Demonstration", "Times New Roman Bold Italic", 18);

// Add a title to the y axis using 12 pts Arial Bold Italic font
c.yAxis().setTitle("Y Axis Title", "Arial Bold Italic", 12);

// Add a title to the x axis using 12 pts Arial Bold Italic font
c.xAxis().setTitle("X Axis Title", "Arial Bold Italic", 12);

// Set the axes line width to 3 pixels
c.xAxis().setWidth(3);
c.yAxis().setWidth(3);

// Add a vector layer to the chart using blue (0000CC) color, with vector arrow size
// set to 11 pixels
c.addVectorLayer(dataX, dataY, dataR, dataA, cd.YAxisScale, "0x0000cc").setArrowHead(
    11);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='Vector at ({x}, {value}): Length = {len}, Angle = {dir} deg'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Vector Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Area Charts

Area Charts

Title | Description
Simple Area Chart | Demonstrates the basic steps in creating area charts.
Enhanced Area Chart | Extends the Simple Area Chart example by decorating the chart using a number of chart formatting features.
3D Area Chart | Demonstrates a 3D area chart configured using Layer.set3D.
Pattern Area Chart | Demonstrates using a pattern for filling the area in an area chart, together with a number of chart formatting features.
Stacked Area Chart | Demonstrates using multiple data sets to create stacked area chart.
3D Stacked Area Chart | Demonstrates creating a stacked area chart with 3D effects.
Percentage Area Chart | Demonstrates creating a percentage area chart. Also demonstrates how to include icons in the legend box using CDML.
Depth Area Chart | Demonstrates using multiple area layers with semi-transparent colors to create a depth area chart.
Rotated Area Chart | Demonstrates swapping the x and y axes to produce an rotated area chart in which the area goes from left to right (instead of bottom to top).


Simple Area Chart

Simple Area Chart

This example demonstrates the basic steps in creating area charts.

  • Create an XYChart object using XYChart.XYChart.

  • Specify the plot area of the chart using XYChart.setPlotArea. The plot area is the rectangle bounded by the x and y axes. You should leave some margin on the outside of the plot area for axis labels, chart titles, etc.

  • Specify the labels on the x-axis using Axis.setLabels.

  • An area chart may contain many points and therefore many x-axis labels. In this example, Axis.setLabelStep is used to specify showing only a subset of the labels on the x-axis to avoid over-crowding.

  • Add an area layer and specify the data for the area using XYChart.addAreaLayer.

  • Generate the chart using BaseChart.makeSession.

  • Generate tool tips for the chart using BaseChart.getHTMLImageMap.

Source Code Listing

[File: cfdemo/simplearea.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the area chart
data = Array(30, 28, 40, 55, 75, 68, 54, 60, 50, 62, 75, 65, 75, 89, 60, 55, 53, 35,
    50, 66, 56, 48, 52, 65, 62);

// The labels for the area chart
labels = Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12",
    "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24");

// Create a XYChart object of size 250 x 250 pixels
c = cd.XYChart(250, 250);

// Set the plotarea at (30, 20) and of size 200 x 200 pixels
c.setPlotArea(30, 20, 200, 200);

// Add an area chart layer using the given data
c.addAreaLayer(data);

// Set the labels on the x axis.
c.xAxis().setLabels(labels);

// Display 1 out of 3 labels on the x-axis.
c.xAxis().setLabelStep(3);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "", "title='Hour {xLabel}: Traffic {value} GBytes'"
    );

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Simple Area Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Enhanced Area Chart

Enhanced Area Chart

This example extends the Simple Area Chart example by decorating the chart using a number of chart formatting features.

  • Create an XYChart object with background color and 3D border using XYChart.XYChart.

  • The rounded frame is configured using BaseChart.setRoundedFrame.

  • Set the background, border and grid colors of the plot area using XYChart.setPlotArea.

  • Add a title to the chart using BaseChart.addTitle. The title text is represented using CDML for including star icons in the text.

  • The soft lighting effect of the title is defined using ChartDirector.CFChart.softLighting, then applied to the title using Box.setBackground of the title TextBox object.

  • Add titles to the axes using Axis.setTitle.

  • Set the axis widths using Axis.setWidth.

  • Use a semi-transparent gradient color as the area color. The gradient color is created using BaseChart.linearGradientColor.

  • Add a logo at the bottom right corner of the plot area as custom text using BaseChart.addText with BottomRight alignment. The logo includes images and text encoded using CDML.

Source Code Listing

[File: cfdemo/enhancedarea.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the area chart
data = Array(30, 28, 40, 55, 75, 68, 54, 60, 50, 62, 75, 65, 75, 89, 60, 55, 53, 35,
    50, 66, 56, 48, 52, 65, 62);

// The labels for the area chart
labels = Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12",
    "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24");

// Create a XYChart object of size 600 x 300 pixels, with a pale blue (eeeeff)
// background, black border, 1 pixel 3D border effect and rounded corners.
c = cd.XYChart(600, 300, "0xeeeeff", "0x000000", 1);
c.setRoundedFrame();

// Set search path to current directory for loading icon images
c.setSearchPath(GetPageContext());

// Set the plotarea at (55, 55) and of size 520 x 195 pixels, with white (ffffff)
// background. Set horizontal and vertical grid lines to grey (cccccc).
c.setPlotArea(55, 55, 520, 195, "0xffffff", -1, -1, "0xcccccc", "0xcccccc");

// Add a title box to the chart using 15 pts Times Bold Italic font. The text is
// white (ffffff) on a deep blue (000088) background, with soft lighting effect from
// the right side.
c.addTitle(
    "<*block,valign=absmiddle*><*img=star.png*><*img=star.png*> Performance " &
    "Enhancer <*img=star.png*><*img=star.png*><*/*>", "Times New Roman Bold Italic",
    15, "0xffffff").setBackground("0x000088", -1, cd.softLighting(cd.Right));

// Add a title to the y axis
c.yAxis().setTitle("Energy Concentration (KJ per liter)");

// Set the labels on the x axis.
c.xAxis().setLabels(labels);

// Display 1 out of 3 labels on the x-axis.
c.xAxis().setLabelStep(3);

// Add a title to the x axis using CDML
c.xAxis().setTitle(
    "<*block,valign=absmiddle*><*img=clock.png*>  Elapsed Time (hour)<*/*>");

// Set the axes width to 2 pixels
c.xAxis().setWidth(2);
c.yAxis().setWidth(2);

// Add an area layer to the chart using a gradient color that changes vertically from
// semi-transparent red (80ff0000) to semi-transparent white (80ffffff)
c.addAreaLayer(data, c.linearGradientColor(0, 50, 0, 255, "0x80ff0000", "0x80ffffff")
    );

// Add a custom CDML text at the bottom right of the plot area as the logo
c.addText(575, 245,
    "<*block,valign=absmiddle*><*img=small_molecule.png*> <*block*><*font=Times " &
    "New Roman Bold Italic,size=10,color=804040*>Molecular<*br*>Engineering<*/*>"
    ).setAlignment(cd.BottomRight);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "", "title='Hour {xLabel}: {value} KJ/liter'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Enhanced Area Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


3D Area Chart

3D Area Chart

This example demonstrates a 3D area chart configured using Layer.set3D.

Source Code Listing

[File: cfdemo/threedarea.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the area chart
data = Array(30, 28, 40, 55, 75, 68, 54, 60, 50, 62, 75, 65, 75, 89, 60, 55, 53, 35,
    50, 66, 56, 48, 52, 65, 62);

// The labels for the area chart
labels = Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12",
    "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24");

// Create a XYChart object of size 300 x 300 pixels
c = cd.XYChart(300, 300);

// Set the plotarea at (45, 30) and of size 200 x 200 pixels
c.setPlotArea(45, 30, 200, 200);

// Add a title to the chart using 12 pts Arial Bold Italic font
c.addTitle("Daily Server Utilization", "Arial Bold Italic", 12);

// Add a title to the y axis
c.yAxis().setTitle("MBytes");

// Add a title to the x axis
c.xAxis().setTitle("June 12, 2001");

// Add a green (0x00ff00) 3D area chart layer using the give data
c.addAreaLayer(data, "0x00ff00").set3D();

// Set the labels on the x axis.
c.xAxis().setLabels(labels);

// Display 1 out of 3 labels on the x-axis.
c.xAxis().setLabelStep(3);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "", "title='Hour {xLabel}: Traffic {value} MBytes'"
    );

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    3D Area Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Pattern Area Chart

Pattern Area Chart

This example demonstrates using a pattern for filling the area in an area chart, together with a number of chart formatting features.

  • Create an XYChart object with background color and border using XYChart.XYChart.

  • Set the background color of the title box using Box.setBackground. The background color is a pattern color created using BaseChart.patternColor.

  • Enable both vertical and horizontal grid lines using XYChart.setPlotArea. The grid colors are dash line colors created using BaseChart.dashLineColor.

  • Create a pattern color with a "snow pattern" loaded from an image file using BaseChart.patternColor2.

  • Use DataSet.setDataColor to specify the area fill and border colors. Use the "snow pattern" as the area fill color.

  • Use Layer.setLineWidth to increase the border width of the area to highlight it.

Source Code Listing

[File: cfdemo/patternarea.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the area chart
data = Array(3.0, 2.8, 4.0, 5.5, 7.5, 6.8, 5.4, 6.0, 5.0, 6.2, 7.5, 6.5, 7.5, 8.1,
    6.0, 5.5, 5.3, 3.5, 5.0, 6.6, 5.6, 4.8, 5.2, 6.5, 6.2);

// The labels for the area chart
labels = Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12",
    "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24");

// Create a XYChart object of size 300 x 180 pixels. Set the background to pale
// yellow (0xffffa0) with a black border (0x0)
c = cd.XYChart(300, 180, "0xffffa0", "0x000000");

// Set search path to current directory for loading icon images
c.setSearchPath(GetPageContext());

// Set the plotarea at (45, 35) and of size 240 x 120 pixels. Set the background to
// white (0xffffff). Set both horizontal and vertical grid lines to black (&H0&)
// dotted lines (pattern code 0x0103)
c.setPlotArea(45, 35, 240, 120, "0xffffff", -1, -1, c.dashLineColor("0x000000",
    "0x000103"), c.dashLineColor("0x000000", "0x000103"));

// Add a title to the chart using 10 pts Arial Bold font. Use a 1 x 2 bitmap pattern
// as the background. Set the border to black (0x0).
c.addTitle("Snow Percipitation (Dec 12)", "Arial Bold", 10).setBackground(
    c.patternColor(Array("0xb0b0f0", "0xe0e0ff"), 2), "0x000000");

// Add a title to the y axis
c.yAxis().setTitle("mm per hour");

// Set the labels on the x axis.
c.xAxis().setLabels(labels);

// Display 1 out of 3 labels on the x-axis.
c.xAxis().setLabelStep(3);

// Add an area layer to the chart
layer = c.addAreaLayer();

// Load a snow pattern from an external file "snow.png".
snowPattern = c.patternColor2("snow.png");

// Add a data set to the area layer using the snow pattern as the fill color. Use
// deep blue (0x0000ff) as the area border line color (&H0000ff&)
layer.addDataSet(data).setDataColor(snowPattern, "0x0000ff");

// Set the line width to 2 pixels to highlight the line
layer.setLineWidth(2);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "", "title='{xLabel}:00 - {value} mm/hour'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Pattern Area Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Stacked Area Chart

Stacked Area Chart

This example demonstrates using multiple data sets to create stacked area chart.

The key features demonstrated in this example are:

  • Add a stacked area layer using XYChart.addAreaLayer2 with the Stack predefined constant.

  • Add multiple data sets to the area layer using Layer.addDataSet.

  • Add a legend at the bottom of the chart using BaseChart.addLegend/

  • Set the y-axis label format to "US$nn" using Axis.setLabelFormat.

Source Code Listing

[File: cfdemo/stackedarea.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the area chart
data0 = Array(42, 49, 33, 38, 51, 46, 29, 41, 44, 57, 59, 52, 37, 34, 51, 56, 56, 60,
    70, 76, 63, 67, 75, 64, 51);
data1 = Array(50, 45, 47, 34, 42, 49, 63, 62, 73, 59, 56, 50, 64, 60, 67, 67, 58, 59,
    73, 77, 84, 82, 80, 84, 89);
data2 = Array(61, 79, 85, 66, 53, 39, 24, 21, 37, 56, 37, 22, 21, 33, 13, 17, 4, 23,
    16, 25, 9, 10, 5, 7, 16);
labels = Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12",
    "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24");

// Create a XYChart object of size 300 x 210 pixels. Set the background to pale
// yellow (0xffffc0) with a black border (0x0)
c = cd.XYChart(300, 210, "0xffffc0", "0x000000");

// Set the plotarea at (50, 30) and of size 240 x 140 pixels. Use white (0xffffff)
// background.
c.setPlotArea(50, 30, 240, 140).setBackground("0xffffff");

// Add a legend box at (50, 185) (below of plot area) using horizontal layout. Use 8
// pts Arial font with Transparent background.
c.addLegend(50, 185, False, "", 8).setBackground(cd.Transparent);

// Add a title box to the chart using 8 pts Arial Bold font, with yellow (0xffff40)
// background and a black border (0x0)
c.addTitle("Sales Volume", "Arial Bold", 8).setBackground("0xffff40", 0);

// Set the y axis label format to US$nnnn
c.yAxis().setLabelFormat("US${value}");

// Set the labels on the x axis.
c.xAxis().setLabels(labels);

// Display 1 out of 2 labels on the x-axis. Show minor ticks for remaining labels.
c.xAxis().setLabelStep(2, 1);

// Add an stack area layer with three data sets
layer = c.addAreaLayer2(cd.Stack);
layer.addDataSet(data0, "0x4040ff", "Store ##1");
layer.addDataSet(data1, "0xff4040", "Store ##2");
layer.addDataSet(data2, "0x40ff40", "Store ##3");

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName} sales at hour {xLabel}: US${value}K'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Stacked Area Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


3D Stacked Area Chart

3D Stacked Area Chart

This example demonstrates creating a stacked area chart with 3D effects.

The key features demonstrated in this example are:

  • Add a stacked area layer using XYChart.addAreaLayer2 with the Stack predefined constant.

  • Add multiple data sets to the area layer using Layer.addDataSet.

  • Add a legend to the chart using BaseChart.addLegend

  • Add a title to the y-axis using Axis.setTitle, and draw the title upright (instead of rotated 90 degrees) using TextBox.setFontAngle. Note that the title can contain multiple lines using line break characters.

Source Code Listing

[File: cfdemo/threedstackarea.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the area chart
data0 = Array(42, 49, 33, 38, 51, 46, 29, 41, 44, 57, 59, 52, 37, 34, 51, 56, 56, 60,
    70, 76, 63, 67, 75, 64, 51);
data1 = Array(50, 45, 47, 34, 42, 49, 63, 62, 73, 59, 56, 50, 64, 60, 67, 67, 58, 59,
    73, 77, 84, 82, 80, 84, 89);
data2 = Array(61, 79, 85, 66, 53, 39, 24, 21, 37, 56, 37, 22, 21, 33, 13, 17, 4, 23,
    16, 25, 9, 10, 5, 7, 16);
labels = Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12",
    "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24");

// Create a XYChart object of size 500 x 300 pixels
c = cd.XYChart(500, 300);

// Set the plotarea at (90, 30) and of size 300 x 240 pixels.
c.setPlotArea(90, 30, 300, 240);

// Add a legend box at (405, 100)
c.addLegend(405, 100);

// Add a title to the chart
c.addTitle("Daily System Load");

// Add a title to the y axis. Draw the title upright (font angle = 0)
c.yAxis().setTitle("Database<*br*>Queries<*br*>(per sec)").setFontAngle(0);

// Set the labels on the x axis.
c.xAxis().setLabels(labels);

// Display 1 out of 2 labels on the x-axis. Show minor ticks for remaining labels.
c.xAxis().setLabelStep(2, 1);

// Add an area layer
layer = c.addAreaLayer();

// Draw the area layer in 3D
layer.set3D();

// Add the three data sets to the area layer
layer.addDataSet(data0, -1, "Server ## 1");
layer.addDataSet(data1, -1, "Server ## 2");
layer.addDataSet(data2, -1, "Server ## 3");

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName} load at hour {xLabel}: {value} queries/sec'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    3D Stacked Area Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Percentage Area Chart

Percentage Area Chart

This example demonstrates creating a percentage area chart. It also demonstrates how to include icons in the legend box using CDML.

A percentage area chart is like a stacked area chart, except the areas are individually scaled so that they stacked up to 100.

Note that in this example, the legend box contains icons. This is achieved by including the icons in the data set name using CDML.

The key features demonstrated in this example are:

  • Add a legend to the chart using BaseChart.addLegend, and set the key size (the color box to the right of each legend entry) to 16 x 32 pixels using LegendBox.setKeySize. This is to better match the size of the icons.

  • Reverse the legend box entries using Layer.setLegend, so that the last data set name is on top in the legend box. This is useful for a vertical legend box in a vertical stacked chart with purely positive data. In such case, the last data set will be stacked to the top. Reversing the legend box will make the legend keys visually consistent with the stacking order of the chart.

  • Add a percentage area layer using XYChart.addAreaLayer2 with the Percentage predefined constant.

  • Add multiple data sets to the area layer using Layer.addDataSet, with data set names expressed using CDML to include icons.

Source Code Listing

[File: cfdemo/percentarea.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the area chart
data0 = Array(42, 49, 33, 38, 51, 46, 29, 41, 44, 57, 59, 52, 37, 34, 51, 56, 56, 60,
    70, 76, 63, 67, 75, 64, 51);
data1 = Array(50, 55, 47, 34, 42, 49, 63, 62, 73, 59, 56, 50, 64, 60, 67, 67, 58, 59,
    73, 77, 84, 82, 80, 84, 98);
data2 = Array(87, 89, 85, 66, 53, 39, 24, 21, 37, 56, 37, 23, 21, 33, 13, 17, 14, 23,
    16, 25, 29, 30, 45, 47, 46);

// The timestamps on the x-axis
labels = Array(CreateDate(1996, 1, 1), CreateDate(1996, 4, 1), CreateDate(1996, 7, 1
    ), CreateDate(1996, 10, 1), CreateDate(1997, 1, 1), CreateDate(1997, 4, 1),
    CreateDate(1997, 7, 1), CreateDate(1997, 10, 1), CreateDate(1998, 1, 1),
    CreateDate(1998, 4, 1), CreateDate(1998, 7, 1), CreateDate(1998, 10, 1),
    CreateDate(1999, 1, 1), CreateDate(1999, 4, 1), CreateDate(1999, 7, 1),
    CreateDate(1999, 10, 1), CreateDate(2000, 1, 1), CreateDate(2000, 4, 1),
    CreateDate(2000, 7, 1), CreateDate(2000, 10, 1), CreateDate(2001, 1, 1),
    CreateDate(2001, 4, 1), CreateDate(2001, 7, 1), CreateDate(2001, 10, 1),
    CreateDate(2002, 1, 1));

// Create a XYChart object of size 500 x 280 pixels, using 0xffffcc as background
// color, with a black border, and 1 pixel 3D border effect
c = cd.XYChart(500, 280, "0xffffcc", 0, 1);

// Set search path to current directory for loading icon images
c.setSearchPath(GetPageContext());

// Set the plotarea at (50, 45) and of size 320 x 200 pixels with white background.
// Enable horizontal and vertical grid lines using the grey (0xc0c0c0) color.
c.setPlotArea(50, 45, 320, 200, "0xffffff").setGridColor("0xc0c0c0", "0xc0c0c0");

// Add a legend box at (370, 45) using vertical layout and 8 points Arial Bold font.
legendBox = c.addLegend(370, 45, True, "Arial Bold", 8);

// Set the legend box background and border to transparent
legendBox.setBackground(cd.Transparent, cd.Transparent);

// Set the legend box icon size to 16 x 32 pixels to match with custom icon size
legendBox.setKeySize(16, 32);

// Add a title to the chart using 14 points Times Bold Itatic font and white font
// color, and 0x804020 as the background color
c.addTitle("Quarterly Product Sales", "Times New Roman Bold Italic", 14, "0xffffff"
    ).setBackground("0x804020");

// Set the labels on the x axis.
c.xAxis().setLabels2(labels);

// Set multi-style axis label formatting. Start of year labels are displayed as yyyy.
// For other labels, just show minor tick.
c.xAxis().setMultiFormat(cd.StartOfYearFilter(), "{value|yyyy}", cd.AllPassFilter(),
    "-");

// Add a percentage area layer to the chart
layer = c.addAreaLayer2(cd.Percentage);

// Add the three data sets to the area layer, using icons images with labels as data
// set names
layer.addDataSet(data0, "0x40ddaa77",
    "<*block,valign=absmiddle*><*img=service.png*> Service<*/*>");
layer.addDataSet(data1, "0x40aadd77",
    "<*block,valign=absmiddle*><*img=software.png*> Software<*/*>");
layer.addDataSet(data2, "0x40aa77dd",
    "<*block,valign=absmiddle*><*img=computer.png*> Hardware<*/*>");

// For a vertical stacked chart with positive data only, the last data set is always
// on top. However, in a vertical legend box, the last data set is at the bottom.
// This can be reversed by using the setLegend method.
layer.setLegend(cd.ReverseLegend);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName} sales at {xLabel|yyyy} Q{=({xLabel|m}+2)/3|0}: " &
    "US${value}K ({percent}%)'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Percentage Area Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Depth Area Chart

Depth Area Chart

This example demonstrates using multiple area layers with semi-transparent colors to create a depth area chart.

ChartDirector allows an XYChart to containing multiple layers of the same or different types. In this example, all layers are 3D area layers. The areas are filled using semi-transparent colors to avoid the area on the front hiding the areas at the back.

Source Code Listing

[File: cfdemo/deptharea.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the area chart
data0 = Array(42, 49, 33, 38, 51, 46, 29, 41, 44, 57, 59, 52, 37, 34, 51, 56, 56, 60,
    70, 76, 63, 67, 75, 64, 51);
data1 = Array(50, 55, 47, 34, 42, 49, 63, 62, 73, 59, 56, 50, 64, 60, 67, 67, 58, 59,
    73, 77, 84, 82, 80, 84, 89);
data2 = Array(87, 89, 85, 66, 53, 39, 24, 21, 37, 56, 37, 22, 21, 33, 13, 17, 4, 23,
    16, 25, 9, 10, 5, 7, 6);
labels = Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12",
    "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24");

// Create a XYChart object of size 350 x 230 pixels
c = cd.XYChart(350, 230);

// Set the plotarea at (50, 30) and of size 250 x 150 pixels.
c.setPlotArea(50, 30, 250, 150);

// Add a legend box at (55, 0) (top of the chart) using 8 pts Arial Font. Set
// background and border to Transparent.
c.addLegend(55, 0, False, "", 8).setBackground(cd.Transparent);

// Add a title to the x axis
c.xAxis().setTitle("Network Load for Jun 12");

// Add a title to the y axis
c.yAxis().setTitle("MBytes");

// Set the labels on the x axis.
c.xAxis().setLabels(labels);

// Display 1 out of 2 labels on the x-axis. Show minor ticks for remaining labels.
c.xAxis().setLabelStep(2, 1);

// Add three area layers, each representing one data set. The areas are drawn in
// semi-transparent colors.
c.addAreaLayer(data2, "0x808080ff", "Server ##1", 3);
c.addAreaLayer(data0, "0x80ff0000", "Server ##2", 3);
c.addAreaLayer(data1, "0x8000ff00", "Server ##3", 3);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName} load at hour {xLabel}: {value} MBytes'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Depth Area Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Rotated Area Chart

Rotated Area Chart

This example demonstrates swapping the x and y axes to produce an rotated area chart in which the area goes from left to right (instead of bottom to top).

The x and y axes in the example are configured as follows:

  • Initially, the x-axis is horizontal from left to right at the bottom of the plot area, while the y-axis is vertical from bottom to top at the left side of the plot area.

  • Swap the x and y axes using XYChart.swapXY. Now the x-axis is vertical from bottom to top at the left side of the chart, while the y-axis is horizontal from left to right at the bottom of the chart.

  • Use XYChart.setYAxisOnRight to move the y-axis to the opposite side of the plot area, so that the y-axis is at the top of the plot area. (Note: the "right" word on setYAxisOnRight means the "right" side before "swapXY" rotation. After rotation, the right side will become to top side.)

  • Use Axis.setReverse to reverse the direction of the x-axis, so that the x-axis is vertical from top to bottom (instead of from bottom to top).
The area in this chart is filled using a gradient color created with BaseChart.gradientColor.

Source Code Listing

[File: cfdemo/rotatedarea.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the area chart
data = Array(30, 28, 40, 55, 75, 68, 54, 60, 50, 62, 75, 65, 75, 89, 60, 55, 53, 35,
    50, 66, 56, 48, 52, 65, 62);

// The labels for the area chart
labels = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
    20, 21, 22, 23, 24);

// Create a XYChart object of size 320 x 320 pixels
c = cd.XYChart(320, 320);

// Swap the x and y axis to become a rotated chart
c.swapXY();

// Set the y axis on the top side (right + rotated = top)
c.setYAxisOnRight();

// Reverse the x axis so it is pointing downwards
c.xAxis().setReverse();

// Set the plotarea at (50, 50) and of size 200 x 200 pixels. Enable horizontal and
// vertical grids by setting their colors to grey (0xc0c0c0).
c.setPlotArea(50, 50, 250, 250).setGridColor("0xc0c0c0", "0xc0c0c0");

// Add a line chart layer using the given data
c.addAreaLayer(data, c.gradientColor(50, 0, 300, 0, "0xffffff", "0x0000ff"));

// Set the labels on the x axis. Append "m" after the value to show the unit.
c.xAxis().setLabels2(labels, "{value} m");

// Display 1 out of 3 labels.
c.xAxis().setLabelStep(3);

// Add a title to the x axis
c.xAxis().setTitle("Depth");

// Add a title to the y axis
c.yAxis().setTitle("Carbon Dioxide Concentration (ppm)");

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='Carbon dioxide concentration at {xLabel}: {value} ppm'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Rotated Area Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Floating Box/Waterfall Charts

Floating Box/Waterfall Charts

Title | Description
Box-Whisker Chart | Demonstrates creating a box-whisker chart.
Horizontal Box-Whisker Chart | Demonstrates creating a multi-color horizontal box-whisker chart.
Floating Box Chart | Demonstrates creating a multi-color floating box chart.
Waterfall Chart | Demonstrates creating a multi-color waterfall chart.
Pos/Neg Waterfall Chart | Demonstrates a waterfall chart with positive and negative data shown in different colors.


Box-Whisker Chart

Box-Whisker Chart

This example demonstrates creating a box-whisker chart.

A standard box-whisker chart plots up to 5 data sets using box-whisker symbols. The 5 data sets are sometimes called the maximum, 3rd quartile, median, 1st quartile and minimum, although they can represent any kind of quantities.

In a box-whisker symbol, the 3rd and 1st quartile values are represented as a box. The maximum, minimum and median values are represented as horizontal marks. There is a vertical line joining the maximum and minimum.

In ChartDirector, XYChart.addBoxWhiskerLayer and XYChart.addBoxWhiskerLayer2 may be used to create single-color and multi-color box-whisker layers.

When creating a box-whisker layer, not all 5 data sets need to be present. One common usage is to provide only the 3rd and 1st quartile data (leave other arguments as empty arrays) to draw only the "box" part of the chart. This will result in a floating box chart. Another common usage is to provide only the maximum and minimum values to draw only the "whisker" part of the chart. They are useful as "error symbols". (See Line with Error Symbols for an example.) You may even provide only the median data to draw floating mark lines.

Source Code Listing

[File: cfdemo/boxwhisker.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// Sample data for the Box-Whisker chart. Represents the minimum, 1st quartile,
// medium, 3rd quartile and maximum values of some quantities
Q0Data = Array(40, 45, 40, 30, 20, 50, 25, 44);
Q1Data = Array(55, 60, 50, 40, 38, 60, 51, 60);
Q2Data = Array(62, 70, 60, 50, 48, 70, 62, 70);
Q3Data = Array(70, 80, 65, 60, 53, 78, 69, 76);
Q4Data = Array(80, 90, 75, 70, 60, 85, 80, 84);

// The labels for the chart
labels = Array("Group A", "Group B", "Group C", "Group D", "Group E", "Group F",
    "Group G", "Group H");

// Create a XYChart object of size 550 x 250 pixels
c = cd.XYChart(550, 250);

// Set the plotarea at (50, 25) and of size 450 x 200 pixels. Enable both horizontal
// and vertical grids by setting their colors to grey (0xc0c0c0)
c.setPlotArea(50, 25, 450, 200).setGridColor("0xc0c0c0", "0xc0c0c0");

// Add a title to the chart
c.addTitle("Computer Vision Test Scores");

// Set the labels on the x axis and the font to Arial Bold
c.xAxis().setLabels(labels).setFontStyle("Arial Bold");

// Set the font for the y axis labels to Arial Bold
c.yAxis().setLabelStyle("Arial Bold");

// Add a Box Whisker layer using light blue 0x9999ff as the fill color and blue
// (0xcc) as the line color. Set the line width to 2 pixels
c.addBoxWhiskerLayer(Q3Data, Q1Data, Q4Data, Q0Data, Q2Data, "0x9999ff", "0x0000cc"
    ).setLineWidth(2);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='{xLabel}: min/med/max = {min}/{med}/{max}<*br*>Inter-quartile range: " &
    "{bottom} to {top}'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Box-Whisker Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Horizontal Box-Whisker Chart

Horizontal Box-Whisker Chart

This example demonstrates creating a multi-color horizontal box-whisker chart.

XYChart.addBoxWhiskerLayer2 is used to create the multi-color box-whisker layer. The chart is set to horizontal orientation using XYChart.swapXY.

Source Code Listing

[File: cfdemo/boxwhisker2.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// Sample data for the Box-Whisker chart. Represents the minimum, 1st quartile,
// medium, 3rd quartile and maximum values of some quantities
Q0Data = Array(40, 45, 35);
Q1Data = Array(55, 60, 50);
Q2Data = Array(62, 70, 60);
Q3Data = Array(70, 80, 65);
Q4Data = Array(80, 90, 75);

// The labels for the chart
labels = Array("<*img=robot1.png*><*br*>Bipedal Type",
    "<*img=robot2.png*><*br*>Wolf Type", "<*img=robot5.png*><*br*>Bird Type");

// Create a XYChart object of size 540 x 320 pixels
c = cd.XYChart(540, 320);

// swap the x and y axes to create a horizontal box-whisker chart
c.swapXY();

// Set search path to current directory for loading icon images
c.setSearchPath(GetPageContext());

// Set the plotarea at (75, 25) and of size 440 x 270 pixels. Enable both horizontal
// and vertical grids by setting their colors to grey (0xc0c0c0)
c.setPlotArea(75, 25, 440, 270).setGridColor("0xc0c0c0", "0xc0c0c0");

// Add a title to the chart
c.addTitle("           Robot Shooting Accuracy Scores");

// Set the labels on the x axis and the font to Arial Bold
c.xAxis().setLabels(labels).setFontStyle("Arial Bold");

// Disable x axis ticks by setting the length to 0
c.xAxis().setTickLength(0);

// Set the font for the y axis labels to Arial Bold
c.yAxis().setLabelStyle("Arial Bold");

// Add a Box Whisker layer using light blue 0x9999ff as the fill color and blue
// (0xcc) as the line color. Set the line width to 2 pixels
c.addBoxWhiskerLayer2(Q3Data, Q1Data, Q4Data, Q0Data, Q2Data).setLineWidth(2);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='{xLabel}: min/med/max = {min}/{med}/{max}<*br*>Inter-quartile range: " &
    "{bottom} to {top}'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Box-Whisker Chart (2)
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Floating Box Chart

Floating Box Chart

This example demonstrates creating a multi-color floating box chart.

This chart is composed of 4 box-whisker layers, created using XYChart.addBoxWhiskerLayer. Each layer handles boxes of one color. Only the "box" part of the box-whisker layer is used.

Source Code Listing

[File: cfdemo/floatingbox.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// Sample data for the Box-Whisker chart. Represents the minimum, 1st quartile,
// medium, 3rd quartile and maximum values of some quantities
Q0Data = Array(40, 45, 40, 30, 20, 50, 25, 44);
Q1Data = Array(55, 60, 50, 40, 38, 60, 51, 60);
Q2Data = Array(62, 70, 60, 50, 48, 70, 62, 70);
Q3Data = Array(70, 80, 65, 60, 53, 78, 69, 76);
Q4Data = Array(80, 90, 75, 70, 60, 85, 80, 84);

// The labels for the chart
labels = Array("Group A", "Group B", "Group C", "Group D", "Group E", "Group F",
    "Group G", "Group H");

// Create a XYChart object of size 550 x 250 pixels
c = cd.XYChart(550, 275);

// Set the plotarea at (50, 25) and of size 450 x 200 pixels. Enable both horizontal
// and vertical grids by setting their colors to grey (0xc0c0c0)
c.setPlotArea(50, 50, 450, 200).setGridColor("0xc0c0c0", "0xc0c0c0");

// Add a title to the chart
c.addTitle("Computer Vision Test Scores");

// Set the labels on the x axis and the font to Arial Bold
c.xAxis().setLabels(labels).setFontStyle("Arial Bold");

// Set the font for the y axis labels to Arial Bold
c.yAxis().setLabelStyle("Arial Bold");

// Add a Box Whisker layer using light blue 0x9999ff as the fill color and blue
// (0xcc) as the line color. Set the line width to 2 pixels
c.addBoxLayer(Q4Data, Q3Data, "0x00ff00", "Top 25%");
c.addBoxLayer(Q3Data, Q2Data, "0x9999ff", "25% - 50%");
c.addBoxLayer(Q2Data, Q1Data, "0xffff00", "50% - 75%");
c.addBoxLayer(Q1Data, Q0Data, "0xff0000", "Bottom 25%");

// Add legend box at top center above the plot area using 10 pts Arial Bold Font
b = c.addLegend(50 + 225, 22, False, "Arial Bold", 10);
b.setAlignment(cd.TopCenter);
b.setBackground(cd.Transparent);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='{xLabel} ({dataSetName}): {bottom} to {top} points'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Floating Box Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Waterfall Chart

Waterfall Chart

This example demonstrates creating a multi-color waterfall chart.

This chart is created as a multi-color box-whisker layer using XYChart.addBoxWhiskerLayer2. Only the "box" part of the box-whisker layer is used.

The top-edges of the boxes are obtained by accumulating the raw data using the ArrayMath utility. The bottom-edges of the boxes are simply the top-edges of previous boxes, with the exception of the last "total" box which always starts at 0.

Source Code Listing

[File: cfdemo/waterfall.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// 4 data points to represent the cash flow for the Q1 - Q4
data = Array(230, 140, 220, 330, 150);

// We want to plot a waterfall chart showing the 4 quarters as well as the total
labels = Array("Product 1", "Product 2", "Product 3", "Product 4", "Product 5",
    "Total");

// The top side of the bars in a waterfall chart is the accumulated data. We use the
// ChartDirector ArrayMath utility to accumulate the data. The "total" is handled by
// inserting a zero point at the end before accumulation (after accumulation it will
// become the total).
boxTop = cd.ArrayMath(data).insert2(0, 1).acc().result();

// The botom side of the bars is just the top side of the previous bar. So we shifted
// the top side data to obtain the bottom side data.
boxBottom = cd.ArrayMath(boxTop).shift(1, 0).result();

// The last point (total) is different. Its bottom side is always 0.
boxBottom[ArrayLen(boxBottom)] = 0;

// Create a XYChart object of size 500 x 280 pixels. Set background color to light
// blue (ccccff), with 1 pixel 3D border effect.
c = cd.XYChart(500, 290, "0xccccff", "0x000000", 1);

// Add a title to the chart using 13 points Arial Bold Itatic font, with white
// (ffffff) text on a deep blue (0x80) background
c.addTitle("Product Revenue - Year 2004", "Arial Bold Italic", 13, "0xffffff"
    ).setBackground("0x000080");

// Set the plotarea at (55, 50) and of size 430 x 215 pixels. Use alternative
// white/grey background.
c.setPlotArea(55, 45, 430, 215, "0xffffff", "0xeeeeee");

// Set the labels on the x axis using Arial Bold font
c.xAxis().setLabels(labels).setFontStyle("Arial Bold");

// Set the x-axis ticks and grid lines to be between the bars
c.xAxis().setTickOffset(0.5);

// Use Arial Bold as the y axis label font
c.yAxis().setLabelStyle("Arial Bold");

// Add a title to the y axis
c.yAxis().setTitle("USD (in millions)");

// Add a multi-color box-whisker layer to represent the waterfall bars
layer = c.addBoxWhiskerLayer2(boxTop, boxBottom);

// Put data labels on the bars to show the cash flow using Arial Bold font
layer.setDataLabelFormat("{={top}-{bottom}}M");
layer.setDataLabelStyle("Arial Bold").setAlignment(cd.Center);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "", "title='{xLabel}: {={top}-{bottom}} millions'")
    ;

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Waterfall Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Pos/Neg Waterfall Chart

Pos/Neg Waterfall Chart

This example demonstrates a waterfall chart with positive and negative data shown in different colors.

This chart is created as a box-whisker layer using XYChart.addBoxWhiskerLayer. Only the "box" part of the box-whisker layer is used.

The top-edges of the boxes are obtained by accumulating the raw data using the ArrayMath utility. The bottom-edges of the boxes are simply the top-edges of previous boxes, with the exception of the last "total" box which always starts at 0.

The color for each box is set using BoxWhiskerLayer.setBoxColor, in which the color depends on whether the top-edge is above or below the bottom-edge (that is, whether the data is positive or negative).

Source Code Listing

[File: cfdemo/posnegwaterfall.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// 4 data points to represent the cash flow for the Q1 - Q4
data = Array(230, -140, 220, 330);

// We want to plot a waterfall chart showing the 4 quarters as well as the total
labels = Array("1st Quarter", "2nd Quarter", "3rd Quarter", "4th Quarter", "Total");

// The top side of the bars in a waterfall chart is the accumulated data. We use the
// ChartDirector ArrayMath utility to accumulate the data. The "total" is handled by
// inserting a zero point at the end before accumulation (after accumulation it will
// become the total).
boxTop = cd.ArrayMath(data).insert2(0, 1, ArrayLen(data)).acc().result();

// The botom side of the bars is just the top side of the previous bar. So we shifted
// the top side data to obtain the bottom side data.
boxBottom = cd.ArrayMath(boxTop).shift(1, 0).result();

// The last point (total) is different. Its bottom side is always 0.
boxBottom[ArrayLen(boxBottom)] = 0;

// In this example, we want to use different colors depending on the data is positive
// or negative.
posColor = "0x00ff00";
negColor = "0xff0000";

// Create a XYChart object of size 500 x 280 pixels. Set background color to light
// blue (ccccff), with 1 pixel 3D border effect.
c = cd.XYChart(500, 300, "0xccccff", "0x000000", 1);

// Add a title to the chart using 13 points Arial Bold Itatic font, with white
// (ffffff) text on a deep blue (0x80) background
c.addTitle("Corporate Cash Flow - Year 2004", "Arial Bold Italic", 13, "0xffffff"
    ).setBackground("0x000080");

// Set the plotarea at (55, 50) and of size 430 x 215 pixels. Use alternative
// white/grey background.
c.setPlotArea(55, 50, 430, 215, "0xffffff", "0xeeeeee");

// Add a legend box at (55, 25) using 8 pts Arial Bold font with horizontal layout,
// with transparent background and border color.
b = c.addLegend(55, 25, False, "Arial Bold", 8);
b.setBackground(cd.Transparent, cd.Transparent);

// Add keys to show the colors for positive and negative cash flows
b.addKey("Positive Cash Flow", posColor);
b.addKey("Negative Cash Flow", negColor);

// Set the labels on the x axis using Arial Bold font
c.xAxis().setLabels(labels).setFontStyle("Arial Bold");

// Set the x-axis ticks and grid lines to be between the bars
c.xAxis().setTickOffset(0.5);

// Use Arial Bold as the y axis label font
c.yAxis().setLabelStyle("Arial Bold");

// Add a title to the y axis
c.yAxis().setTitle("USD (in millions)");

// Add a box-whisker layer to represent the waterfall bars
layer = c.addBoxWhiskerLayer(boxTop, boxBottom);

// Color the bars depending on whether it is positive or negative
for (i = 0; i LT ArrayLen(boxTop); i = i + 1) {
    if (boxTop[i + 1] GTE boxBottom[i + 1]) {
        layer.setBoxColor(i, posColor);
    } else {
        layer.setBoxColor(i, negColor);
    }
}

// Put data labels on the bars to show the cash flow using Arial Bold font
layer.setDataLabelFormat("{={top}-{bottom}}M");
layer.setDataLabelStyle("Arial Bold").setAlignment(cd.Center);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "", "title='{xLabel}: {={top}-{bottom}} millions'")
    ;

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Pos/Neg Waterfall Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Gantt Charts

Gantt Charts

Title | Description
Simple Gantt Chart | Demonstrates a simple gantt chart.
Multi-Color Gantt Chart | Demonstrates a multi-color gantt chart with milestone symbols.
Multi-Layer Gantt Chart | Demonstrates a gantt chart containing two layers for the planned and actual dates.


Simple Gantt Chart

Simple Gantt Chart

This example demonstrates a simple gantt chart.

This chart is created by using a horizontal box-whisker layer, in which only the "box" part of the box-whisker layer is used. Date/time values are used as box data, resulting in a gantt chart.

The key features demonstrated in this example are:

  • Create the box-whisker layer using XYChart.addBoxWhiskerLayer, in which the data arrays are dates.

  • Swap the x-axis and y-axis using XYChart.swapXY, so the chart is using a horizontal orientation.

  • Use XYChart.setYAxisOnRight to move the y-axis to the opposite side of the plot area, so that the y-axis is at the top of the plot area. (Note: the "right" word on setYAxisOnRight means the "right" side before "swapXY" rotation. After rotation, the right side will become to top side.)

  • Use Axis.setReverse to reverse the direction of the x-axis, so that the x-axis is vertical from top to bottom (instead of from bottom to top).

  • Set the y-axis to date scale using Axis.setDateScale.

  • Set multi-format axis labels for the y-axis using Axis.setMultiFormat. Note that the labels for the first week of the month are in bold, with the month name shown. The other labels just show the day.

  • Use alternative background colors for the plot area by providing two background colors when calling XYChart.setPlotArea.

Source Code Listing

[File: cfdemo/gantt.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// data for the gantt chart, representing the start date, end date and names for
// various activities
startDate = Array(CreateDate(2004, 8, 16), CreateDate(2004, 8, 30), CreateDate(2004,
    9, 13), CreateDate(2004, 9, 20), CreateDate(2004, 9, 27), CreateDate(2004, 10, 4
    ), CreateDate(2004, 10, 25), CreateDate(2004, 11, 1), CreateDate(2004, 11, 8));
endDate = Array(CreateDate(2004, 8, 30), CreateDate(2004, 9, 13), CreateDate(2004, 9,
    27), CreateDate(2004, 10, 4), CreateDate(2004, 10, 11), CreateDate(2004, 11, 8),
    CreateDate(2004, 11, 8), CreateDate(2004, 11, 22), CreateDate(2004, 11, 22));
labels = Array("Market Research", "Define Specifications", "Overall Archiecture",
    "Project Planning", "Detail Design", "Software Development", "Test Plan",
    "Testing and QA", "User Documentation");

// Create a XYChart object of size 620 x 280 pixels. Set background color to light
// blue (ccccff), with 1 pixel 3D border effect.
c = cd.XYChart(620, 280, "0xccccff", "0x000000", 1);

// Add a title to the chart using 15 points Times Bold Itatic font, with white
// (ffffff) text on a deep blue (000080) background
c.addTitle("Simple Gantt Chart Demo", "Times New Roman Bold Italic", 15, "0xffffff"
    ).setBackground("0x000080");

// Set the plotarea at (140, 55) and of size 460 x 200 pixels. Use alternative
// white/grey background. Enable both horizontal and vertical grids by setting their
// colors to grey (c0c0c0). Set vertical major grid (represents month boundaries) 2
// pixels in width
c.setPlotArea(140, 55, 460, 200, "0xffffff", "0xeeeeee", cd.LineColor, "0xc0c0c0",
    "0xc0c0c0").setGridWidth(2, 1, 1, 1);

// swap the x and y axes to create a horziontal box-whisker chart
c.swapXY();

// Set the y-axis scale to be date scale from Aug 16, 2004 to Nov 22, 2004, with
// ticks every 7 days (1 week)
c.yAxis().setDateScale(CreateDate(2004, 8, 16), CreateDate(2004, 11, 22), 86400 * 7);

// Set multi-style axis label formatting. Month labels are in Arial Bold font in "mmm
// d" format. Weekly labels just show the day of month and use minor tick (by using
// '-' as first character of format string).
c.yAxis().setMultiFormat(cd.StartOfMonthFilter(), "<*font=Arial Bold*>{value|mmm d}",
    cd.StartOfDayFilter(), "-{value|d}");

// Set the y-axis to shown on the top (right + swapXY = top)
c.setYAxisOnRight();

// Set the labels on the x axis
c.xAxis().setLabels(labels);

// Reverse the x-axis scale so that it points downwards.
c.xAxis().setReverse();

// Set the horizontal ticks and grid lines to be between the bars
c.xAxis().setTickOffset(0.5);

// Add a green (33ff33) box-whisker layer showing the box only.
c.addBoxWhiskerLayer(startDate, endDate, Array(), Array(), Array(), "0x00cc00",
    cd.SameAsMainColor, cd.SameAsMainColor);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='{xLabel}: {top|mmm dd, yyyy} to {bottom|mmm dd, yyyy}'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Simple Gantt Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Multi-Color Gantt Chart

Multi-Color Gantt Chart

This example demonstrates a multi-color gantt chart with milestone symbols.

The bars in this chart come from a multi-color box-whisker layer created using XYChart.addBoxWhiskerLayer2. The scatter symbols come from scatter layers created using XYChart.addScatterLayer.

In this example, a data series is used to specify the task number of the bars. This allows multiple bars to associated with the same task. The task numbers act as the x-coordinates of the bars and are set to the box-whisker layer using Layer.setXData. Another data series is used to specify the colors of the bars. This allows the bars to have different colors.

Source Code Listing

[File: cfdemo/colorgantt.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The tasks for the gantt chart
labels = Array("Market Research", "Define Specifications", "Overall Archiecture",
    "Project Planning", "Detail Design", "Software Development", "Test Plan",
    "Testing and QA", "User Documentation");

// The task index, start date, end date and color for each bar
taskNo = Array(0, 0, 1, 2, 3, 4, 5, 6, 6, 7, 8, 8);
startDate = Array(CreateDate(2004, 8, 16), CreateDate(2004, 10, 4), CreateDate(2004,
    8, 30), CreateDate(2004, 9, 13), CreateDate(2004, 9, 20), CreateDate(2004, 9, 27
    ), CreateDate(2004, 10, 4), CreateDate(2004, 10, 4), CreateDate(2004, 10, 25),
    CreateDate(2004, 11, 1), CreateDate(2004, 10, 18), CreateDate(2004, 11, 8));
endDate = Array(CreateDate(2004, 8, 30), CreateDate(2004, 10, 18), CreateDate(2004,
    9, 13), CreateDate(2004, 9, 27), CreateDate(2004, 10, 4), CreateDate(2004, 10, 11
    ), CreateDate(2004, 11, 8), CreateDate(2004, 10, 18), CreateDate(2004, 11, 8),
    CreateDate(2004, 11, 22), CreateDate(2004, 11, 1), CreateDate(2004, 11, 22));
colors = Array("0x00cc00", "0x00cc00", "0x00cc00", "0x0000cc", "0x0000cc",
    "0xcc0000", "0xcc0000", "0x0000cc", "0xcc0000", "0xcc0000", "0x00cc00",
    "0xcc0000");

// Create a XYChart object of size 620 x 325 pixels. Set background color to light
// red (0xffcccc), with 1 pixel 3D border effect.
c = cd.XYChart(620, 325, "0xffcccc", "0x000000", 1);

// Add a title to the chart using 15 points Times Bold Itatic font, with white
// (ffffff) text on a dark red (800000) background
c.addTitle("Mutli-Color Gantt Chart Demo", "Times New Roman Bold Italic", 15,
    "0xffffff").setBackground("0x800000");

// Set the plotarea at (140, 55) and of size 460 x 200 pixels. Use alternative
// white/grey background. Enable both horizontal and vertical grids by setting their
// colors to grey (c0c0c0). Set vertical major grid (represents month boundaries) 2
// pixels in width
c.setPlotArea(140, 55, 460, 200, "0xffffff", "0xeeeeee", cd.LineColor, "0xc0c0c0",
    "0xc0c0c0").setGridWidth(2, 1, 1, 1);

// swap the x and y axes to create a horziontal box-whisker chart
c.swapXY();

// Set the y-axis scale to be date scale from Aug 16, 2004 to Nov 22, 2004, with
// ticks every 7 days (1 week)
c.yAxis().setDateScale(CreateDate(2004, 8, 16), CreateDate(2004, 11, 22), 86400 * 7);

// Set multi-style axis label formatting. Month labels are in Arial Bold font in "mmm
// d" format. Weekly labels just show the day of month and use minor tick (by using
// '-' as first character of format string).
c.yAxis().setMultiFormat(cd.StartOfMonthFilter(), "<*font=Arial Bold*>{value|mmm d}",
    cd.StartOfDayFilter(), "-{value|d}");

// Set the y-axis to shown on the top (right + swapXY = top)
c.setYAxisOnRight();

// Set the labels on the x axis
c.xAxis().setLabels(labels);

// Reverse the x-axis scale so that it points downwards.
c.xAxis().setReverse();

// Set the horizontal ticks and grid lines to be between the bars
c.xAxis().setTickOffset(0.5);

// Add some symbols to the chart to represent milestones. The symbols are added using
// scatter layers. We need to specify the task index, date, name, symbol shape, size
// and color.
c.addScatterLayer(Array(1), Array(CreateDate(2004, 9, 13)), "Milestone 1",
    cd.Cross2Shape(), 13, "0xffff00").setHTMLImageMap("{disable}");
c.addScatterLayer(Array(3), Array(CreateDate(2004, 10, 4)), "Milestone 2",
    cd.StarShape(5), 15, "0xff00ff").setHTMLImageMap("{disable}");
c.addScatterLayer(Array(5), Array(CreateDate(2004, 11, 8)), "Milestone 3",
    cd.TriangleSymbol, 13, "0xff9933").setHTMLImageMap("{disable}");

// Add a multi-color box-whisker layer to represent the gantt bars
layer = c.addBoxWhiskerLayer2(startDate, endDate, Array(), Array(), Array(), colors);
layer.setXData(taskNo);
layer.setBorderColor(cd.SameAsMainColor);

// Divide the plot area height ( = 200 in this chart) by the number of tasks to get
// the height of each slot. Use 80% of that as the bar height.
layer.setDataWidth(Int(200 * 4 / 5 / ArrayLen(labels)));

// Add a legend box at (140, 265) - bottom of the plot area. Use 8 pts Arial Bold as
// the font with auto-grid layout. Set the width to the same width as the plot area.
// Set the backgorund to grey (dddddd).
legendBox = c.addLegend2(140, 265, cd.AutoGrid, "Arial Bold", 8);
legendBox.setWidth(461);
legendBox.setBackground("0xdddddd");

// The keys for the scatter layers (milestone symbols) will automatically be added to
// the legend box. We just need to add keys to show the meanings of the bar colors.
legendBox.addKey("Market Team", "0x00cc00");
legendBox.addKey("Planning Team", "0x0000cc");
legendBox.addKey("Development Team", "0xcc0000");

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='{xLabel}: {top|mmm dd, yyyy} to {bottom|mmm dd, yyyy}'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Multi-Color Gantt Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Multi-Layer Gantt Chart

Multi-Layer Gantt Chart

This example demonstrates a gantt chart containing two layers for the planned and actual dates.

The two layers are created using XYChart.addBoxWhiskerLayer. The bar width of the top layer is set using BaseBoxLayer.setDataWidth to a narrow width so that it will not block the bottom layer.

In this example, the color of the top layer is a pattern color created using an 4 x 4 in-memory pattern with BaseChart.patternColor.

Source Code Listing

[File: cfdemo/layergantt.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// the names of the tasks
labels = Array("Market Research", "Define Specifications", "Overall Archiecture",
    "Project Planning", "Detail Design", "Software Development", "Test Plan",
    "Testing and QA", "User Documentation");

// the planned start dates and end dates for the tasks
startDate = Array(CreateDate(2004, 8, 16), CreateDate(2004, 8, 30), CreateDate(2004,
    9, 13), CreateDate(2004, 9, 20), CreateDate(2004, 9, 27), CreateDate(2004, 10, 4
    ), CreateDate(2004, 10, 25), CreateDate(2004, 11, 1), CreateDate(2004, 11, 8));
endDate = Array(CreateDate(2004, 8, 30), CreateDate(2004, 9, 13), CreateDate(2004, 9,
    27), CreateDate(2004, 10, 4), CreateDate(2004, 10, 11), CreateDate(2004, 11, 8),
    CreateDate(2004, 11, 8), CreateDate(2004, 11, 22), CreateDate(2004, 11, 22));

// the actual start dates and end dates for the tasks up to now
actualStartDate = Array(CreateDate(2004, 8, 16), CreateDate(2004, 8, 27), CreateDate(
    2004, 9, 9), CreateDate(2004, 9, 18), CreateDate(2004, 9, 22));
actualEndDate = Array(CreateDate(2004, 8, 27), CreateDate(2004, 9, 9), CreateDate(
    2004, 9, 27), CreateDate(2004, 10, 2), CreateDate(2004, 10, 8));

// Create a XYChart object of size 620 x 280 pixels. Set background color to light
// green (ccffcc) with 1 pixel 3D border effect.
c = cd.XYChart(620, 280, "0xccffcc", "0x000000", 1);

// Add a title to the chart using 15 points Times Bold Itatic font, with white
// (ffffff) text on a dark green (0x6000) background
c.addTitle("Mutli-Layer Gantt Chart Demo", "Times New Roman Bold Italic", 15,
    "0xffffff").setBackground("0x006000");

// Set the plotarea at (140, 55) and of size 460 x 200 pixels. Use alternative
// white/grey background. Enable both horizontal and vertical grids by setting their
// colors to grey (c0c0c0). Set vertical major grid (represents month boundaries) 2
// pixels in width
c.setPlotArea(140, 55, 460, 200, "0xffffff", "0xeeeeee", cd.LineColor, "0xc0c0c0",
    "0xc0c0c0").setGridWidth(2, 1, 1, 1);

// swap the x and y axes to create a horziontal box-whisker chart
c.swapXY();

// Set the y-axis scale to be date scale from Aug 16, 2004 to Nov 22, 2004, with
// ticks every 7 days (1 week)
c.yAxis().setDateScale(CreateDate(2004, 8, 16), CreateDate(2004, 11, 22), 86400 * 7);

// Add a red (ff0000) dash line to represent the current day
c.yAxis().addMark(CreateDate(2004, 10, 8), c.dashLineColor("0xff0000", cd.DashLine));

// Set multi-style axis label formatting. Month labels are in Arial Bold font in "mmm
// d" format. Weekly labels just show the day of month and use minor tick (by using
// '-' as first character of format string).
c.yAxis().setMultiFormat(cd.StartOfMonthFilter(), "<*font=Arial Bold*>{value|mmm d}",
    cd.StartOfDayFilter(), "-{value|d}");

// Set the y-axis to shown on the top (right + swapXY = top)
c.setYAxisOnRight();

// Set the labels on the x axis
c.xAxis().setLabels(labels);

// Reverse the x-axis scale so that it points downwards.
c.xAxis().setReverse();

// Set the horizontal ticks and grid lines to be between the bars
c.xAxis().setTickOffset(0.5);

// Use blue (0000aa) as the color for the planned schedule
plannedColor = "0x0000aa";

// Use a red hash pattern as the color for the actual dates. The pattern is created
// as a 4 x 4 bitmap defined in memory as an array of colors.
actualColor = c.patternColor(Array("0xffffff", "0xffffff", "0xffffff", "0xff0000",
    "0xffffff", "0xffffff", "0xff0000", "0xffffff", "0xffffff", "0xff0000",
    "0xffffff", "0xffffff", "0xff0000", "0xffffff", "0xffffff", "0xffffff"), 4);

// Add a box whisker layer to represent the actual dates. We add the actual dates
// layer first, so it will be the top layer.
actualLayer = c.addBoxLayer(actualStartDate, actualEndDate, actualColor, "Actual");

// Set the bar height to 8 pixels so they will not block the bottom bar
actualLayer.setDataWidth(8);

// Add a box-whisker layer to represent the planned schedule date
c.addBoxLayer(startDate, endDate, plannedColor, "Planned").setBorderColor(
    cd.SameAsMainColor);

// Add a legend box on the top right corner (595, 60) of the plot area with 8 pt
// Arial Bold font. Use a semi-transparent grey (80808080) background.
b = c.addLegend(595, 60, False, "Arial Bold", 8);
b.setAlignment(cd.TopRight);
b.setBackground("0x80808080", -1, 2);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='{xLabel} ({dataSetName}): {top|mmm dd, yyyy} to {bottom|mmm dd, yyyy}'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Multi-Layer Gantt Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Finance Charts

Finance Charts

Title | Description
High-Low-Open-Close Chart | Demonstrates a multi-color high-low-open-close chart.
Candlestick Chart | Demonstrates a candlestick chart.
Finance Chart (1) | Demonstrate creating a full-featured finance chart, with HLOC, moving averages, Bollinger band, volume bars, RSI and Momentum indicators.
Finance Chart (2) | Demonstrate creating a full-featured finance chart, with candlesticks, moving averages, Donchian channel, volume bars, MACD and Stochastic indicators.
Interactive Financial Chart | Demonstrates a full-featured financial chart in which the user can select the time ranges, technical indicators, and various chart options.


High-Low-Open-Close Chart

High-Low-Open-Close Chart

This example demonstrates a multi-color high-low-open-close chart.

  • Create a HLOC layer using XYChart.addHLOCLayer.

  • Add custom text to the top left corner of the plot area using BaseChart.addText.

  • Draw the y-axis on the right using XYChart.setYAxisOnRight.

  • Rotate the x-axis labels by 45 degrees using TextBox.setFontAngle of the TextBox object that represents the axis label prototype (returned from Axis.setLabels).

Source Code Listing

[File: cfdemo/hloc.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

//
// Sample data for the HLOC chart.
//
highData = Array(2043, 2039, 2076, 2064, 2048, 2058, 2070, 2033, 2027, 2029, 2071,
    2085, 2034, 2031, 2056, 2128, 2180, 2183, 2192, 2213, 2230, 2281, 2272);

lowData = Array(1931, 1921, 1985, 2028, 1986, 1994, 1999, 1958, 1943, 1944, 1962,
    2011, 1975, 1962, 1928, 2059, 2112, 2103, 2151, 2127, 2123, 2152, 2212);

openData = Array(2000, 1957, 1993, 2037, 2018, 2021, 2045, 2009, 1959, 1985, 2008,
    2048, 2006, 2010, 1971, 2080, 2116, 2137, 2170, 2172, 2171, 2191, 2240);

closeData = Array(1950, 1991, 2026, 2029, 2004, 2053, 2011, 1962, 1987, 2019, 2040,
    2016, 1996, 1985, 2006, 2113, 2142, 2167, 2158, 2201, 2188, 2231, 2242);

// The labels for the HLOC chart
labels = Array("Mon 1", "Tue 2", "Wed 3", "Thu 4", "Fri 5", "Mon 8", "Tue 9",
    "Wed 10", "Thu 11", "Fri 12", "Mon 15", "Tue 16", "Wed 17", "Thu 18", "Fri 19",
    "Mon 22", "Tue 23", "Wed 24", "Thu 25", "Fri 26", "Mon 29", "Tue 30", "Wed 31");

// Create a XYChart object of size 600 x 350 pixels
c = cd.XYChart(600, 350);

// Set the plotarea at (50, 25) and of size 500 x 250 pixels. Enable both the
// horizontal and vertical grids by setting their colors to grey (0xc0c0c0)
c.setPlotArea(50, 25, 500, 250).setGridColor("0xc0c0c0", "0xc0c0c0");

// Add a title to the chart
c.addTitle("Universal Stock Index on Jan 2001");

// Add a custom text at (50, 25) (the upper left corner of the plotarea). Use 12 pts
// Arial Bold/blue (4040c0) as the font.
c.addText(50, 25, "(c) Global XYZ ABC Company", "Arial Bold", 12, "0x4040c0");

// Add a title to the x axis
c.xAxis().setTitle("Jan 2001");

// Set the labels on the x axis. Rotate the labels by 45 degrees.
c.xAxis().setLabels(labels).setFontAngle(45);

// Add a title to the y axis
c.yAxis().setTitle("Universal Stock Index");

// Draw the y axis on the right hand side of the plot area
c.setYAxisOnRight(True);

// Add a HLOC layer to the chart using green (008000) for up days and red (ff0000)
// for down days
layer = c.addHLOCLayer3(highData, lowData, openData, closeData, "0x008000",
    "0xff0000");

// Set the line width to 2 pixels
layer.setLineWidth(2);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='{xLabel} Jan 2001<*br*>High:{high}<*br*>Open:{open}<*br*>" &
    "Close:{close}<*br*>Low:{low}'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Simple HLOC Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Candlestick Chart

Candlestick Chart

This example demonstrates a candlestick chart.

  • Create a candlestick layer using XYChart.addCandleStickLayer.

  • Add custom text to the top left corner of the plot area using BaseChart.addText.

  • Draw the y-axis on the right using XYChart.setYAxisOnRight.

  • Rotate the x-axis labels by 45 degrees using TextBox.setFontAngle of the TextBox object that represents the axis label prototype (returned from Axis.setLabels).

Source Code Listing

[File: cfdemo/candlestick.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

//
// Sample data for the CandleStick chart.
//
highData = Array(2043, 2039, 2076, 2064, 2048, 2058, 2070, 2033, 2027, 2029, 2071,
    2085, 2034, 2031, 2056, 2128, 2180, 2183, 2192, 2213, 2230, 2281, 2272);

lowData = Array(1931, 1921, 1985, 2028, 1986, 1994, 1999, 1958, 1943, 1944, 1962,
    2011, 1975, 1962, 1928, 2059, 2112, 2103, 2151, 2127, 2123, 2152, 2212);

openData = Array(2000, 1957, 1993, 2037, 2018, 2021, 2045, 2009, 1959, 1985, 2008,
    2048, 2006, 2010, 1971, 2080, 2116, 2137, 2170, 2172, 2171, 2191, 2240);

closeData = Array(1950, 1991, 2026, 2029, 2004, 2053, 2011, 1962, 1987, 2019, 2040,
    2016, 1996, 1985, 2006, 2113, 2142, 2167, 2158, 2201, 2188, 2231, 2242);

// The labels for the CandleStick chart
labels = Array("Mon 1", "Tue 2", "Wed 3", "Thu 4", "Fri 5", "Mon 8", "Tue 9",
    "Wed 10", "Thu 11", "Fri 12", "Mon 15", "Tue 16", "Wed 17", "Thu 18", "Fri 19",
    "Mon 22", "Tue 23", "Wed 24", "Thu 25", "Fri 26", "Mon 29", "Tue 30", "Wed 31");

// Create a XYChart object of size 600 x 350 pixels
c = cd.XYChart(600, 350);

// Set the plotarea at (50, 25) and of size 500 x 250 pixels. Enable both the
// horizontal and vertical grids by setting their colors to grey (0xc0c0c0)
c.setPlotArea(50, 25, 500, 250).setGridColor("0xc0c0c0", "0xc0c0c0");

// Add a title to the chart
c.addTitle("Universal Stock Index on Jan 2001");

// Add a custom text at (50, 25) (the upper left corner of the plotarea). Use 12 pts
// Arial Bold/blue (4040c0) as the font.
c.addText(50, 25, "(c) Global XYZ ABC Company", "Arial Bold", 12, "0x4040c0");

// Add a title to the x axis
c.xAxis().setTitle("Jan 2001");

// Set the labels on the x axis. Rotate the labels by 45 degrees.
c.xAxis().setLabels(labels).setFontAngle(45);

// Add a title to the y axis
c.yAxis().setTitle("Universal Stock Index");

// Draw the y axis on the right hand side of the plot area
c.setYAxisOnRight(True);

// Reserve 10% margin at the top and bottom of the plot area during auto-scaling.
// This is to leave space for the high and low data labels.
c.yAxis().setAutoScale(0.1, 0.1);

// Add a CandleStick layer to the chart using green (00ff00) for up candles and red
// (ff0000) for down candles
layer = c.addCandleStickLayer(highData, lowData, openData, closeData, "0x00ff00",
    "0xff0000");

// Set the line width to 2 pixels
layer.setLineWidth(2);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='{xLabel} Jan 2001<*br*>High:{high}<*br*>Open:{open}<*br*>" &
    "Close:{close}<*br*>Low:{low}'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Simple Candlestick Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Finance Chart (1)

Finance Chart (1)

This example demonstrate creating a full-featured finance chart, with HLOC, moving averages, Bollinger band, volume bars, RSI and Momentum indicators.

This example employs the FinanceChart library add-on to allow complex financial charts to be composed easily. In this example, the key steps are:

  • Create a new FinanceChart object

  • Set data into the chart using FinanceChart.setData

  • Add the main chart using FinanceChart.addMainChart

  • Add simple moving average lines to the main chart using FinanceChart.addSimpleMovingAvg

  • Add HLOC symbols to the main chart using FinanceChart.addHLOC

  • Add Bollinger Band to the main chart using FinanceChart.addBollingerBand

  • Add volume bars to the main chart using FinanceChart.addVolBars

  • Add an additional RSI indicator chart using FinanceChart.addRSI

  • Add an additional Momentum indicator chart using FinanceChart.addMomentum
For simplicity and to allow this example to run without connecting to a real database, a RanTable object is used to simulate the data. RanTable is a ChartDirector utility class used for creating tables with random numbers.

Source Code Listing

[File: cfdemo/finance.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// Create a finance chart demo containing 100 days of data
noOfDays = 100;

// To compute moving averages starting from the first day, we need to get extra data
// points before the first day
extraDays = 30;

// In this exammple, we use a random number generator utility to simulate the data.
// We set up the random table to create 6 cols x (noOfDays + extraDays) rows, using 9
// as the seed.
rantable = cd.RanTable(9, 6, noOfDays + extraDays);

// Set the 1st col to be the timeStamp, starting from Sep 4, 2002, with each row
// representing one day, and counting week days only (jump over Sat and Sun)
rantable.setDateCol(0, CreateDate(2002, 9, 4), 86400, True);

// Set the 2nd, 3rd, 4th and 5th columns to be high, low, open and close data. The
// open value starts from 100, and the daily change is random from -5 to 5.
rantable.setHLOCCols(1, 100, -5, 5);

// Set the 6th column as the vol data from 5 to 25 million
rantable.setCol(5, 50000000, 250000000);

// Now we read the data from the table into arrays
timeStamps = rantable.getCol(0);
highData = rantable.getCol(1);
lowData = rantable.getCol(2);
openData = rantable.getCol(3);
closeData = rantable.getCol(4);
volData = rantable.getCol(5);

// Create a FinanceChart object of width 600 pixels
c = cd.FinanceChart(600);

// Add a title to the chart
c.addTitle("Finance Chart Demonstration");

// Set the data into the finance chart object
c.setData(timeStamps, highData, lowData, openData, closeData, volData, extraDays);

// Add the main chart with 210 pixels in height
c.addMainChart(210);

// Add a 5 period simple moving average to the main chart, using brown color
c.addSimpleMovingAvg(5, "0x663300");

// Add a 20 period simple moving average to the main chart, using purple color
c.addSimpleMovingAvg(20, "0x9900ff");

// Add an HLOC symbols to the main chart, using green/red for up/down days
c.addHLOC("0x008000", "0xcc0000");

// Add 20 days bollinger band to the main chart, using light blue (9999ff) as the
// border and semi-transparent blue (c06666ff) as the fill color
c.addBollingerBand(20, 2, "0x9999ff", "0xc06666ff");

// Add a 70 pixels volume bars sub-chart to the bottom of the main chart, using
// green/red/grey for up/down/flat days
c.addVolBars(70, "0x99ff99", "0xff9999", "0x808080");

// Append a 14-days RSI indicator chart (70 pixels height) after the main chart. The
// main RSI line is purple (800080). Set threshold region to +/- 20 (that is, RSI =
// 50 +/- 25). The upper/lower threshold regions will be filled with red
// (ff0000)/blue (0000ff).
c.addRSI(70, 14, "0x800080", 20, "0xff0000", "0x0000ff");

// Append a 12-days momentum indicator chart (70 pixels height) using blue (0000ff)
// color.
c.addMomentum(70, 12, "0x0000ff");

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Finance Chart (1)
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" />
</cfoutput>
</body>
</html>


Finance Chart (2)

Finance Chart (2)

This example demonstrate creating a full-featured finance chart, with candlesticks, moving averages, Donchian channel, volume bars, MACD and Stochastic indicators.

This example employs the FinanceChart library add-on to allow complex financial charts to be composed easily. In this example, the key steps are:

  • Create a new FinanceChart object

  • Set data into the chart using FinanceChart.setData

  • Add a Slow Stochastic indicator chart as the top chart using FinanceChart.addSlowStochastic

  • Add the main chart using FinanceChart.addMainChart

  • Add simple moving average lines to the main chart using FinanceChart.addSimpleMovingAvg

  • Add candlestick symbols to the main chart using FinanceChart.addCandleStick

  • Add Donchian Channel to the main chart using FinanceChart.addDonchianChannel

  • Add volume bars to the main chart using FinanceChart.addVolBars

  • Add an additional MACD indicator chart using FinanceChart.addMACD
For simplicity and to allow this example to run without connecting to a real database, a RanTable object is used to simulate the data. RanTable is a ChartDirector utility class used for creating tables with random numbers.

Source Code Listing

[File: cfdemo/finance2.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// Create a finance chart demo containing 100 days of data
noOfDays = 100;

// To compute moving averages starting from the first day, we need to get extra data
// points before the first day
extraDays = 30;

// In this exammple, we use a random number generator utility to simulate the data.
// We set up the random table to create 6 cols x (noOfDays + extraDays) rows, using 9
// as the seed.
rantable = cd.RanTable(9, 6, noOfDays + extraDays);

// Set the 1st col to be the timeStamp, starting from Sep 4, 2002, with each row
// representing one day, and counting week days only (jump over Sat and Sun)
rantable.setDateCol(0, CreateDate(2002, 9, 4), 86400, True);

// Set the 2nd, 3rd, 4th and 5th columns to be high, low, open and close data. The
// open value starts from 100, and the daily change is random from -5 to 5.
rantable.setHLOCCols(1, 100, -5, 5);

// Set the 6th column as the vol data from 5 to 25 million
rantable.setCol(5, 50000000, 250000000);

// Now we read the data from the table into arrays
timeStamps = rantable.getCol(0);
highData = rantable.getCol(1);
lowData = rantable.getCol(2);
openData = rantable.getCol(3);
closeData = rantable.getCol(4);
volData = rantable.getCol(5);

// Create a FinanceChart object of width 600 pixels
c = cd.FinanceChart(600);

// Add a title to the chart
c.addTitle("Finance Chart Demonstration");

// Set the data into the finance chart object
c.setData(timeStamps, highData, lowData, openData, closeData, volData, extraDays);

// Add a slow stochastic chart with %K = 14 and %D = 3
c.addSlowStochastic(70, 14, 3, "0x006060", "0x606000");

// Add the main chart with 210 pixels in height
c.addMainChart(210);

// Add a 10 period simple moving average to the main chart, using brown color
c.addSimpleMovingAvg(10, "0x663300");

// Add a 20 period simple moving average to the main chart, using purple color
c.addSimpleMovingAvg(20, "0x9900ff");

// Add an HLOC symbols to the main chart, using green/red for up/down days
c.addCandleStick("0x00ff00", "0xff0000");

// Add 20 days donchian channel to the main chart, using light blue (9999ff) as the
// border and semi-transparent blue (c06666ff) as the fill color
c.addDonchianChannel(20, "0x9999ff", "0xc06666ff");

// Add a 70 pixels volume bars sub-chart to the bottom of the main chart, using
// green/red/grey for up/down/flat days
c.addVolBars(70, "0x99ff99", "0xff9999", "0x808080");

// Append a MACD(26, 12) indicator chart (70 pixels height) after the main chart,
// using 9 days for computing divergence.
c.addMACD(70, 26, 12, 9, "0x0000ff", "0xff00ff", "0x008000");

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Finance Chart (2)
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" />
</cfoutput>
</body>
</html>


Interactive Financial Chart

Interactive Financial Chart

This example demonstrates a full-featured financial chart in which the user can select the time ranges, technical indicators, and various chart options.

The Interactive Financial Chart is implemented in two parts - "financedemo.cfm" for the containing web page, and "financedemochart.cfm" for the charting page.

The containing web page "financedemo.cfm" is basically just a standard HTML Form. When the "Update Chart" button is pressed, instead of posting to the server, a client side Javascript function is activated. This function combines all Form elements into a query string, appends it to the charting URL "financedemochart.cfm" and uses it to update the <IMG> tag.

The "financedemochart.cfm" draws the finance chart according to the query parameters, which reflects user selections, and outputs the chart to the <IMG> tag.

The "financedemochart.cfm" contains two key parts.

  • The get15MinData, getDailyData, getWeeklyData and getMonthlyData functions are for retrieving stock data. In this example, they just retrieve data from a random number generator. You may replace the code in these functions with your own code to get data from your data source.

  • The drawChart function is the real charting code. It creates a FinanceChart object, sets data to it, and configures it according to query parameters.

Source Code Listing

[File: cfdemo/financedemo.cfm]
<html>
<cfoutput>
<head>
<title>ChartDirector Financial Chart Demonstration</title>
<script language="Javascript">

//Cross browser method to get an object
function getObject(id)
{
    if (document.getElementById)
        //IE 5.x or NS 6.x or above
        return document.getElementById(id);
    else if (document.all)
        //IE 4.x
        return document.all[id];
    else
        //Netscape 4.x
        return document[id];
}

//Update the chart according to user selection
function updateChart()
{
    //
    //we encode the values of all form elements as query parameters
    //
    var elements = getObject("Form1").elements;
    var url = "financedemochart.cfm?";
    for (var i = 0; i < elements.length; ++i)
    {
        var e = elements[i];
        if (e.type == "checkbox")
            url = url + e.id + "=" + (e.checked ? "1" : "0") + "&";
        else
            url = url + e.id + "=" + escape(e.value) + "&";
    }

    //Now we update the URL of the image to update the chart
    getObject("ChartImage").src = url;
}
</script>
</head>
<body style="margin:0px" onLoad="updateChart();">
<table cellspacing="0" cellpadding="0" border="0">
    <tr>
        <td align="right" colspan="2" style="background:##000088">
            <div style="padding-right:3px; padding-bottom:2px; font-family:arial; font-size:10pt; font-weight:bold; font-style:italic">
                <a style="color:##ffff00; text-decoration:none" href="http://www.advsofteng.com">
                    Advanced Software Engineering
                </a>
            </div>
        </td>
    </tr>
    <tr valign="top">
        <td style="width:150px; background:##bbddff">
            <form id="Form1" action="javascript:updateChart()">
            <div style="font-size:9pt; margin:10px 5px; font-family:verdana">
                <b>Ticker Symbol</b><br />
                <select id="TickerSymbol" name="TickerSymbol" style="width:140px; height:20px">
                    <option value="9">Random Data 9</option>
                    <option value="99">Random Data 99</option>
                    <option value="999">Random Data 999</option>
                    <option value="1">Random Data 1</option>
                    <option value="11">Random Data 11</option>
                    <option value="111">Random Data 111</option>
                    <option value="5">Random Data 5</option>
                    <option value="55">Random Data 55</option>
                    <option value="555">Random Data 555</option>
                    <option value="159">Random Data 159</option>
                </select>
            </div>
            <div style="font-size:9pt; margin:10px 5px; font-family:verdana">
                <b>Time Period</b><br />
                <select id="TimeRange" name="TimeRange" style="width:140px; height:20px">
                    <option value="1">1 day</option>
                    <option value="2">2 days</option>
                    <option value="5">5 days</option>
                    <option value="10">10 days</option>
                    <option value="30">1 month</option>
                    <option value="60">2 months</option>
                    <option value="90">3 months</option>
                    <option value="180" selected>6 months</option>
                    <option value="360">1 year</option>
                    <option value="720">2 years</option>
                    <option value="1080">3 years</option>
                    <option value="1440">4 years</option>
                    <option value="1800">5 years</option>
                    <option value="3600">10 years</option>
                </select>
            </div>
            <div style="font-size:9pt; margin:10px 5px; font-family:verdana">
                <b>Chart Size</b><br />
                <select id="ChartSize" name="ChartSize" style="width:140px; height:20px">
                    <option value="S">Small</option>
                    <option value="M">Medium</option>
                    <option value="L" selected>Large</option>
                    <option value="H">Huge</option>
                </select><br />
                <input type="checkbox" id="Volume" name="Volume" checked><label for="Volume">Show Volume Bars</label><br />
                <input type="checkbox" id="VGrid" name="VGrid" checked><label for="VGrid">Vertical Grid</label><br />
                <input type="checkbox" id="HGrid" name="HGrid" checked><label for="HGrid">Horizontal Grid</label><br />
                <input type="checkbox" id="LogScale" name="LogScale"><label for="LogScale">Log Scale</label><br />
            </div>
            <div style="font-size:9pt; margin:10px 5px; font-family:verdana">
                <b>Chart Type</b><br />
                <select id="ChartType" style="width:140px; height:20px" name="ChartType">
                    <option value="None">None</option>
                    <option value="CandleStick" selected>CandleStick</option>
                    <option value="Close">Closing Price</option>
                    <option value="Median">Median Price</option>
                    <option value="OHLC">OHLC</option>
                    <option value="TP">Typical Price</option>
                    <option value="WC">Weighted Close</option>
                </select>
            </div>
            <div style="font-size:9pt; margin:10px 5px; font-family:verdana">
                <b>Price Band</b><br />
                <select id="Band" name="Band" style="width:140px; height:20px">
                    <option value="None">None</option>
                    <option value="BB" selected>Bollinger Band</option>
                    <option value="DC">Donchain Channel</option>
                    <option value="Envelop">Envelop (SMA 20 +/- 10%)</option>
                </select>
            </div>
            <div style="font-size:9pt; margin:10px 5px; font-family:verdana">
                <b>Moving Averages</b><br />
                <nobr><select id="avgType1" name="avgType1" style="width:105px; height:20px">
                    <option value="None">None</option>
                    <option value="SMA" selected>Simple</option>
                    <option value="EMA">Exponential</option>
                    <option value="TMA">Triangular</option>
                    <option value="WMA">Weighted</option>
                </select>
                <input id="movAvg1" name="movAvg1" style="width:30px; height:20px" value="10"></nobr><br />
                <nobr><select id="avgType2" name="avgType2" style="width:105px; height:20px">
                    <option value="None">None</option>
                    <option value="SMA" selected>Simple</option>
                    <option value="EMA">Exponential</option>
                    <option value="TMA">Triangular</option>
                    <option value="WMA">Weighted</option>
                </select>
                <input id="movAvg2" name="movAvg2" style="width:30px; height:20px" value="25"></nobr><br />
            </div>
            <div style="font-size:9pt; margin:10px 5px; font-family:verdana">
                <b>Technical Indicators</b><br />
                <select id="Indicator1" name="Indicator1" style="width:140px; height:20px">
                    <option value="None">None</option>
                    <option value="AccDist">Accumulation/Distribution</option>
                    <option value="AroonOsc">Aroon Oscillator</option>
                    <option value="Aroon">Aroon Up/Down</option>
                    <option value="ADX">Avg Directional Index</option>
                    <option value="ATR">Avg True Range</option>
                    <option value="BBW">Bollinger Band Width</option>
                    <option value="CMF">Chaikin Money Flow</option>
                    <option value="COscillator">Chaikin Oscillator</option>
                    <option value="CVolatility">Chaikin Volatility</option>
                    <option value="CLV">Close Location Value</option>
                    <option value="CCI">Commodity Channel Index</option>
                    <option value="DPO">Detrended Price Osc</option>
                    <option value="DCW">Donchian Channel Width</option>
                    <option value="EMV">Ease of Movement</option>
                    <option value="FStoch">Fast Stochastic</option>
                    <option value="MACD">MACD</option>
                    <option value="MDX">Mass Index</option>
                    <option value="Momentum">Momentum</option>
                    <option value="MFI">Money Flow Index</option>
                    <option value="NVI">Neg Volume Index</option>
                    <option value="OBV">On Balance Volume</option>
                    <option value="Performance">Performance</option>
                    <option value="PPO">% Price Oscillator</option>
                    <option value="PVO">% Volume Oscillator</option>
                    <option value="PVI">Pos Volume Index</option>
                    <option value="PVT">Price Volume Trend</option>
                    <option value="ROC">Rate of Change</option>
                    <option value="RSI" selected>RSI</option>
                    <option value="SStoch">Slow Stochastic</option>
                    <option value="StochRSI">StochRSI</option>
                    <option value="TRIX">TRIX</option>
                    <option value="UO">Ultimate Oscillator</option>
                    <option value="Vol">Volume</option>
                    <option value="WilliamR">William's %R</option>
                </select><br />
                <select id="Indicator2" name="Indicator2" style="width:140px; height:20px">
                    <option value="None">None</option>
                    <option value="AccDist">Accumulation/Distribution</option>
                    <option value="AroonOsc">Aroon Oscillator</option>
                    <option value="Aroon">Aroon Up/Down</option>
                    <option value="ADX">Avg Directional Index</option>
                    <option value="ATR">Avg True Range</option>
                    <option value="BBW">Bollinger Band Width</option>
                    <option value="CMF">Chaikin Money Flow</option>
                    <option value="COscillator">Chaikin Oscillator</option>
                    <option value="CVolatility">Chaikin Volatility</option>
                    <option value="CLV">Close Location Value</option>
                    <option value="CCI">Commodity Channel Index</option>
                    <option value="DPO">Detrended Price Osc</option>
                    <option value="DCW">Donchian Channel Width</option>
                    <option value="EMV">Ease of Movement</option>
                    <option value="FStoch">Fast Stochastic</option>
                    <option value="MACD" selected>MACD</option>
                    <option value="MDX">Mass Index</option>
                    <option value="Momentum">Momentum</option>
                    <option value="MFI">Money Flow Index</option>
                    <option value="NVI">Neg Volume Index</option>
                    <option value="OBV">On Balance Volume</option>
                    <option value="Performance">Performance</option>
                    <option value="PPO">% Price Oscillator</option>
                    <option value="PVO">% Volume Oscillator</option>
                    <option value="PVI">Pos Volume Index</option>
                    <option value="PVT">Price Volume Trend</option>
                    <option value="ROC">Rate of Change</option>
                    <option value="RSI">RSI</option>
                    <option value="SStoch">Slow Stochastic</option>
                    <option value="StochRSI">StochRSI</option>
                    <option value="TRIX">TRIX</option>
                    <option value="UO">Ultimate Oscillator</option>
                    <option value="Vol">Volume</option>
                    <option value="WilliamR">William's %R</option>
                </select><br />
                <select id="Indicator3" name="Indicator3" style="width:140px; height:20px">
                    <option value="None" selected>None</option>
                    <option value="AccDist">Accumulation/Distribution</option>
                    <option value="AroonOsc">Aroon Oscillator</option>
                    <option value="Aroon">Aroon Up/Down</option>
                    <option value="ADX">Avg Directional Index</option>
                    <option value="ATR">Avg True Range</option>
                    <option value="BBW">Bollinger Band Width</option>
                    <option value="CMF">Chaikin Money Flow</option>
                    <option value="COscillator">Chaikin Oscillator</option>
                    <option value="CVolatility">Chaikin Volatility</option>
                    <option value="CLV">Close Location Value</option>
                    <option value="CCI">Commodity Channel Index</option>
                    <option value="DPO">Detrended Price Osc</option>
                    <option value="DCW">Donchian Channel Width</option>
                    <option value="EMV">Ease of Movement</option>
                    <option value="FStoch">Fast Stochastic</option>
                    <option value="MACD">MACD</option>
                    <option value="MDX">Mass Index</option>
                    <option value="Momentum">Momentum</option>
                    <option value="MFI">Money Flow Index</option>
                    <option value="NVI">Neg Volume Index</option>
                    <option value="OBV">On Balance Volume</option>
                    <option value="Performance">Performance</option>
                    <option value="PPO">% Price Oscillator</option>
                    <option value="PVO">% Volume Oscillator</option>
                    <option value="PVI">Pos Volume Index</option>
                    <option value="PVT">Price Volume Trend</option>
                    <option value="ROC">Rate of Change</option>
                    <option value="RSI">RSI</option>
                    <option value="SStoch">Slow Stochastic</option>
                    <option value="StochRSI">StochRSI</option>
                    <option value="TRIX">TRIX</option>
                    <option value="UO">Ultimate Oscillator</option>
                    <option value="Vol">Volume</option>
                    <option value="WilliamR">William's %R</option>
                </select><br />
                <select id="Indicator4" name="Indicator4" style="width:140px; height:20px">
                    <option value="None" selected>None</option>
                    <option value="AccDist">Accumulation/Distribution</option>
                    <option value="AroonOsc">Aroon Oscillator</option>
                    <option value="Aroon">Aroon Up/Down</option>
                    <option value="ADX">Avg Directional Index</option>
                    <option value="ATR">Avg True Range</option>
                    <option value="BBW">Bollinger Band Width</option>
                    <option value="CMF">Chaikin Money Flow</option>
                    <option value="COscillator">Chaikin Oscillator</option>
                    <option value="CVolatility">Chaikin Volatility</option>
                    <option value="CLV">Close Location Value</option>
                    <option value="CCI">Commodity Channel Index</option>
                    <option value="DPO">Detrended Price Osc</option>
                    <option value="DCW">Donchian Channel Width</option>
                    <option value="EMV">Ease of Movement</option>
                    <option value="FStoch">Fast Stochastic</option>
                    <option value="MACD">MACD</option>
                    <option value="MDX">Mass Index</option>
                    <option value="Momentum">Momentum</option>
                    <option value="MFI">Money Flow Index</option>
                    <option value="NVI">Neg Volume Index</option>
                    <option value="OBV">On Balance Volume</option>
                    <option value="Performance">Performance</option>
                    <option value="PPO">% Price Oscillator</option>
                    <option value="PVO">% Volume Oscillator</option>
                    <option value="PVI">Pos Volume Index</option>
                    <option value="PVT">Price Volume Trend</option>
                    <option value="ROC">Rate of Change</option>
                    <option value="RSI">RSI</option>
                    <option value="SStoch">Slow Stochastic</option>
                    <option value="StochRSI">StochRSI</option>
                    <option value="TRIX">TRIX</option>
                    <option value="UO">Ultimate Oscillator</option>
                    <option value="Vol">Volume</option>
                    <option value="WilliamR">William's %R</option>
                </select>
            </div>
            <div style="font-size:9pt; font-family:verdana; text-align:center">
                <input id="Button1" name="Button1" type="submit" value="Update Chart">
            </div>
            </form>
        </td>
        <td>
            <div style="font-weight:bold;  font-family:arial; font-size:20pt; margin:5px 0px 0px 5px">
                ChartDirector Financial Chart Demonstration
            </div>
            <hr style="border:solid 1px ##000080" />
            <br />
            <img id="ChartImage" align="top" border="0">
        </td>
    </tr>
</table>
</body>
</cfoutput>
</html>

[File: cfdemo/financedemochart.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

//
// Create a finance chart based on user selections, which are encoded as query
// parameters. This code is designed to work with the financedemo HTML form.
//

// The timeStamps, volume, high, low, open and close data
timeStamps = Array();
volData = Array();
highData = Array();
lowData = Array();
openData = Array();
closeData = Array();

/// <summary>
/// Get 15 minutes data series for timeStamps, highData, lowData, openData, closeData
/// and volData.
/// </summary>
/// <param name="ticker">The ticker symbol for the data series.</param>
/// <param name="startDate">The starting date/time for the data series.</param>
/// <param name="endDate">The ending date/time for the data series.</param>
function get15MinData(ticker, startDate, endDate)
{
    //
    // In this demo, we use a random number generator to generate the data. In
    // practice, you may get the data from a database or by other means. If you do
    // not have 15 minute data, you may modify the "drawChart" method below to not
    // using 15 minute data.
    //
    generateRandomData(ticker, startDate, endDate, 900);
}

/// <summary>
/// Get daily data series for timeStamps, highData, lowData, openData, closeData
/// and volData.
/// </summary>
/// <param name="ticker">The ticker symbol for the data series.</param>
/// <param name="startDate">The starting date/time for the data series.</param>
/// <param name="endDate">The ending date/time for the data series.</param>
function getDailyData(ticker, startDate, endDate)
{
    //
    // In this demo, we use a random number generator to generate the data. In
    // practice, you may get the data from a database or by other means.
    //
    generateRandomData(ticker, startDate, endDate, 86400);
}

/// <summary>
/// Get weekly data series for timeStamps, highData, lowData, openData, closeData
/// and volData.
/// </summary>
/// <param name="ticker">The ticker symbol for the data series.</param>
/// <param name="startDate">The starting date/time for the data series.</param>
/// <param name="endDate">The ending date/time for the data series.</param>
function getWeeklyData(ticker, startDate, endDate)
{
    //
    // If you do not have weekly data, you may call "getDailyData(startDate,
    // endDate)" to get daily data, then call "convertDailyToWeeklyData()" to convert
    // to weekly data.
    //
    generateRandomData(ticker, startDate, endDate, 86400 * 7);
}

/// <summary>
/// Get monthly data series for timeStamps, highData, lowData, openData, closeData
/// and volData.
/// </summary>
/// <param name="ticker">The ticker symbol for the data series.</param>
/// <param name="startDate">The starting date/time for the data series.</param>
/// <param name="endDate">The ending date/time for the data series.</param>
function getMonthlyData(ticker, startDate, endDate)
{
    //
    // If you do not have weekly data, you may call "getDailyData(startDate,
    // endDate)" to get daily data, then call "convertDailyToMonthlyData()" to
    // convert to monthly data.
    //
    generateRandomData(ticker, startDate, endDate, 86400 * 30);
}

/// <summary>
/// A random number generator designed to generate realistic financial data.
/// </summary>
/// <param name="ticker">The ticker symbol for the data series.</param>
/// <param name="startDate">The starting date/time for the data series.</param>
/// <param name="endDate">The ending date/time for the data series.</param>
/// <param name="resolution">The period of the data series.</param>
function generateRandomData(ticker, startDate, endDate, resolution)
{
    // Declare local variables
    var db = 0;

    db = cd.FinanceSimulator(Int(ticker), startDate, endDate, resolution);
    timeStamps = db.getTimeStamps();
    highData = db.getHighData();
    lowData = db.getLowData();
    openData = db.getOpenData();
    closeData = db.getCloseData();
    volData = db.getVolData();
}

/// <summary>
/// A utility to convert daily to weekly data.
/// </summary>
function convertDailyToWeeklyData()
{
    aggregateData(cd.ArrayMath(timeStamps).selectStartOfWeek());
}

/// <summary>
/// A utility to convert daily to monthly data.
/// </summary>
function convertDailyToMonthlyData()
{
    aggregateData(cd.ArrayMath(timeStamps).selectStartOfMonth());
}

/// <summary>
/// An internal method used to aggregate daily data.
/// </summary>
function aggregateData(aggregator)
{
    timeStamps = aggregator.aggregate(timeStamps, cd.AggregateFirst);
    highData = aggregator.aggregate(highData, cd.AggregateMax);
    lowData = aggregator.aggregate(lowData, cd.AggregateMin);
    openData = aggregator.aggregate(openData, cd.AggregateFirst);
    closeData = aggregator.aggregate(closeData, cd.AggregateLast);
    volData = aggregator.aggregate(volData, cd.AggregateSum);
}

/// <summary>
/// Create a financial chart according to user selections. The user selections are
/// encoded in the query parameters.
/// </summary>
function drawChart()
{
    // Declare local variables
    var endDate = 0;
    var durationInDays = 0;
    var startDate = 0;
    var avgPeriod1 = 0;
    var avgPeriod2 = 0;
    var extraPoints = 0;
    var tickerKey = 0;
    var resolution = 0;
    var dataPointsPerDay = 0;
    var i = 0;
    var errMsg = 0;
    var lastTime = 0;
    var width = 0;
    var mainHeight = 0;
    var indicatorHeight = 0;
    var size = 0;
    var m = 0;
    var resolutionText = 0;
    var vGridColor = 0;
    var hGridColor = 0;
    var mainType = 0;
    var bandType = 0;

    // In this demo, we just assume we plot up to the latest time. So end date is
    // now.
    endDate = Now();

    // If the trading day has not yet started (before 9:30am), or if the end date is
    // on on Sat or Sun, we set the end date to 4:00pm of the last trading day
    while ((Hour(endDate) * 60 + Minute(endDate) LT 9 * 60 + 30) Or
        DayOfWeek(endDate) EQ 1 Or DayOfWeek(endDate) EQ 7) {
        endDate = DateAdd("d", -1, CreateDateTime(Year(endDate), Month(endDate),
            Day(endDate), 16, 0, 0));
    }

    // The duration selected by the user
    durationInDays = Int(URL.TimeRange);

    // Compute the start date by subtracting the duration from the end date.
    startDate = endDate;
    if (durationInDays GTE 30) {
        // More or equal to 30 days - so we use months as the unit
        startDate = DateAdd("m", - durationInDays \ 30,
            CreateDate(Year(endDate), Month(endDate), 1));
    } else {
        // Less than 30 days - use day as the unit. The starting point of the axis is
        // always at the start of the day (9:30am). Note that we use trading days, so
        // we skip Sat and Sun in counting the days.
        startDate = CreateDateTime(Year(endDate), Month(endDate), Day(endDate),
            9, 30, 0);
        for (i = 1; i LT durationInDays; i = i + 1) {
            if (DayOfWeek(startDate) EQ 2) {
                startDate = DateAdd("d", -3, startDate);
            } else {
                startDate = DateAdd("d", -1, startDate);
            }
        }
    }

    // The moving average periods selected by the user.
    avgPeriod1 = 0;
    if (IsNumeric(URL.movAvg1)) {
        avgPeriod1 = Int(URL.movAvg1);;
    } else {
        avgPeriod1 = 0;;
    }
    avgPeriod2 = 0;
    if (IsNumeric(URL.movAvg2)) {
        avgPeriod2 = Int(URL.movAvg2);;
    } else {
        avgPeriod2 = 0;;
    }

    if (avgPeriod1 LT 0) {
        avgPeriod1 = 0;
    } else if (avgPeriod1 GT 300) {
        avgPeriod1 = 300;
    }

    if (avgPeriod2 LT 0) {
        avgPeriod2 = 0;
    } else if (avgPeriod2 GT 300) {
        avgPeriod2 = 300;
    }

    // We need extra leading data points in order to compute moving averages.
    extraPoints = 20;
    if (avgPeriod1 GT extraPoints) {
        extraPoints = avgPeriod1;
    }
    if (avgPeriod2 GT extraPoints) {
        extraPoints = avgPeriod2;
    }

    // The data series we want to get.
    tickerKey = URL.TickerSymbol;

    // In this demo, we can get 15 min, daily, weekly or monthly data depending on
    // the time range.
    resolution = 86400;
    if (durationInDays LTE 10) {
        // 10 days or less, we assume 15 minute data points are available
        resolution = 900;

        // We need to adjust the startDate backwards for the extraPoints. We assume
        // 6.5 hours trading time per day, and 5 trading days per week.
        dataPointsPerDay = 6.5 * 3600 / resolution;
        adjustedStartDate = DateAdd("d", -Ceiling(extraPoints / dataPointsPerDay * 7
            / 5) - 2, CreateDate(Year(startDate), Month(startDate), Day(startDate)));

        // Get the required 15 min data
        get15MinData(tickerKey, adjustedStartDate, endDate);

    } else if (durationInDays GTE 4.5 * 360) {
        // 4 years or more - use monthly data points.
        resolution = 30 * 86400;

        // Adjust startDate backwards to cater for extraPoints
        adjustedStartDate = DateAdd("m", -extraPoints, startDate);

        // Get the required monthly data
        getMonthlyData(tickerKey, adjustedStartDate, endDate);

    } else if (durationInDays GTE 1.5 * 360) {
        // 1 year or more - use weekly points.
        resolution = 7 * 86400;

        // Adjust startDate backwards to cater for extraPoints
        adjustedStartDate = DateAdd("d", -extraPoints * 7 - 6, startDate);

        // Get the required weekly data
        getWeeklyData(tickerKey, adjustedStartDate, endDate);

    } else {
        // Default - use daily points
        resolution = 86400;

        // Adjust startDate backwards to cater for extraPoints. We multiply the days
        // by 7/5 as we assume 1 week has 5 trading days.
        adjustedStartDate = DateAdd("d", -Int((extraPoints * 7 + 4) / 5) - 2,
            CreateDate(Year(startDate), Month(startDate), Day(startDate)));

        // Get the required daily data
        getDailyData(tickerKey, adjustedStartDate, endDate);
    }

    // We now confirm the actual number of extra points (data points that are before
    // the start date) as inferred using actual data from the database.
    extraPoints = ArrayLen(timeStamps);
    for (i = 0; i LT ArrayLen(timeStamps); i = i + 1) {
        if (timeStamps[i + 1] GTE startDate) {
            extraPoints = i;
            break;
        }
    }

    // Check if there is any valid data
    if (extraPoints GTE ArrayLen(timeStamps)) {
        // No data - just display the no data message.
        errMsg = cd.MultiChart(400, 50);
        errMsg.addTitle2(cd.Center,
            "No data available for the specified time period", "Arial", 10);
        return errMsg;
    }

    // In some finance chart presentation style, even if the data for the latest day
    // is not fully available, the axis for the entire day will still be drawn, where
    // no data will appear near the end of the axis.
    if (resolution LT 86400) {
        // Add extra points to the axis until it reaches the end of the day. The end
        // of day is assumed to be 16:00 (it depends on the stock exchange).
        lastTime = timeStamps[ArrayLen(timeStamps)];
        extraTrailingPoints = Int((16 * 3600.0 - Hour(lastTime) * 3600 -
            Minute(lastTime) * 60 - Second(lastTime)) / resolution);
        for (i = 0; i LT extraTrailingPoints; i = i + 1) {
            ArrayAppend(timeStamps, DateAdd("s", resolution * i, lastTime));
        }
    }

    //
    // At this stage, all data are available. We can draw the chart as according to
    // user input.
    //

    //
    // Determine the chart size. In this demo, user can select 4 different chart
    // sizes. Default is the large chart size.
    //
    width = 780;
    mainHeight = 250;
    indicatorHeight = 80;

    size = URL.ChartSize;
    if (size EQ "S") {
        // Small chart size
        width = 450;
        mainHeight = 160;
        indicatorHeight = 60;
    } else if (size EQ "M") {
        // Medium chart size
        width = 620;
        mainHeight = 210;
        indicatorHeight = 65;
    } else if (size EQ "H") {
        // Huge chart size
        width = 1000;
        mainHeight = 320;
        indicatorHeight = 90;
    }

    // Create the chart object using the selected size
    m = cd.FinanceChart(width);

    // Set the data into the chart object
    m.setData(timeStamps, highData, lowData, openData, closeData, volData,
        extraPoints);

    //
    // We configure the title of the chart. In this demo chart design, we put the
    // company name as the top line of the title with left alignment.
    //
    m.addPlotAreaTitle(cd.TopLeft, "Random Data " & tickerKey);

    // We displays the current date as well as the data resolution on the next line.
    resolutionText = "";
    if (resolution EQ 30 * 86400) {
        resolutionText = "Monthly";
    } else if (resolution EQ 7 * 86400) {
        resolutionText = "Weekly";
    } else if (resolution EQ 86400) {
        resolutionText = "Daily";
    } else if (resolution EQ 900) {
        resolutionText = "15-min";
    }

    m.addPlotAreaTitle(cd.BottomLeft, "<*font=Arial,size=8*>" & m.formatValue(Now(),
        "mmm dd, yyyy") & " - " & resolutionText & " chart");

    // A copyright message at the bottom left corner the title area
    m.addPlotAreaTitle(cd.BottomRight,
        "<*font=Arial,size=8*>(c) Advanced Software Engineering");

    //
    // Set the grid style according to user preference. In this simple demo user
    // interface, user can enable/disable grid lines. The code achieve this by
    // setting the grid color to dddddd (light grey) or Transparent. The plot area
    // background color is set to fffff0 (pale yellow).
    //
    vGridColor = cd.Transparent;
    if (URL.VGrid EQ "1") {
        vGridColor = "0xdddddd";
    }
    hGridColor = cd.Transparent;
    if (URL.HGrid EQ "1") {
        hGridColor = "0xdddddd";
    }
    m.setPlotAreaStyle("0xfffff0", hGridColor, vGridColor, hGridColor, vGridColor);

    //
    // Set log or linear scale according to user preference
    //
    if (URL.LogScale EQ "1") {
        m.setLogScale(True);
    }

    //
    // Add the first techical indicator according. In this demo, we draw the first
    // indicator on top of the main chart.
    //
    addIndicator(m, URL.Indicator1, indicatorHeight);

    //
    // Add the main chart
    //
    m.addMainChart(mainHeight);

    //
    // Add moving average lines.
    //
    addMovingAvg(m, URL.avgType1, avgPeriod1, "0x663300");
    addMovingAvg(m, URL.avgType2, avgPeriod2, "0x9900ff");

    //
    // Draw the main chart depending on the chart type the user has selected
    //
    mainType = URL.ChartType;
    if (mainType EQ "CandleStick") {
        m.addCandleStick("0x33ff33", "0xff3333");
    } else if (mainType EQ "OHLC") {
        m.addHLOC("0x008800", "0xcc0000");
    } else if (mainType EQ "Close") {
        m.addCloseLine("0x000040");
    } else if (mainType EQ "TP") {
        m.addTypicalPrice("0x000040");
    } else if (mainType EQ "WC") {
        m.addWeightedClose("0x000040");
    } else if (mainType EQ "Median") {
        m.addMedianPrice("0x000040");
    }

    //
    // Add price band/channel/envelop to the chart according to user selection
    //
    bandType = URL.Band;
    if (bandType EQ "BB") {
        m.addBollingerBand(20, 2, "0x9999ff", "0xc06666ff");
    } else if (bandType EQ "DC") {
        m.addDonchianChannel(20, "0x9999ff", "0xc06666ff");
    } else if (bandType EQ "Envelop") {
        m.addEnvelop(20, 0.1, "0x9999ff", "0xc06666ff");
    }

    //
    // Add volume bars to the main chart if necessary
    //
    if (URL.Volume EQ "1") {
        m.addVolBars(indicatorHeight, "0x99ff99", "0xff9999", "0xc0c0c0");
    }

    //
    // Add additional indicators as according to user selection.
    //
    addIndicator(m, URL.Indicator2, indicatorHeight);
    addIndicator(m, URL.Indicator3, indicatorHeight);
    addIndicator(m, URL.Indicator4, indicatorHeight);

    return m;
}

/// <summary>
/// Add a moving average line to the FinanceChart object.
/// </summary>
/// <param name="m">The FinanceChart object to add the line to.</param>
/// <param name="avgType">The moving average type (SMA/EMA/TMA/WMA).</param>
/// <param name="avgPeriod">The moving average period.</param>
/// <param name="color">The color of the line.</param>
function addMovingAvg(m, avgType, avgPeriod, color)
{
    if (avgPeriod GT 1) {
        if (avgType EQ "SMA") {
            m.addSimpleMovingAvg(avgPeriod, color);
        } else if (avgType EQ "EMA") {
            m.addExpMovingAvg(avgPeriod, color);
        } else if (avgType EQ "TMA") {
            m.addTriMovingAvg(avgPeriod, color);
        } else if (avgType EQ "WMA") {
            m.addWeightedMovingAvg(avgPeriod, color);
        }
    }
}

/// <summary>
/// Add an indicator chart to the FinanceChart object. In this demo example, the
/// indicator parameters (such as the period used to compute RSI, colors of the lines,
/// etc.) are hard coded to commonly used values. You are welcome to design a more
/// complex user interface to allow users to set the parameters.
/// </summary>
/// <param name="m">The FinanceChart object to add the line to.</param>
/// <param name="indicator">The selected indicator.</param>
/// <param name="height">Height of the chart in pixels</param>
function addIndicator(m, indicator, height)
{
    if (indicator EQ "RSI") {
        m.addRSI(height, 14, "0x800080", 20, "0xff6666", "0x6666ff");
    } else if (indicator EQ "StochRSI") {
        m.addStochRSI(height, 14, "0x800080", 30, "0xff6666", "0x6666ff");
    } else if (indicator EQ "MACD") {
        m.addMACD(height, 26, 12, 9, "0x0000ff", "0xff00ff", "0x008000");
    } else if (indicator EQ "FStoch") {
        m.addFastStochastic(height, 14, 3, "0x006060", "0x606000");
    } else if (indicator EQ "SStoch") {
        m.addSlowStochastic(height, 14, 3, "0x006060", "0x606000");
    } else if (indicator EQ "ATR") {
        m.addATR(height, 14, "0x808080", "0x0000ff");
    } else if (indicator EQ "ADX") {
        m.addADX(height, 14, "0x008000", "0x800000", "0x000080");
    } else if (indicator EQ "DCW") {
        m.addDonchianWidth(height, 20, "0x0000ff");
    } else if (indicator EQ "BBW") {
        m.addBollingerWidth(height, 20, 2, "0x0000ff");
    } else if (indicator EQ "DPO") {
        m.addDPO(height, 20, "0x0000ff");
    } else if (indicator EQ "PVT") {
        m.addPVT(height, "0x0000ff");
    } else if (indicator EQ "Momentum") {
        m.addMomentum(height, 12, "0x0000ff");
    } else if (indicator EQ "Performance") {
        m.addPerformance(height, "0x0000ff");
    } else if (indicator EQ "ROC") {
        m.addROC(height, 12, "0x0000ff");
    } else if (indicator EQ "OBV") {
        m.addOBV(height, "0x0000ff");
    } else if (indicator EQ "AccDist") {
        m.addAccDist(height, "0x0000ff");
    } else if (indicator EQ "CLV") {
        m.addCLV(height, "0x0000ff");
    } else if (indicator EQ "WilliamR") {
        m.addWilliamR(height, 14, "0x800080", 30, "0xff6666", "0x6666ff");
    } else if (indicator EQ "Aroon") {
        m.addAroon(height, 14, "0x339933", "0x333399");
    } else if (indicator EQ "AroonOsc") {
        m.addAroonOsc(height, 14, "0x0000ff");
    } else if (indicator EQ "CCI") {
        m.addCCI(height, 20, "0x800080", 100, "0xff6666", "0x6666ff");
    } else if (indicator EQ "EMV") {
        m.addEaseOfMovement(height, 9, "0x006060", "0x606000");
    } else if (indicator EQ "MDX") {
        m.addMassIndex(height, "0x800080", "0xff6666", "0x6666ff");
    } else if (indicator EQ "CVolatility") {
        m.addChaikinVolatility(height, 10, 10, "0x0000ff");
    } else if (indicator EQ "COscillator") {
        m.addChaikinOscillator(height, "0x0000ff");
    } else if (indicator EQ "CMF") {
        m.addChaikinMoneyFlow(height, 21, "0x008000");
    } else if (indicator EQ "NVI") {
        m.addNVI(height, 255, "0x0000ff", "0x883333");
    } else if (indicator EQ "PVI") {
        m.addPVI(height, 255, "0x0000ff", "0x883333");
    } else if (indicator EQ "MFI") {
        m.addMFI(height, 14, "0x800080", 30, "0xff6666", "0x6666ff");
    } else if (indicator EQ "PVO") {
        m.addPVO(height, 26, 12, 9, "0x0000ff", "0xff00ff", "0x008000");
    } else if (indicator EQ "PPO") {
        m.addPPO(height, 26, 12, 9, "0x0000ff", "0xff00ff", "0x008000");
    } else if (indicator EQ "UO") {
        m.addUltimateOscillator(height, 7, 14, 28, "0x800080", 20, "0xff6666",
            "0x6666ff");
    } else if (indicator EQ "Vol") {
        m.addVolIndicator(height, "0x99ff99", "0xff9999", "0xc0c0c0");
    } else if (indicator EQ "TRIX") {
        m.addTRIX(height, 12, "0x0000ff");
    }
}

// create the finance chart
c = drawChart();

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Stream chart directly to browser
GetPageContext().forward("getchart.cfm?" & chart1URL);

</cfscript>


Other XY Chart Features

Other XY Chart Features

Title | Description
Marks and Zones | Demonstrates adding marks and zones to the chart, and adding custom legend keys to represent the zones.
Marks and Zones (2) | Demonstrates adding marks and zones to the chart, and positioning mark labels.
Y Zone Coloring | Demonstrates using y zone colors - colors that change at certain y value thresholds.
X Zone Coloring | Demonstrates using x zone colors - colors that change at certain x value thresholds.
Dual Y-Axis | Demonstrates a chart with two independent y-axis.
Dual X-Axis | Demonstrates a chart with two x-axes and two y-axes.
Multiple Axes | Demonstrates using 4 y-axes in a chart.
4 Quadrant Chart | Demonstrates 4 quadrant charts in which the x-axis and y-axis meet at the origin at the center of the plot area.
Text Styles and Colors (2) | Demonstrates controlling text style and colors in various text containing objects (chart and axis titles, axis labels, legend keys, data labels, etc).
Background and Wallpaper | Demonstrates some of the background effects supported by ChartDirector.
Log Scale Axis | Demonstrates using a log scale axis versus a linear scale axis.
Y-Axis Scaling | Demonstrates how to control auto-scaling.
Tick Density | Demonstrates how to control the axis tick density in auto-scaling.


Marks and Zones

Marks and Zones

This example demonstrates adding marks and zones to the chart, and adding custom legend keys to represent the zones.

A "mark" is a line drawn in the plot area. The purple "Alert" line and the green "Watch" line on the chart are mark lines. It is added to the chart using Axis.addMark.

Mark lines can be horizontal or vertical, depending on which axis the marks are defined on. Marks can be drawn on the front of the plot area (the default), or at the back like grid lines. This is configured using Mark.setDrawOnTop.

A "zone" is a color band on the back of the plot area. In this example, the red, yellow and green areas are zones. They are added to the chart using Axis.addZone. Like marks, zones can be horizontal or vertical.

In this example, LegendBox.addKey is used to add the names of the zones to the legend box as custom entries.

Source Code Listing

[File: cfdemo/markzone.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the chart
data = Array(40, 45, 37, 24, 32, 39, 53, 52, 63, 49, 46, 40, 54, 50, 57, 57, 48, 49,
    63, 67, 74, 72, 70, 89, 74);
labels = Array("0<*br*>Jun 4", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
    "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23",
    "0<*br*>Jun 5");

// Create a XYChart object of size 400 x 270 pixels
c = cd.XYChart(400, 270);

// Set the plotarea at (80, 60) and of size 300 x 200 pixels. Turn off the grid lines
// by setting their colors to Transparent.
c.setPlotArea(80, 28, 300, 200).setGridColor(cd.Transparent);

// Add a title to the y axis
textbox = c.yAxis().setTitle("Temperature");

// Set the y axis title upright (font angle = 0)
textbox.setFontAngle(0);

// Put the y axis title on top of the axis
textbox.setAlignment(cd.TopLeft2);

// Add green (0x99ff99), yellow (0xffff99) and red (0xff9999) zones to the y axis to
// represent the ranges 0 - 50, 50 - 80, and 80 - max.
c.yAxis().addZone(0, 50, "0x99ff99");
c.yAxis().addZone(50, 80, "0xffff99");
c.yAxis().addZone(80, 9999, "0xff9999");

// Add a purple (0x800080) mark at y = 70 using a line width of 2.
c.yAxis().addMark(70, "0x800080", "Alert = 70").setLineWidth(2);

// Add a green (0x008000) mark at y = 40 using a line width of 2.
c.yAxis().addMark(40, "0x008000", "Watch = 40").setLineWidth(2);

// Add a legend box at (165, 0) (top right of the chart) using 8 pts Arial font. and
// horizontal layout.
legend = c.addLegend(165, 0, False, "Arial Bold", 8);

// Disable the legend box boundary by setting the colors to Transparent
legend.setBackground(cd.Transparent, cd.Transparent);

// Add 3 custom entries to the legend box to represent the 3 zones
legend.addKey("Normal", "0x80ff80");
legend.addKey("Warning", "0xffff80");
legend.addKey("Critical", "0xff8080");

// Set the labels on the x axis.
c.xAxis().setLabels(labels);

// Display 1 out of 3 labels on the x-axis. Show minor ticks for remaining labels.
c.xAxis().setLabelStep(3, 1);

// Add a 3D bar layer with the given data
layer = c.addBarLayer(data, "0xbbbbff");

// Set the bar gap to 0 so that the bars are packed tightly
layer.setBarGap(0);

// Set the border color of the bars same as the fill color, with 1 pixel 3D border
// effect.
layer.setBorderColor(cd.SameAsMainColor, 1);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "", "title='Temperature at {x}:00 = {value} C'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Marks and Zones
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Marks and Zones (2)

Marks and Zones (2)

This example demonstrates adding marks and zones to the chart, and positioning mark labels.

The chart in the example consists of three mark lines (one horizontal and two vertical) and one vertical zone. The mark lines are created using Axis.addMark. The zone is created using Axis.addZone.

By default, mark labels will be drawn as axis labels. In this example, the label of the red mark line is moved to the top center of the mark line using TextBox.setAlignment with TopCenter alignment.

Similarly, the labels for the brown mark lines are moved to the left and right sides of the mark lines, with the text rotated by 90 degrees. This is achieved by using TextBox.setAlignment with Left and Right alignments, and using TextBox.setFontAngle.

Source Code Listing

[File: cfdemo/markzone2.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the chart
data = Array(50, 55, 47, 34, 42, 49, 63, 62, 73, 59, 56, 50, 64, 60, 67, 67, 58, 59,
    73, 77, 84, 82, 80, 84, 89);

// The labels for the chart. Note the "-" means a minor tick.
labels = Array("0<*br*>Jun 4", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
    "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23",
    "0<*br*>Jun 5");

// Create a XYChart object of size 400 x 270 pixels
c = cd.XYChart(400, 270);

// Set the plotarea at (80, 25) and of size 300 x 200 pixels. Use alternate color
// background (0xeeeeee) and (0xffffff). Set border and grid colors to grey
// (0xc0c0c0).
c.setPlotArea(50, 25, 300, 200, "0xeeeeee", "0xffffff", "0xc0c0c0", "0xc0c0c0",
    "0xc0c0c0");

// Add a title to the chart using 14 pts Times Bold Italic font
c.addTitle("Server Monitor", "Times New Roman Bold Italic", 14);

// Add a title to the y axis
c.yAxis().setTitle("Server Load (MBytes)");

// Set the y axis width to 2 pixels
c.yAxis().setWidth(2);

// Set the labels on the x axis.
c.xAxis().setLabels(labels);

// Display 1 out of 3 labels on the x-axis. Show minor ticks for remaining labels.
c.xAxis().setLabelStep(3, 1);

// Set the x axis width to 2 pixels
c.xAxis().setWidth(2);

// Add a horizontal red (0x800080) mark line at y = 80
yMark = c.yAxis().addMark(80, "0xff0000", "Critical Threshold Set Point");

// Set the mark line width to 2 pixels
yMark.setLineWidth(2);

// Put the mark label at the top center of the mark line
yMark.setAlignment(cd.TopCenter);

// Add an orange (0xffcc66) zone from x = 18 to x = 20
c.xAxis().addZone(18, 20, "0xffcc66");

// Add a vertical brown (0x995500) mark line at x = 18
xMark1 = c.xAxis().addMark(18, "0x995500", "Backup Start");

// Set the mark line width to 2 pixels
xMark1.setLineWidth(2);

// Put the mark label at the left of the mark line
xMark1.setAlignment(cd.Left);

// Rotate the mark label by 90 degrees so it draws vertically
xMark1.setFontAngle(90);

// Add a vertical brown (0x995500) mark line at x = 20
xMark2 = c.xAxis().addMark(20, "0x995500", "Backup End");

// Set the mark line width to 2 pixels
xMark2.setLineWidth(2);

// Put the mark label at the right of the mark line
xMark2.setAlignment(cd.Right);

// Rotate the mark label by 90 degrees so it draws vertically
xMark2.setFontAngle(90);

// Add a green (0x00cc00) line layer with line width of 2 pixels
c.addLineLayer(data, "0x00cc00").setLineWidth(2);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "", "title='Load at {x}:00 = {value} MBytes'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Marks and Zones (2)
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Y Zone Coloring

Y Zone Coloring

This example demonstrates using y zone colors - colors that change at certain y value thresholds.

In this example, a y zone color is used as the fill color of an area layer, so that the area fill color changes above a certain threshold.

Y zone colors are created using Layer.yZoneColor. You can use a y zone color in any ChartDirector API that expects a color. For instance, you can use a y zone color as background color, fill color of data sets, line color, etc.

A single y zone color can support one threshold value and change between two colors. The two colors can be any colors, including another y zone color. You may create y zone colors with multiple thresholds by cascading multiple y zone colors this way.

Source Code Listing

[File: cfdemo/yzonecolor.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the chart
data = Array(30, 28, 40, 55, 75, 68, 54, 60, 50, 62, 75, 65, 75, 89, 60, 55, 53, 35,
    50, 66, 56, 48, 52, 65, 62);

// The labels for the chart
labels = Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12",
    "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24");

// Create a XYChart object of size 500 x 300 pixels, with a pale yellow (0xffffc0)
// background, a black border, and 1 pixel 3D border effect
c = cd.XYChart(500, 300, "0xffffc0", "0x000000", 1);

// Set search path to current directory for loading icon images
c.setSearchPath(GetPageContext());

// Set the plotarea at (55, 50) and of size 420 x 205 pixels, with white background.
// Turn on both horizontal and vertical grid lines with light grey color (0xc0c0c0)
c.setPlotArea(55, 50, 420, 205, "0xffffff").setGridColor("0xc0c0c0", "0xc0c0c0");

// Add a legend box at (55, 25) (top of the chart) with horizontal layout. Use 8 pts
// Arial font. Set the background and border color to Transparent.
legendBox = c.addLegend(55, 25, False, "", 8);
legendBox.setBackground(cd.Transparent);

// Add keys to the legend box to explain the color zones
legendBox.addKey("Normal Zone", "0x8033ff33");
legendBox.addKey("Alert Zone", "0x80ff3333");

// Add a title box to the chart using 13 pts Arial Bold Italic font. The title is in
// CDML and includes embedded images for highlight. The text is white (0xffffff) on a
// black background, with a 1 pixel 3D border.
c.addTitle(
    "<*block,valign=absmiddle*><*img=star.png*><*img=star.png*> Y Zone Color Demo " &
    "<*img=star.png*><*img=star.png*><*/*>", "Arial Bold Italic", 13, "0xffffff"
    ).setBackground("0x000000", -1, 1);

// Add a title to the y axis
c.yAxis().setTitle("Energy Concentration (KJ per liter)");

// Set the labels on the x axis.
c.xAxis().setLabels(labels);

// Display 1 out of 3 labels on the x-axis.
c.xAxis().setLabelStep(3);

// Add a title to the x axis using CDML
c.xAxis().setTitle(
    "<*block,valign=absmiddle*><*img=clock.png*>  Elapsed Time (hour)<*/*>");

// Set the axes width to 2 pixels
c.xAxis().setWidth(2);
c.yAxis().setWidth(2);

// Add an area layer to the chart. The area is using a y zone color, where the color
// is semi-transparent green below 60, and semi-transparent red above 60.
c.addAreaLayer(data, c.yZoneColor(60, "0x8033ff33", "0x80ff3333"));

// Add a custom CDML text at the bottom right of the plot area as the logo
c.addText(475, 255,
    "<*block,valign=absmiddle*><*img=small_molecule.png*> <*block*><*font=Times " &
    "New Roman Bold Italic,size=10,color=804040*>Molecular<*br*>Engineering<*/*>"
    ).setAlignment(cd.BottomRight);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "", "title='Hour {xLabel}: {value} KJ/liter'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Y Zone Coloring
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


X Zone Coloring

X Zone Coloring

This example demonstrates using x zone colors - colors that change at certain x value thresholds.

In this example, a x zone colors are used as the color of the line, and as the fill color of the band surrounding the line.

The x zone color for the line is configured to change from solid blue color to a red dash line color upon reaching a certain x value threshold. The x zone color for the band is configured to change from semi-transparent blue to semi-transparent red upon reaching the same threshold.

X zone colors are created using Layer.xZoneColor. You can use a x zone color in any ChartDirector API that expects a color. For instance, you can use a x zone color as background color, fill color of data sets, line color, etc.

A single x zone color can support one threshold value and change between two colors. The two colors can be any colors, including another x zone color. You may create x zone colors with multiple thresholds by cascading multiple x zone colors this way.

Source Code Listing

[File: cfdemo/xzonecolor.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the chart
data = Array(50, 55, 47, 34, 42, 49, 63, 62, 73, 59, 56, 50, 64, 60, 67, 67, 58, 59,
    73, 77, 84, 82, 80, 84, 89);

// The error data representing the error band around the data points
errData = Array(5, 6, 5.1, 6.5, 6.6, 8, 5.4, 5.1, 4.6, 5.0, 5.2, 6.0, 4.9, 5.6, 4.8,
    6.2, 7.4, 7.1, 6.5, 9.6, 12.1, 15.3, 18.5, 20.9, 24.1);

// The timestamps for the data
labels = Array(CreateDate(2001, 1, 1), CreateDate(2001, 2, 1), CreateDate(2001, 3, 1
    ), CreateDate(2001, 4, 1), CreateDate(2001, 5, 1), CreateDate(2001, 6, 1),
    CreateDate(2001, 7, 1), CreateDate(2001, 8, 1), CreateDate(2001, 9, 1),
    CreateDate(2001, 10, 1), CreateDate(2001, 11, 1), CreateDate(2001, 12, 1),
    CreateDate(2002, 1, 1), CreateDate(2002, 2, 1), CreateDate(2002, 3, 1),
    CreateDate(2002, 4, 1), CreateDate(2002, 5, 1), CreateDate(2002, 6, 1),
    CreateDate(2002, 7, 1), CreateDate(2002, 8, 1), CreateDate(2002, 9, 1),
    CreateDate(2002, 10, 1), CreateDate(2002, 11, 1), CreateDate(2002, 12, 1),
    CreateDate(2003, 1, 1));

// Create a XYChart object of size 550 x 220 pixels
c = cd.XYChart(550, 220);

// Set the plot area at (50, 10) and of size 480 x 180 pixels. Enabled both vertical
// and horizontal grids by setting their colors to light grey (cccccc)
c.setPlotArea(50, 10, 480, 180).setGridColor("0xcccccc", "0xcccccc");

// Add a legend box (50, 10) (top of plot area) using horizontal layout. Use 8 pts
// Arial font. Disable bounding box (set border to transparent).
legendBox = c.addLegend(50, 10, False, "", 8);
legendBox.setBackground(cd.Transparent);

// Add keys to the legend box to explain the color zones
legendBox.addKey("Historical", "0x9999ff");
legendBox.addKey("Forecast", "0xff9966");

// Add a title to the y axis.
c.yAxis().setTitle("Energy Consumption");

// Set the labels on the x axis
c.xAxis().setLabels2(labels);

// Set multi-style axis label formatting. Use Arial Bold font for yearly labels and
// display them as "yyyy". Use default font for monthly labels and display them as
// "mmm". Replace some labels with minor ticks to ensure the labels are at least 3
// units apart.
c.xAxis().setMultiFormat(cd.StartOfYearFilter(), "<*font=Arial Bold*>{value|yyyy}",
    cd.StartOfMonthFilter(), "{value|mmm}", 3);

// Add a line layer to the chart
layer = c.addLineLayer2();

// Create the color to draw the data line. The line is blue (0x333399) to the left of
// x = 18, and become a red (0xd04040) dash line to the right of x = 18.
lineColor = layer.xZoneColor(18, "0x333399", c.dashLineColor("0xd04040", cd.DashLine)
    );

// Add the data line
layer.addDataSet(data, lineColor, "Average");

// We are not showing the data set name in the legend box. The name is for showing in
// tool tips only.
layer.setLegend(cd.NoLegend);

// Create the color to draw the err zone. The color is semi-transparent blue
// (0x809999ff) to the left of x = 18, and become semi-transparent red (0x80ff9966)
// to the right of x = 18.
errColor = layer.xZoneColor(18, "0x809999ff", "0x80ff9966");

// Add the upper border of the err zone
layer.addDataSet(cd.ArrayMath(data).add(errData).result(), errColor, "Upper bound");

// Add the lower border of the err zone
layer.addDataSet(cd.ArrayMath(data).sub(errData).result(), errColor, "Lower bound");

// Set the default line width to 2 pixels
layer.setLineWidth(2);

// In this example, we are not showing the data set name in the legend box
layer.setLegend(cd.NoLegend);

// Color the region between the err zone lines
c.addInterLineLayer(layer.getLine(1), layer.getLine(2), errColor);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart.
imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName} on {xLabel|mmm yyyy}: {value} MJoule'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    X Zone Coloring
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Dual Y-Axis

Dual Y-Axis

This example demonstrates a chart with two independent y-axis.

ChartDirector supports arbitrary number of axes. The first two x and y axes are most commonly used and can be retrieved using XYChart.xAxis, XYChart.xAxis2, XYChart.yAxis and XYChart.yAxis2. These axes are by default put at the edges of the plot area.

By default, a data set will bind to the primary y-axis. This can be modified by using DataSet.setUseYAxis or DataSet.setUseYAxis2.

The y-axes in this example are of different colors. This is achieved by using Axis.setColors.

Source Code Listing

[File: cfdemo/dualyaxis.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the chart
data0 = Array(0.05, 0.06, 0.48, 0.1, 0.01, 0.05);
data1 = Array(100, 125, 265, 147, 67, 105);
labels = Array("Jan", "Feb", "Mar", "Apr", "May", "Jun");

// Create a XYChart object of size 300 x 180 pixels
c = cd.XYChart(300, 180);

// Set the plot area at (50, 20) and of size 200 x 130 pixels
c.setPlotArea(50, 20, 200, 130);

// Add a title to the chart using 8 pts Arial Bold font
c.addTitle("Independent Y-Axis Demo", "Arial Bold", 8);

// Set the labels on the x axis.
c.xAxis().setLabels(labels);

// Add a title to the primary (left) y axis
c.yAxis().setTitle("Packet Drop Rate (pps)");

// Set the axis, label and title colors for the primary y axis to red (0xc00000) to
// match the first data set
c.yAxis().setColors("0xc00000", "0xc00000", "0xc00000");

// Add a title to the secondary (right) y axis
c.yAxis2().setTitle("Throughtput (MBytes)");

// set the axis, label and title colors for the primary y axis to green (0x008000) to
// match the second data set
c.yAxis2().setColors("0x008000", "0x008000", "0x008000");

// Add a line layer to for the first data set using red (0xc00000) color with a line
// width to 3 pixels
lineLayer = c.addLineLayer(data0, "0xc00000");
lineLayer.setLineWidth(3);

// tool tip for the line layer
lineLayer.setHTMLImageMap("", "", "title='Packet Drop Rate on {xLabel}: {value} pps'"
    );

// Add a bar layer to for the second data set using green (0x00C000) color. Bind the
// second data set to the secondary (right) y axis
barLayer = c.addBarLayer(data1, "0x00c000");
barLayer.setUseYAxis2();

// tool tip for the bar layer
barLayer.setHTMLImageMap("", "", "title='Throughput on {xLabel}: {value} MBytes'");

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// include tool tip for the chart
imageMap1 = c.getHTMLImageMap("");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Dual Y-Axis
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Dual X-Axis

Dual X-Axis

This example demonstrates a chart with two x-axes and two y-axes.

ChartDirector supports arbitrary number of axes. The first two x and y axes are most commonly used and can be retrieved using XYChart.xAxis, XYChart.xAxis2, XYChart.yAxis and XYChart.yAxis2. These axes are by default positioned at the edges of the plot area.

The key features demonstrated in this example are:

  • Accessing both the top and bottom x-axes using XYChart.xAxis and XYChart.xAxis2 and set labels to both axes using Axis.setLabels.

  • Accessing both the primary and secondary y-axes by XYChart.yAxis and XYChart.yAxis2.

  • Synchronizing the primary and secondary y-axes by using XYChart.syncYAxis.

  • Use multiple x-axis label formats by using Axis.setMultiFormat.

  • Use Axis.setTickLength and Axis.setTickLength2 to control the axis ticks length and orientation (that is, internal or external to the chart)

Source Code Listing

[File: cfdemo/dualxaxis.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the chart
data0 = Array(42, 49, 33, 38, 51, 46, 29, 41, 44, 57, 59, 52, 37, 34, 51, 56, 56, 60,
    70, 76, 63, 67, 75, 64, 51);
data1 = Array(50, 55, 47, 34, 42, 49, 63, 62, 73, 59, 56, 50, 64, 60, 67, 67, 58, 59,
    73, 77, 84, 82, 80, 84, 98);

// The labels for the bottom x axis. Note the "-" means a minor tick.
labels0 = Array("0<*br*>Jun 4", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
    "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23",
    "0<*br*>Jun 5");

// The labels for the top x axis. Note that "-" means a minor tick.
labels1 = Array("Jun 3<*br*>12", "13", "14", "15", "16", "17", "18", "19", "20",
    "21", "22", "23", "Jun 4<*br*>0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
    "10", "11", "12");

// Create a XYChart object of size 310 x 310 pixels
c = cd.XYChart(310, 310);

// Set the plotarea at (50, 50) and of size 200 x 200 pixels
c.setPlotArea(50, 50, 200, 200);

// Add a title to the primary (left) y axis
c.yAxis().setTitle("US Dollars");

// Set the tick length to -4 pixels (-ve means ticks inside the plot area)
c.yAxis().setTickLength(-4);

// Add a title to the secondary (right) y axis
c.yAxis2().setTitle("HK Dollars (1 USD = 7.8 HKD)");

// Set the tick length to -4 pixels (-ve means ticks inside the plot area)
c.yAxis2().setTickLength(-4);

// Synchronize the y-axis such that y2 = 7.8 x y1
c.syncYAxis(7.8);

// Add a title to the bottom x axis
c.xAxis().setTitle("Hong Kong Time");

// Set the labels on the x axis.
c.xAxis().setLabels(labels0);

// Display 1 out of 3 labels on the x-axis. Show minor ticks for remaining labels.
c.xAxis().setLabelStep(3, 1);

// Set the major tick length to -4 pixels and minor tick length to -2 pixels (-ve
// means ticks inside the plot area)
c.xAxis().setTickLength2(-4, -2);

// Set the distance between the axis labels and the axis to 6 pixels
c.xAxis().setLabelGap(6);

// Add a title to the top x-axis
c.xAxis2().setTitle("New York Time");

// Set the labels on the x axis.
c.xAxis2().setLabels(labels1);

// Display 1 out of 3 labels on the x-axis. Show minor ticks for remaining labels.
c.xAxis2().setLabelStep(3, 1);

// Set the major tick length to -4 pixels and minor tick length to -2 pixels (-ve
// means ticks inside the plot area)
c.xAxis2().setTickLength2(-4, -2);

// Set the distance between the axis labels and the axis to 6 pixels
c.xAxis2().setLabelGap(6);

// Add a line layer to the chart with a line width of 2 pixels
c.addLineLayer(data0, -1, "Red Transactions").setLineWidth(2);

// Add an area layer to the chart with no area boundary line
c.addAreaLayer(data1, -1, "Green Transactions").setLineWidth(0);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName}<*br*>HKT Jun {=3.5+{x}/24|0} {={x}%24}:00 (NYT Jun " &
    "{=3+{x}/24|0} {=({x}+12)%24}:00)<*br*>HKD {={value}*7.8} (USD {value})'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Dual X-Axis
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Multiple Axes

Multiple Axes

This example demonstrates using 4 y-axes in a chart.

The 4 axes are the default primary and secondary y-axes at the left and right edges of the plot area, and two other y-axes added using XYChart.addAxis.

Layer.setUseYAxis and Layer.setUseYAxis2 are used to bind the line layers to the axes. Axis.setTitle and TextBox.setAlignment are used to set the axis titles and put them on the top of the axes. Axis.setColors is used to set the axis colors to be the same as the corresponding line layers for easy matching.

Source Code Listing

[File: cfdemo/multiaxes.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// Data for the chart
data0 = Array(1700, 3900, 2900, 3800, 4100, 4600, 2900, 4100, 4400, 5700, 5900, 5200,
    3700, 3400, 5100, 5600, 5600, 6000, 7000, 7600, 6300, 6700, 7500, 6400, 8800);
data1 = Array(500, 550, 670, 990, 820, 730, 800, 720, 730, 790, 860, 800, 840, 680,
    740, 890, 680, 790, 730, 770, 840, 820, 800, 840, 670);
data2 = Array(46, 68, 35, 33, 38, 20, 12, 18, 15, 23, 30, 24, 28, 15, 21, 26, 46, 42,
    38, 25, 23, 32, 24, 20, 25);
data3 = Array(0.84, 0.82, 0.82, 0.38, 0.25, 0.52, 0.54, 0.52, 0.38, 0.51, 0.46, 0.29,
    0.5, 0.55, 0.47, 0.34, 0.52, 0.33, 0.21, 0.3, 0.25, 0.15, 0.18, 0.22, 0.14);

// Labels for the chart
labels = Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12",
    "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24");

// Create a XYChart object of size 600 x 300 pixels, with a grey (eeeeee) background,
// a black border, and 1 pixel 3D border effect
c = cd.XYChart(600, 300, "0xeeeeee", "0x000000", 1);

// Add a title box to the chart using 15 pts Arial Bold Italic font, with blue
// (aaaaff) background
c.addTitle("Multiple Axes Demonstration", "Arial Bold Italic", 15).setBackground(
    "0xaaaaff");

// Set the plotarea at (100, 70) and of size 400 x 180 pixels, with white background.
// Turn on both horizontal and vertical grid lines with light grey color (cccccc)
c.setPlotArea(100, 70, 400, 180, "0xffffff").setGridColor("0xcccccc", "0xcccccc");

// Add a legend box at (300, 70) (top center of the chart) with horizontal layout.
// Use 8 pts Arial Bold font. Set the background and border color to Transparent.
legendBox = c.addLegend(300, 70, False, "Arial Bold", 8);
legendBox.setAlignment(cd.BottomCenter);
legendBox.setBackground(cd.Transparent, cd.Transparent);

// Set the labels on the x axis.
c.xAxis().setLabels(labels);

// Display 1 out of 3 labels on the x-axis.
c.xAxis().setLabelStep(3);

// Add a title to the x-axis
c.xAxis().setTitle("Hour of Day");

// Add a title on top of the primary (left) y axis.
c.yAxis().setTitle("Power<*br*>(Watt)").setAlignment(cd.TopLeft2);
// Set the axis, label and title colors for the primary y axis to red (c00000) to
// match the first data set
c.yAxis().setColors("0xcc0000", "0xcc0000", "0xcc0000");

// Add a title on top of the secondary (right) y axis.
c.yAxis2().setTitle("Load<*br*>(Mbps)").setAlignment(cd.TopRight2);
// Set the axis, label and title colors for the secondary y axis to green (00800000)
// to match the second data set
c.yAxis2().setColors("0x008000", "0x008000", "0x008000");

// Add the third y-axis at 50 pixels to the left of the plot area
leftAxis = c.addAxis(cd.Left, 50);
// Add a title on top of the third y axis.
leftAxis.setTitle("Temp<*br*>(C)").setAlignment(cd.TopLeft2);
// Set the axis, label and title colors for the third y axis to blue (0000cc) to
// match the third data set
leftAxis.setColors("0x0000cc", "0x0000cc", "0x0000cc");

// Add the fouth y-axis at 50 pixels to the right of the plot area
rightAxis = c.addAxis(cd.Right, 50);
// Add a title on top of the fourth y axis.
rightAxis.setTitle("Error<*br*>(%)").setAlignment(cd.TopRight2);
// Set the axis, label and title colors for the fourth y axis to purple (880088) to
// match the fourth data set
rightAxis.setColors("0x880088", "0x880088", "0x880088");

// Add a line layer to for the first data set using red (c00000) color, with a line
// width of 2 pixels
layer0 = c.addLineLayer(data0, "0xcc0000", "Power");
layer0.setLineWidth(2);

// Add a line layer to for the second data set using green (00c0000) color, with a
// line width of 2 pixels. Bind the layer to the secondary y-axis.
layer1 = c.addLineLayer(data1, "0x008000", "Load");
layer1.setLineWidth(2);
layer1.setUseYAxis2();

// Add a line layer to for the third data set using blue (0000cc) color, with a line
// width of 2 pixels. Bind the layer to the third y-axis.
layer2 = c.addLineLayer(data2, "0x0000cc", "Temperature");
layer2.setLineWidth(2);
layer2.setUseYAxis(leftAxis);

// Add a line layer to for the fourth data set using purple (880088) color, with a
// line width of 2 pixels. Bind the layer to the fourth y-axis.
layer3 = c.addLineLayer(data3, "0x880088", "Error Rate");
layer3.setLineWidth(2);
layer3.setUseYAxis(rightAxis);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName} at hour {xLabel} = {value}'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Multiple Axes
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


4 Quadrant Chart

4 Quadrant Chart

This example demonstrates 4 quadrant charts in which the x-axis and y-axis meet at the origin at the center of the plot area.

By default, ChartDirector puts the axes at the border of the plot area. This avoids the axis labels and the chart contents from overlapping and making the chart hard to read.

In some cases, it may be desirable to have one or both axes to intersect with the zero point of the other axis, where the zero point can be inside the plot area. In ChartDirector, these kinds of axis configurations may be set up with XYChart.setAxisAtOrigin.

This example also demonstrates using PlotArea.set4QBgColor to specify 4 background colors for the 4 quadrants.

Source Code Listing

[File: cfdemo/fourq.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// XY points for the scatter chart
dataX0 = Array(10, 15, 6, -12, 14, -8, 13, -13, 16, 12, 10.5);
dataY0 = Array(130, 150, 80, 110, -110, -105, -130, 115, -170, 125, 125);

dataX1 = Array(6, 7, -4, 3.5, 7, 8, -9, -10, -12, 11, 8);
dataY1 = Array(65, -40, -40, 45, -70, -80, 80, 10, -100, 105, 60);

dataX2 = Array(-10, -12, 11, 8, 6, 12, -4, 3.5, 7, 8, -9);
dataY2 = Array(65, -80, -40, 45, -70, -80, 80, 90, -100, 105, 60);

// Create a XYChart object of size 600 x 300 pixels, with a light blue (ccccff)
// background, a black border, and 1 pixel 3D border effect
c = cd.XYChart(600, 480, "0xccccff", "0x000000", 1);

// Add a title box to the chart using 16 pts Arial Bold Italic font, with white text
// on deep blue background
c.addTitle("Four Quadrant Chart Demonstration", "Arial Bold Italic", 16, "0xffffff"
    ).setBackground("0x000080");

// Set the plotarea at (20, 60) and of size 560 x 360 pixels, with grey (808080)
// border, and light grey (c0c0c0) horizontal and vertical grid lines. Set 4 quadrant
// coloring, where the colors of the quadrants alternate between lighter and deeper
// grey (dddddd/eeeeee)
c.setPlotArea(20, 60, 560, 360, -1, -1, "0x808080", "0xc0c0c0", "0xc0c0c0"
    ).set4QBgColor("0xdddddd", "0xeeeeee", "0xdddddd", "0xeeeeee");

// Set 4 quadrant mode, with both x and y axes symetrical around the origin
c.setAxisAtOrigin(cd.XYAxisAtOrigin, cd.XAxisSymmetric + cd.YAxisSymmetric);

// Add a legend box at (300, 460) (bottom center of the chart) with horizontal
// layout. Use 8 pts Arial Bold font.
legendBox = c.addLegend(300, 460, False, "Arial Bold", 8);
legendBox.setAlignment(cd.BottomCenter);

// Set legend box background to light grey (dddddd) with a black border
legendBox.setBackground("0xdddddd", 0);

// Set left/right margin to 20 pixels and top/bottom margin to 5 pixels
legendBox.setMargin2(20, 20, 5, 5);

// Add a titles to axes
c.xAxis().setTitle("Alpha Index");
c.yAxis().setTitle("Beta Index");

// Set axes width to 2 pixels
c.xAxis().setWidth(2);
c.yAxis().setWidth(2);

// Add scatter layer, using 15 pixels red (ff33333) X shape symbols
c.addScatterLayer(dataX0, dataY0, "Group A", cd.Cross2Shape(), 15, "0xff3333");

// Add scatter layer, using 15 pixels green (33ff33) 6-sided polygon symbols
c.addScatterLayer(dataX1, dataY1, "Group B", cd.PolygonShape(6), 15, "0x33ff33");

// Add scatter layer, using 15 pixels blue (3333ff) triangle symbols
c.addScatterLayer(dataX2, dataY2, "Group C", cd.TriangleSymbol, 15, "0x3333ff");

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='[{dataSetName}] Alpha = {x}, Beta = {value}'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    4 Quadrant Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Text Styles and Colors (2)

Text Styles and Colors (2)

This example demonstrates controlling text style and colors in various text containing objects (chart and axis titles, axis labels, legend keys, data labels, etc).

The chart title, y-axis title, y-axis labels, x-axis labels, legend keys, and the data labels are configured with different fonts and colors, and have different background and 3D border effects. The y-axis labels are appended with "Mbytes" as the unit. The x-axis labels are rotated 45 degrees.

Note that since ChartDirector Ver 3.0, you may use CDML to produce more sophisticated formatting effects than demonstrated in this example.

Source Code Listing

[File: cfdemo/fontxy.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the chart
data0 = Array(100, 125, 245, 147, 67);
data1 = Array(85, 156, 179, 211, 123);
data2 = Array(97, 87, 56, 267, 157);
labels = Array("Mon Jun 4", "Tue Jun 5", "Wed Jun 6", "Thu Jun 7", "Fri Jun 8");

// Create a XYChart object of size 540 x 350 pixels
c = cd.XYChart(540, 350);

// Set the plot area to start at (120, 40) and of size 280 x 240 pixels
c.setPlotArea(120, 40, 280, 240);

// Add a title to the chart using 20 pts Times Bold Italic (timesbi.ttf) font and
// using a deep blue color (0x000080)
c.addTitle("Weekly Server Load", "Times New Roman Bold Italic", 20, "0x000080");

// Add a legend box at (420, 100) (right of plot area) using 12 pts Times Bold font.
// Sets the background of the legend box to light grey 0xd0d0d0 with a 1 pixel 3D
// border.
c.addLegend(420, 100, True, "Times New Roman Bold", 12).setBackground("0xd0d0d0",
    "0xd0d0d0", 1);

// Add a title to the y-axis using 12 pts Arial Bold/deep blue (0x000080) font. Set
// the background to yellow (0xffff00) with a 2 pixel 3D border.
c.yAxis().setTitle("Throughput (per hour)", "Arial Bold", 12, "0x000080"
    ).setBackground("0xffff00", "0xffff00", 2);

// Use 10 pts Arial Bold/orange (0xcc6600) font for the y axis labels
c.yAxis().setLabelStyle("Arial Bold", 10, "0xcc6600");

// Set the axis label format to "nnn MBytes"
c.yAxis().setLabelFormat("{value} MBytes");

// Use 10 pts Arial Bold/green (0x008000) font for the x axis labels. Set the label
// angle to 45 degrees.
c.xAxis().setLabelStyle("Arial Bold", 10, "0x008000").setFontAngle(45);

// Set the labels on the x axis.
c.xAxis().setLabels(labels);

// Add a 3D stack bar layer with a 3D depth of 5 pixels
layer = c.addBarLayer2(cd.Stack, 5);

// Use Arial Italic as the default data label font in the bars
layer.setDataLabelStyle("Arial Italic");

// Use 10 pts Times Bold Italic (timesbi.ttf) as the aggregate label font. Set the
// background to flesh (0xffcc66) color with a 1 pixel 3D border.
layer.setAggregateLabelStyle("Times New Roman Bold Italic", 10).setBackground(
    "0xffcc66", cd.Transparent, 1);

// Add the first data set to the stacked bar layer
layer.addDataSet(data0, -1, "Server ##1");

// Add the second data set to the stacked bar layer
layer.addDataSet(data1, -1, "Server ##2");

// Add the third data set to the stacked bar layer, and set its data label font to
// Arial Bold Italic.
textbox = layer.addDataSet(data2, -1, "Server ##3").setDataLabelStyle(
    "Arial Bold Italic");

// Set the data label font color for the third data set to yellow (0xffff00)
textbox.setFontColor("0xffff00");

// Set the data label background color to the same color as the bar segment, with a 1
// pixel 3D border.
textbox.setBackground(cd.SameAsMainColor, cd.Transparent, 1);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName} on {xLabel}: {value} MBytes/hour'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Text Style and Colors
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Background and Wallpaper

Background and Wallpaper

This example demonstrates some of the background effects supported by ChartDirector.

ChartDirector supports using an image file as the wallpaper of the chart image background with BaseChart.setWallpaper, and as the plot area background with PlotArea.setBackground2.

In addition to wallpapers, ChartDirector supports alternating plot area background colors using PlotArea.setBackground and PlotArea.setAltBgColor.

You can switch the default colors to using a dark background with white lines and text in one step by changing the color palette to a whiteOnBlackPalette using BaseChart.setColors.

Source Code Listing

[File: cfdemo/background.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// Function to create the demo charts
function createChart(img)
{
    // Declare local variables
    var data = 0;
    var labels = 0;
    var c = 0;
    var plotarea = 0;
    var ret = 0;

    // The data for the chart
    data = Array(85, 156, 179.5, 211, 123);
    labels = Array("Mon", "Tue", "Wed", "Thu", "Fri");

    // Create a XYChart object of size 270 x 270 pixels
    c = cd.XYChart(270, 270);

    // Set search path to current directory for loading icon images
    c.setSearchPath(GetPageContext());

    // Set the plot area at (40, 32) and of size 200 x 200 pixels
    plotarea = c.setPlotArea(40, 32, 200, 200);

    // Set the background style based on the input parameter
    if (img EQ "0") {
        // Has wallpaper image
        c.setWallpaper("tile.gif");
    } else if (img EQ "1") {
        // Use a background image as the plot area background
        plotarea.setBackground2("bg.png");
    } else if (img EQ "2") {
        // Use white (0xffffff) and grey (0xe0e0e0) as two alternate plotarea
        // background colors
        plotarea.setBackground("0xffffff", "0xe0e0e0");
    } else {
        // Use a dark background palette
        c.setColors(cd.whiteOnBlackPalette);
    }

    // Set the labels on the x axis
    c.xAxis().setLabels(labels);

    // Add a color bar layer using the given data. Use a 1 pixel 3D border for the
    // bars.
    c.addBarLayer3(data).setBorderColor(-1, 1);

    // Output the chart
    ret = StructNew();
    ret.imageURL = c.makeSession(GetPageContext(), "chart" & img);

    // Include tool tip for the chart
    ret.imageMap = c.getHTMLImageMap("", "",
        "title='Revenue for {xLabel}: US${value}K'");

    return ret;
}

chart0 = createChart(0);
chart1 = createChart(1);
chart2 = createChart(2);
chart3 = createChart(3);

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Background and Wallpaper
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart0.imageURL#" usemap="##map0" border="0" />
<map name="map0">#chart0.imageMap#</map>
<img src="getchart.cfm?#chart1.imageURL#" usemap="##map1" border="0" />
<map name="map1">#chart1.imageMap#</map>
<img src="getchart.cfm?#chart2.imageURL#" usemap="##map2" border="0" />
<map name="map2">#chart2.imageMap#</map>
<img src="getchart.cfm?#chart3.imageURL#" usemap="##map3" border="0" />
<map name="map3">#chart3.imageMap#</map>
</cfoutput>
</body>
</html>


Log Scale Axis

Log Scale Axis

This example demonstrates using a log scale axis versus a linear scale axis.

In ChartDirector, log scale axis can be configured using Axis.setLogScale, Axis.setLogScale2 or Axis.setLogScale3.

Source Code Listing

[File: cfdemo/logaxis.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// Function to create the demo charts
function createChart(img)
{
    // Declare local variables
    var data = 0;
    var labels = 0;
    var c = 0;
    var ret = 0;

    // The data for the chart
    data = Array(100, 125, 260, 147, 67);
    labels = Array("Mon", "Tue", "Wed", "Thu", "Fri");

    // Create a XYChart object of size 200 x 180 pixels
    c = cd.XYChart(200, 180);

    // Set the plot area at (30, 10) and of size 140 x 130 pixels
    c.setPlotArea(30, 10, 140, 130);

    // Ise log scale axis if required
    if (img EQ "1") {
        c.yAxis().setLogScale3();
    }

    // Set the labels on the x axis
    c.xAxis().setLabels(labels);

    // Add a color bar layer using the given data. Use a 1 pixel 3D border for the
    // bars.
    c.addBarLayer3(data).setBorderColor(-1, 1);

    // Output the chart
    ret = StructNew();
    ret.imageURL = c.makeSession(GetPageContext(), "chart" & img);

    // Include tool tip for the chart
    ret.imageMap = c.getHTMLImageMap("", "",
        "title='Mileage on {xLabel}: {value} miles'");

    return ret;
}

chart0 = createChart(0);
chart1 = createChart(1);

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Log Scale Axis
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart0.imageURL#" usemap="##map0" border="0" />
<map name="map0">#chart0.imageMap#</map>
<img src="getchart.cfm?#chart1.imageURL#" usemap="##map1" border="0" />
<map name="map1">#chart1.imageMap#</map>
</cfoutput>
</body>
</html>


Y-Axis Scaling

Y-Axis Scaling

This example demonstrates how to control auto-scaling.

By default, ChartDirector auto-scales all axes. The Axis.setAutoScale method controls the top extension, bottom extension and the zero affinity parameters that ChartDirector uses during auto-scaling. The first two parameters determine the amount of top and bottom margins to reserve during auto-scaling, while the last parameter determines when the axis should start from the origin (0).

The first 3 charts demonstrate the effects of different top/bottom extensions.

The 4th chart demonstrates that one could exclude a segment on the ends of an axis from scaling using Axis.setMargin.

The 5th chart demonstrates manual scaling instead of auto-scaling. In manual scaling, the axis scale is explicitly provided by using Axis.setLinearScale, Axis.setLinearScale2, Axis.setLogScale, Axis.setLogScale2, Axis.setDateScale or Axis.setDateScale2.

Source Code Listing

[File: cfdemo/axisscale.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// Function to create the demo charts
function createChart(img)
{
    // Declare local variables
    var data = 0;
    var labels = 0;
    var c = 0;
    var ret = 0;

    // The data for the chart
    data = Array(5.5, 3.5, -3.7, 1.7, -1.4, 3.3);
    labels = Array("Jan", "Feb", "Mar", "Apr", "May", "Jun");

    // Create a XYChart object of size 200 x 180 pixels
    c = cd.XYChart(200, 180);

    // Set the plot area at (30, 20) and of size 140 x 130 pixels
    c.setPlotArea(30, 20, 140, 130);

    // Configure the axis as according to the input parameter
    if (img EQ "0") {
        c.addTitle("No Axis Extension", "Arial", 8);
    } else if (img EQ "1") {
        c.addTitle("Top/Bottom Extensions = 0/0", "Arial", 8);
        // Reserve 20% margin at top of plot area when auto-scaling
        c.yAxis().setAutoScale(0, 0);
    } else if (img EQ "2") {
        c.addTitle("Top/Bottom Extensions = 0.2/0.2", "Arial", 8);
        // Reserve 20% margin at top and bottom of plot area when auto-scaling
        c.yAxis().setAutoScale(0.2, 0.2);
    } else if (img EQ "3") {
        c.addTitle("Axis Top Margin = 15", "Arial", 8);
        // Reserve 15 pixels at top of plot area
        c.yAxis().setMargin(15);
    } else {
        c.addTitle("Manual Scale -5 to 10", "Arial", 8);
        // Set the y axis to scale from -5 to 10, with ticks every 5 units
        c.yAxis().setLinearScale(-5, 10, 5);
    }

    // Set the labels on the x axis
    c.xAxis().setLabels(labels);

    // Add a color bar layer using the given data. Use a 1 pixel 3D border for the
    // bars.
    c.addBarLayer3(data).setBorderColor(-1, 1);

    // Output the chart
    ret = StructNew();
    ret.imageURL = c.makeSession(GetPageContext(), "chart" & img);

    // Include tool tip for the chart
    ret.imageMap = c.getHTMLImageMap("", "", "title='ROI for {xLabel}: {value}%'");

    return ret;
}

chart0 = createChart(0);
chart1 = createChart(1);
chart2 = createChart(2);
chart3 = createChart(3);
chart4 = createChart(4);

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Y-Axis Scaling
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart0.imageURL#" usemap="##map0" border="0" />
<map name="map0">#chart0.imageMap#</map>
<img src="getchart.cfm?#chart1.imageURL#" usemap="##map1" border="0" />
<map name="map1">#chart1.imageMap#</map>
<img src="getchart.cfm?#chart2.imageURL#" usemap="##map2" border="0" />
<map name="map2">#chart2.imageMap#</map>
<img src="getchart.cfm?#chart3.imageURL#" usemap="##map3" border="0" />
<map name="map3">#chart3.imageMap#</map>
<img src="getchart.cfm?#chart4.imageURL#" usemap="##map4" border="0" />
<map name="map4">#chart4.imageMap#</map>
</cfoutput>
</body>
</html>


Tick Density

Tick Density

This example demonstrates how to control the axis tick density in auto-scaling.

By default, in auto-scaling, ChartDirector automatically chooses the tick spacing for the axis.

In some cases, you may want to suggest the tick spacing to use. This can be done by using Axis.setTickDensity.

Note that the actual tick spacing chosen by ChartDirector may not be equal to the suggested tick spacing. The suggested tick spacing is only a lower bound. It is because there may be other constraints when choosing the ticks. For example, the tick positions should be "neat numbers", such as (0, 5, 10, ...), and not arbitrary numbers like (0, 4.792, 9.584, ...). Also, by default, the axis starts and ends at tick positions (configurable using Axis.setRounding), which means the axis length must be divisible by the tick spacing. These and other constraints will affect the exact ticks being chosen.

In this example, one of the charts is drawn using the default tick spacing. The other chart is drawn using a suggested tick spacing of 10 pixels. Note that the actual tick spacing is slightly larger than 10 pixels.

Source Code Listing

[File: cfdemo/ticks.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// Function to create the demo charts
function createChart(img)
{
    // Declare local variables
    var data = 0;
    var labels = 0;
    var c = 0;
    var ret = 0;

    // The data for the chart
    data = Array(100, 125, 265, 147, 67, 105);
    labels = Array("Jan", "Feb", "Mar", "Apr", "May", "Jun");

    // Create a XYChart object of size 250 x 250 pixels
    c = cd.XYChart(250, 250);

    // Set the plot area at (27, 25) and of size 200 x 200 pixels
    c.setPlotArea(27, 25, 200, 200);

    if (img EQ "1") {
        // High tick density, uses 10 pixels as tick spacing
        c.addTitle("Tick Density = 10 pixels");
        c.yAxis().setTickDensity(10);
    } else {
        // Normal tick density, just use the default setting
        c.addTitle("Default Tick Density");
    }

    // Set the labels on the x axis
    c.xAxis().setLabels(labels);

    // Add a color bar layer using the given data. Use a 1 pixel 3D border for the
    // bars.
    c.addBarLayer3(data).setBorderColor(-1, 1);

    // Output the chart
    ret = StructNew();
    ret.imageURL = c.makeSession(GetPageContext(), "chart" & img);

    // Include tool tip for the chart
    ret.imageMap = c.getHTMLImageMap("", "",
        "title='Revenue for {xLabel}: US${value}M'");

    return ret;
}

chart0 = createChart(0);
chart1 = createChart(1);

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Tick Density
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart0.imageURL#" usemap="##map0" border="0" />
<map name="map0">#chart0.imageMap#</map>
<img src="getchart.cfm?#chart1.imageURL#" usemap="##map1" border="0" />
<map name="map1">#chart1.imageMap#</map>
</cfoutput>
</body>
</html>


Polar/Radar Charts

Polar/Radar Charts

In this section, we will discuss how to create polar/radar charts using ChartDirector through a number of examples.

Title | Description
Simple Radar Chart | Demonstrates the basic steps in creating radar charts.
Multi Radar Chart | Demonstrates a radar chart with two layers and a number of chart formatting effects.
Stacked Radar Chart | Demonstrates a stacked radar chart.
Polar Line Chart | Demonstrates a polar line chart, completed with data symbols and data labels.
Polar Area Chart | This examples demonstrates a polar area chart.
Polar Spline Chart | Demonstrates polar spline line and polar spline area.
Polar Scatter Chart | Demonstrates how to create polar scatter charts. Also demonstrates using alternating background colors along the angular direction.
Polar Bubble Chart | Demonstrates how to create polar bubble charts. Also demonstrates using alternating background colors along the radial direction.
Polar Vector Chart | Demonstrates a polar vector chart.
Simple Rose Chart | Demonstrates how to create a rose chart.
Stacked Rose Chart | Demonstrates how to create a stacked rose chart.
Circular Zones | Demonstrates adding circular zones to a polar chart.
Sector Zones | Demonstrates adding sector zones to a polar chart.


Simple Radar Chart

Simple Radar Chart

This example demonstrates the basic steps in creating radar charts.

  • Create a PolarChart object using PolarChart.PolarChart.

  • Specify the polar plot area of the chart using PolarChart.setPlotArea.

  • Add a polar area layer and specify the data for the area using PolarChart.addAreaLayer.

  • Specify the labels on the angular axis using AngularAxis.setLabels. In a polar/radar chart, the radial axis refers to the axis from the center to the perimeter of the plot area, and the angular axis refers to the axis lying on the perimeter of the plot area.

  • Generate the chart using BaseChart.makeSession.

  • Generate tool tips for the chart using BaseChart.getHTMLImageMap.

Source Code Listing

[File: cfdemo/simpleradar.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the chart
data = Array(90, 60, 65, 75, 40);

// The labels for the chart
labels = Array("Speed", "Reliability", "Comfort", "Safety", "Efficiency");

// Create a PolarChart object of size 450 x 350 pixels
c = cd.PolarChart(450, 350);

// Set center of plot area at (225, 185) with radius 150 pixels
c.setPlotArea(225, 185, 150);

// Add an area layer to the polar chart
c.addAreaLayer(data, "0x9999ff");

// Set the labels to the angular axis as spokes
c.angularAxis().setLabels(labels);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "", "title='{label}: score = {value}'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Simple Radar Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Multi Radar Chart

Multi Radar Chart

This example demonstrates a radar chart with two layers and a number of chart formatting effects.

  • Create a PolarChart object using PolarChart.PolarChart, using a golden color created with ChartDirector.CFChart.goldColor as the background color.

  • Add a title to the chart with white text on a deep blue background using BaseChart.addTitle.

  • Specify the polar plot area of the chart using PolarChart.setPlotArea.

  • Add a legend box to the chart using BaseChart.addLegend. Set the legend box background to silver with 3D border effect using Box.setBackground. The silver color is created using ChartDirector.CFChart.silverColor.

  • Add two polar area layers using PolarChart.addAreaLayer. Use semi-transparent colors as the area fill colors to avoid the top layer blocking the bottom layer.

  • Add two polar line layers with PolarChart.addLineLayer, using the same data as the polar area layer. Set a thick line width using PolarLayer.setLineWidth. The line layers becomes borders of the area layers to highlight the areas.

  • Specify the labels on the angular axis using AngularAxis.setLabels.

  • Generate the chart using BaseChart.makeSession.

  • Generate tool tips for the chart using BaseChart.getHTMLImageMap.

Source Code Listing

[File: cfdemo/multiradar.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the chart
data0 = Array(90, 60, 85, 75, 55);
data1 = Array(60, 80, 70, 80, 85);

// The labels for the chart
labels = Array("Speed", "Reliability", "Comfort", "Safety", "Efficiency");

// Create a PolarChart object of size 480 x 380 pixels. Set background color to gold,
// with 1 pixel 3D border effect
c = cd.PolarChart(480, 380, cd.goldColor(), "0x000000", 1);

// Add a title to the chart using 15 pts Times Bold Italic font. The title text is
// white (ffffff) on a deep blue (000080) background
c.addTitle("Space Travel Vehicles Compared", "Times New Roman Bold Italic", 15,
    "0xffffff").setBackground("0x000080");

// Set plot area center at (240, 210), with 150 pixels radius, and a white (ffffff)
// background.
c.setPlotArea(240, 210, 150, "0xffffff");

// Add a legend box at top right corner (470, 35) using 10 pts Arial Bold font. Set
// the background to silver, with 1 pixel 3D border effect.
b = c.addLegend(470, 35, True, "Arial Bold", 10);
b.setAlignment(cd.TopRight);
b.setBackground(cd.silverColor(), cd.Transparent, 1);

// Add an area layer to the chart using semi-transparent blue (0x806666cc). Add a
// blue (0x6666cc) line layer using the same data with 3 pixel line width to
// highlight the border of the area.
c.addAreaLayer(data0, "0x806666cc", "Model Saturn");
c.addLineLayer(data0, "0x6666cc").setLineWidth(3);

// Add an area layer to the chart using semi-transparent red (0x80cc6666). Add a red
// (0xcc6666) line layer using the same data with 3 pixel line width to highlight the
// border of the area.
c.addAreaLayer(data1, "0x80cc6666", "Model Jupiter");
c.addLineLayer(data1, "0xcc6666").setLineWidth(3);

// Set the labels to the angular axis as spokes.
c.angularAxis().setLabels(labels);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='[{dataSetName}] {label}: score = {value}'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Multi Radar Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Stacked Radar Chart

Stacked Radar Chart

This example demonstrates a stacked radar chart.

This example is similar to the previous Multi-Radar Chart example, except the data are stacked before passing to ChartDirector.

Source Code Listing

[File: cfdemo/stackradar.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the chart
data0 = Array(100, 100, 100, 100, 100);
data1 = Array(90, 85, 85, 80, 70);
data2 = Array(80, 65, 65, 75, 45);

// The labels for the chart
labels = Array("Population<*br*><*font=Arial*>6 millions",
    "GDP<*br*><*font=Arial*>120 billions", "Export<*br*><*font=Arial*>25 billions",
    "Import<*br*><*font=Arial*>24 billions",
    "Investments<*br*><*font=Arial*>20 billions");

// Create a PolarChart object of size 480 x 460 pixels. Set background color to
// silver, with 1 pixel 3D border effect
c = cd.PolarChart(480, 460, cd.silverColor(), "0x000000", 1);

// Add a title to the chart using 15 pts Times Bold Italic font. The title text is
// white (ffffff) on a deep green (008000) background
c.addTitle("Economic Growth", "Times New Roman Bold Italic", 15, "0xffffff"
    ).setBackground("0x008000");

// Set plot area center at (240, 270), with 150 pixels radius
c.setPlotArea(240, 270, 150);

// Use 1 pixel width semi-transparent black (c0000000) lines as grid lines
c.setGridColor("0xc0000000", 1, "0xc0000000", 1);

// Add a legend box at top-center of plot area (240, 35) using horizontal layout. Use
// 10 pts Arial Bold font, with silver background and 1 pixel 3D border effect.
b = c.addLegend(240, 35, False, "Arial Bold", 10);
b.setAlignment(cd.TopCenter);
b.setBackground(cd.silverColor(), cd.Transparent, 1);

// Add area layers of different colors to represent the data
c.addAreaLayer(data0, "0xcc8880", "Year 2004");
c.addAreaLayer(data1, "0xffd080", "Year 1994");
c.addAreaLayer(data2, "0xa0bce0", "Year 1984");

// Set the labels to the angular axis as spokes.
c.angularAxis().setLabels(labels);

// Set radial axis from 0 - 100 with a tick every 20 units
c.radialAxis().setLinearScale(0, 100, 20);

// Just show the radial axis as a grid line. Hide the axis labels by setting the
// label color to Transparent
c.radialAxis().setColors("0xc0000000", cd.Transparent);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='Current {label}: {value}% in {dataSetName}'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Stacked Radar Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Polar Line Chart

Polar Line Chart

This example demonstrates a polar line chart, completed with data symbols and data labels.

  • The grid lines in this example is circular (instead of polygonal as is in Simple Radar Chart). This is configured using PolarChart.setGridStyle.

  • The angular scale in this example is set to 0 - 360, with spokes every 30 units. This is by using AngularAxis.setLinearScale.

  • The two lines in this example is added using PolarChart.addLineLayer with angular coordinates of the points provided by PolarLayer.setAngles.

  • The data symbols are enabled using PolarLayer.setDataSymbol.

  • The data labels are configured using PolarLayer.setDataLabelFormat to consist of the radial and angular coordinates.

  • The data label background colors and 3D borders are configured using PolarLayer.setDataLabelStyle and Box.setBackground.

  • Note that the blue line in this example is a closed loop (the default), while the red is not a loop. This is configured by using PolarLineLayer.setCloseLoop.

Source Code Listing

[File: cfdemo/polarline.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the chart
data0 = Array(90, 25, 40, 55, 68, 44, 79, 85, 50);
angles0 = Array(15, 60, 110, 180, 230, 260, 260, 310, 340);

data1 = Array(80, 91, 66, 80, 92, 87);
angles1 = Array(40, 65, 88, 110, 150, 200);

// Create a PolarChart object of size 460 x 500 pixels, with a grey (e0e0e0)
// background and 1 pixel 3D border
c = cd.PolarChart(460, 500, "0xe0e0e0", "0x000000", 1);

// Set search path to current directory for loading icon images
c.setSearchPath(GetPageContext());

// Add a title to the chart at the top left corner using 15pts Arial Bold Italic
// font. Use a wood pattern as the title background.
c.addTitle("Polar Line Chart Demo", "Arial Bold Italic", 15).setBackground(
    c.patternColor("wood.png"));

// Set center of plot area at (230, 280) with radius 180 pixels, and white (ffffff)
// background.
c.setPlotArea(230, 280, 180, "0xffffff");

// Set the grid style to circular grid, with grids below the chart layers
c.setGridStyle(False, False);

// Add a legend box at top-center of plot area (230, 35) using horizontal layout. Use
// 10 pts Arial Bold font, with 1 pixel 3D border effect.
b = c.addLegend(230, 35, False, "Arial Bold", 9);
b.setAlignment(cd.TopCenter);
b.setBackground(cd.Transparent, cd.Transparent, 1);

// Set angular axis as 0 - 360, with a spoke every 30 units
c.angularAxis().setLinearScale(0, 360, 30);

// Add a blue (0xff) line layer to the chart using (data0, angle0)
layer0 = c.addLineLayer(data0, "0x0000ff", "Close Loop Line");
layer0.setAngles(angles0);

// Set the line width to 2 pixels
layer0.setLineWidth(2);

// Use 11 pixel triangle symbols for the data points
layer0.setDataSymbol(cd.TriangleSymbol, 11);

// Enable data label and set its format
layer0.setDataLabelFormat("({value},{angle})");

// Set the data label text box with light blue (0x9999ff) backgruond color and 1
// pixel 3D border effect
layer0.setDataLabelStyle().setBackground("0x9999ff", cd.Transparent, 1);

// Add a red (0xff0000) line layer to the chart using (data1, angle1)
layer1 = c.addLineLayer(data1, "0xff0000", "Open Loop Line");
layer1.setAngles(angles1);

// Set the line width to 2 pixels
layer1.setLineWidth(2);

// Use 11 pixel diamond symbols for the data points
layer1.setDataSymbol(cd.DiamondSymbol, 11);

// Set the line to open loop
layer1.setCloseLoop(False);

// Enable data label and set its format
layer1.setDataLabelFormat("({value},{angle})");

// Set the data label text box with light red (0xff9999) backgruond color and 1 pixel
// 3D border effect
layer1.setDataLabelStyle().setBackground("0xff9999", cd.Transparent, 1);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "", "title='[{dataSetName}] ({radius}, {angle})'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Polar Line Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Polar Area Chart

Polar Area Chart

This examples demonstrates a polar area chart.

The polar area layer is created using PolarChart.addAreaLayer. In this example, 3 area layers are used. The area data are already stacked before passing to ChartDirector.

Source Code Listing

[File: cfdemo/polararea.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// Data for the chart
data0 = Array(5, 3, 10, 4, 3, 5, 2, 5);
data1 = Array(12, 6, 17, 6, 7, 9, 4, 7);
data2 = Array(17, 7, 22, 7, 18, 13, 5, 11);

labels = Array("North", "North<*br*>East", "East", "South<*br*>East", "South",
    "South<*br*>West", "West", "North<*br*>West");

// Create a PolarChart object of size 460 x 500 pixels, with a grey (e0e0e0)
// background and 1 pixel 3D border
c = cd.PolarChart(460, 500, "0xe0e0e0", "0x000000", 1);

// Set search path to current directory for loading icon images
c.setSearchPath(GetPageContext());

// Add a title to the chart at the top left corner using 15pts Arial Bold Italic
// font. Use a wood pattern as the title background.
c.addTitle("Polar Area Chart Demo", "Arial Bold Italic", 15).setBackground(
    c.patternColor("wood.png"));

// Set center of plot area at (230, 280) with radius 180 pixels, and white (ffffff)
// background.
c.setPlotArea(230, 280, 180, "0xffffff");

// Set the grid style to circular grid
c.setGridStyle(False);

// Add a legend box at top-center of plot area (230, 35) using horizontal layout. Use
// 10 pts Arial Bold font, with 1 pixel 3D border effect.
b = c.addLegend(230, 35, False, "Arial Bold", 9);
b.setAlignment(cd.TopCenter);
b.setBackground(cd.Transparent, cd.Transparent, 1);

// Set angular axis using the given labels
c.angularAxis().setLabels(labels);

// Specify the label format for the radial axis
c.radialAxis().setLabelFormat("{value}%");

// Set radial axis label background to semi-transparent grey (40cccccc)
c.radialAxis().setLabelStyle().setBackground("0x40cccccc", 0);

// Add the data as area layers
c.addAreaLayer(data2, -1, "5 m/s or above");
c.addAreaLayer(data1, -1, "1 - 5 m/s");
c.addAreaLayer(data0, -1, "less than 1 m/s");

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "", "title='[{label}] {dataSetName}: {value}%'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Polar Area Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Polar Spline Chart

Polar Spline Chart

This example demonstrates polar spline line and polar spline area.

The polar spline line is created using PolarChart.addSplineLineLayer. The polar spline area is created using PolarChart.addSplineAreaLayer.

Source Code Listing

[File: cfdemo/polarspline.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the chart
data0 = Array(5.1, 2.6, 1.5, 2.2, 5.1, 4.3, 4.0, 9.0, 1.7, 8.8, 9.9, 9.5, 9.4, 1.8,
    2.1, 2.3, 3.5, 7.7, 8.8, 6.1, 5.0, 3.1, 6.0, 4.3);
angles0 = Array(0, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180, 195, 210,
    225, 240, 255, 270, 285, 300, 315, 330, 345);

data1 = Array(8.1, 2.5, 5, 5.2, 6.5, 8.5, 9, 7.6, 8.7, 6.4, 5.5, 5.4, 3.0, 8.7, 7.1,
    8.8, 7.9, 2.2, 5.0, 4.0, 1.5, 7.5, 8.3, 9.0);
angles1 = Array(0, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180, 195, 210,
    225, 240, 255, 270, 285, 300, 315, 330, 345);

// Create a PolarChart object of size 460 x 460 pixels
c = cd.PolarChart(460, 460);

// Add a title to the chart at the top left corner using 15pts Arial Bold Italic font
c.addTitle2(cd.TopLeft, "<*underline=2*>EM Field Strength", "Arial Bold Italic", 15);

// Set center of plot area at (230, 240) with radius 180 pixels
c.setPlotArea(230, 240, 180);

// Set the grid style to circular grid
c.setGridStyle(False);

// Add a legend box at the top right corner of the chart using 9 pts Arial Bold font
c.addLegend(459, 0, True, "Arial Bold", 9).setAlignment(cd.TopRight);

// Set angular axis as 0 - 360, with a spoke every 30 units
c.angularAxis().setLinearScale(0, 360, 30);

// Add a red (0xff9999) spline area layer to the chart using (data0, angles0)
c.addSplineAreaLayer(data0, "0xff9999", "Above 100MHz").setAngles(angles0);

// Add a blue (0xff) spline line layer to the chart using (data1, angle1)
layer1 = c.addSplineLineLayer(data1, "0x0000ff", "Below 100MHz");
layer1.setAngles(angles1);

// Set the line width to 3 pixels
layer1.setLineWidth(3);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName} EM field at {angle} deg: {value} Watt'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Polar Spline Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Polar Scatter Chart

Polar Scatter Chart

This example demonstrates how to create polar scatter charts. It also demonstrates using alternating background colors along the angular direction.

A polar scatter chart can be created as a polar line chart with data symbols. The line width is set to 0, so only the symbols can be seen. This will create the effects of a scatter chart.

The detail steps are:

  • Create a polar line layer using PolarChart.addLineLayer.

  • Enable data symbols for the line using PolarLayer.setDataSymbol (or PolarLayer.setDataSymbol2 or PolarLayer.setDataSymbol3 or PolarLayer.setDataSymbol4).

  • Disable the line by setting its width to 0 using PolarLayer.setLineWidth.
Note that in this example, the polar plot area uses two alternating background colors along the angular direction. This is by using PolarChart.setPlotAreaBg.

Source Code Listing

[File: cfdemo/polarscatter.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the chart
data0 = Array(43, 89, 76, 64, 48, 18, 92, 68, 44, 79, 71, 85);
angles0 = Array(45, 96, 169, 258, 15, 30, 330, 260, 60, 75, 110, 140);

data1 = Array(50, 91, 26, 29, 80, 53, 62, 87, 19, 40);
angles1 = Array(230, 210, 240, 310, 179, 250, 244, 199, 89, 160);

data2 = Array(88, 65, 76, 49, 80, 53);
angles2 = Array(340, 310, 340, 210, 30, 300);

// The labels on the angular axis (spokes)
labels = Array("North", "North<*br*>East", "East", "South<*br*>East", "South",
    "South<*br*>West", "West", "North<*br*>West");

// Create a PolarChart object of size 460 x 460 pixels
c = cd.PolarChart(460, 460);

// Add a title to the chart at the top left corner using 15pts Arial Bold Italic font
c.addTitle2(cd.TopLeft, "<*underline=2*>Plants in Wonderland", "Arial Bold Italic",
    15);

// Set center of plot area at (230, 240) with radius 180 pixels
c.setPlotArea(230, 240, 180);

// Use alternative light grey/dark grey sector background color
c.setPlotAreaBg("0xdddddd", "0xeeeeee", False);

// Set the grid style to circular grid
c.setGridStyle(False);

// Add a legend box at the top right corner of the chart using 9 pts Arial Bold font
c.addLegend(459, 0, True, "Arial Bold", 9).setAlignment(cd.TopRight);

// Set angular axis as 0 - 360, either 8 spokes
c.angularAxis().setLinearScale2(0, 360, labels);

// Set the radial axis label format
c.radialAxis().setLabelFormat("{value} km");

// Add a blue (0xff) polar line layer to the chart using (data0, angle0)
layer0 = c.addLineLayer(data0, "0x0000ff", "Immortal Weed");
layer0.setAngles(angles0);

layer0.setLineWidth(0);
layer0.setDataSymbol(cd.TriangleSymbol, 11);

// Add a red (0xff0000) polar line layer to the chart using (data1, angles1)
layer1 = c.addLineLayer(data1, "0xff0000", "Precious Flower");
layer1.setAngles(angles1);

// Disable the line by setting its width to 0, so only the symbols are visible
layer1.setLineWidth(0);

// Use a 11 pixel diamond data point symbol
layer1.setDataSymbol(cd.DiamondSymbol, 11);

// Add a green (0x00ff00) polar line layer to the chart using (data2, angles2)
layer2 = c.addLineLayer(data2, "0x00ff00", "Magical Tree");
layer2.setAngles(angles2);

// Disable the line by setting its width to 0, so only the symbols are visible
layer2.setLineWidth(0);

// Use a 9 pixel square data point symbol
layer2.setDataSymbol(cd.SquareSymbol, 9);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName} at ({value} km, {angle} deg)'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Polar Scatter Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Polar Bubble Chart

Polar Bubble Chart

This example demonstrates how to create polar bubble charts. It also demonstrates using alternating background colors along the radial direction.

A polar bubble chart can be created as a polar line chart with circles as data symbols. The line width is set to 0, so only the symbols can be seen. The symbol sizes are then controlled using another data series. This will create the effects of a bubble chart.

The detail steps are:

  • Create a polar line layer using PolarChart.addLineLayer.

  • Enable data symbols for the line using PolarLayer.setDataSymbol (or PolarLayer.setDataSymbol2 or PolarLayer.setDataSymbol3 or PolarLayer.setDataSymbol4). ChartDirector supports using arbitrary shapes as bubbles, although traditionally, circles are used.

  • Disable the line by setting its width to 0 using PolarLayer.setLineWidth.

  • Control the size of the symbols by a data series using PolarLayer.setSymbolScale.
Note that in this example, the polar plot area uses two alternating background colors along the radial direction. This is by using PolarChart.setPlotAreaBg.

Source Code Listing

[File: cfdemo/polarbubble.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the chart
data0 = Array(6, 12.5, 18.2, 15);
angles0 = Array(45, 96, 169, 258);
size0 = Array(41, 105, 12, 20);

data1 = Array(18, 16, 11, 14);
angles1 = Array(30, 210, 240, 310);
size1 = Array(30, 45, 12, 90);

// Create a PolarChart object of size 460 x 460 pixels
c = cd.PolarChart(460, 460);

// Add a title to the chart at the top left corner using 15pts Arial Bold Italic font
c.addTitle2(cd.TopLeft, "<*underline=2*>EM Field Strength", "Arial Bold Italic", 15);

// Set center of plot area at (230, 240) with radius 180 pixels
c.setPlotArea(230, 240, 180);

// Use alternative light grey/dark grey circular background color
c.setPlotAreaBg("0xdddddd", "0xeeeeee");

// Set the grid style to circular grid
c.setGridStyle(False);

// Add a legend box at the top right corner of the chart using 9 pts Arial Bold font
c.addLegend(459, 0, True, "Arial Bold", 9).setAlignment(cd.TopRight);

// Set angular axis as 0 - 360, with a spoke every 30 units
c.angularAxis().setLinearScale(0, 360, 30);

// Set the radial axis label format
c.radialAxis().setLabelFormat("{value} km");

// Add a blue (0x9999ff) line layer to the chart using (data0, angle0)
layer0 = c.addLineLayer(data0, "0x9999ff", "Cold Spot");
layer0.setAngles(angles0);

// Disable the line by setting its width to 0, so only the symbols are visible
layer0.setLineWidth(0);

// Use a circular data point symbol
layer0.setDataSymbol(cd.CircleSymbol, 11);

// Modulate the symbol size by size0 to produce a bubble chart effect
layer0.setSymbolScale(size0);

// Add a red (0xff9999) line layer to the chart using (data1, angle1)
layer1 = c.addLineLayer(data1, "0xff9999", "Hot Spot");
layer1.setAngles(angles1);

// Disable the line by setting its width to 0, so only the symbols are visible
layer1.setLineWidth(0);

// Use a circular data point symbol
layer1.setDataSymbol(cd.CircleSymbol, 11);

// Modulate the symbol size by size1 to produce a bubble chart effect
layer1.setSymbolScale(size1);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName} at ({value} km, {angle} deg)<*br*>Strength = {z} Watt'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Polar Bubble Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Polar Vector Chart

Polar Vector Chart

This example demonstrates a polar vector chart.

A vector chart is like a scatter chart, but the symbols are arrows which can be of arbitrary lengths pointing to arbitrary directions. Thus each symbol in a vector chart is specified by 4 values - the radial and angular coordinates, and the length and the direction.

In ChartDirector, a polar vector layer is created using PolarChart.addVectorLayer.

Source Code Listing

[File: cfdemo/polarvector.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// Coordinates of the starting points of the vectors
radius = Array(5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 10, 10, 10, 10, 10, 10, 10, 10,
    10, 10, 10, 10, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 20, 20, 20, 20,
    20, 20, 20, 20, 20, 20, 20, 20, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25);
angle = Array(0, 30, 60, 90, 120, 150, 180, 210, 240, 270, 300, 330, 0, 30, 60, 90,
    120, 150, 180, 210, 240, 270, 300, 330, 0, 30, 60, 90, 120, 150, 180, 210, 240,
    270, 300, 330, 0, 30, 60, 90, 120, 150, 180, 210, 240, 270, 300, 330, 0, 30, 60,
    90, 120, 150, 180, 210, 240, 270, 300, 330);

// Magnitude and direction of the vectors
magnitude = Array(5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
    4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1,
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);
direction = Array(60, 90, 120, 150, 180, 210, 240, 270, 300, 330, 0, 30, 60, 90, 120,
    150, 180, 210, 240, 270, 300, 330, 0, 30, 60, 90, 120, 150, 180, 210, 240, 270,
    300, 330, 0, 30, 60, 90, 120, 150, 180, 210, 240, 270, 300, 330, 0, 30, 60, 90,
    120, 150, 180, 210, 240, 270, 300, 330, 0, 30);

// Create a PolarChart object of size 460 x 460 pixels
c = cd.PolarChart(460, 460);

// Add a title to the chart at the top left corner using 15pts Arial Bold Italic font
c.addTitle("Polar Vector Chart Demonstration", "Arial Bold Italic", 15);

// Set center of plot area at (230, 240) with radius 180 pixels
c.setPlotArea(230, 240, 180);

// Set the grid style to circular grid
c.setGridStyle(False);

// Set angular axis as 0 - 360, with a spoke every 30 units
c.angularAxis().setLinearScale(0, 360, 30);

// Add a polar vector layer to the chart with blue (0000ff) vectors
c.addVectorLayer(radius, angle, magnitude, direction, cd.RadialAxisScale, "0x0000ff")
    ;

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='Vector at ({value}, {angle} deg): Length = {len}, Angle = {dir} deg'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Polar Vector Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Simple Rose Chart

Simple Rose Chart

This example demonstrates how to create a rose chart.

A rose chart is basically a polar chart with sectors of variable radius. This can be achieved by creating a PolarChart object as the graph paper, and adding sector zones on it using AngularAxis.addZone.

To enable auto-scale of the axis, in this example, we also add the radius data to a transparent line layer using PolarChart.addLineLayer. The line layer has no visible effect, but it causes the radial axis to auto-scale so that it covers the radius data.

Source Code Listing

[File: cfdemo/rose.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// Data for the chart
data = Array(9.4, 1.8, 2.1, 2.3, 3.5, 7.7, 8.8, 6.1, 5.0, 3.1, 6.0, 4.3, 5.1, 2.6,
    1.5, 2.2, 5.1, 4.3, 4.0, 9.0, 1.7, 8.8, 9.9, 9.5);
angles = Array(0, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180, 195, 210,
    225, 240, 255, 270, 285, 300, 315, 330, 345);

// Create a PolarChart object of size 460 x 460 pixels, with a silver background and
// a 1 pixel 3D border
c = cd.PolarChart(460, 460, cd.silverColor(), "0x000000", 1);

// Add a title to the chart at the top left corner using 15pts Arial Bold Italic
// font. Use white text on deep blue background.
c.addTitle("Polar Vector Chart Demonstration", "Arial Bold Italic", 15, "0xffffff"
    ).setBackground("0x000080");

// Set plot area center at (230, 240) with radius 180 pixels and white background
c.setPlotArea(230, 240, 180, "0xffffff");

// Set the grid style to circular grid
c.setGridStyle(False);

// Set angular axis as 0 - 360, with a spoke every 30 units
c.angularAxis().setLinearScale(0, 360, 30);

// Add sectors to the chart as sector zones
for (i = 0; i LT ArrayLen(data); i = i + 1) {
    c.angularAxis().addZone(angles[i + 1], angles[i + 1] + 15, 0, data[i + 1],
        "0x33ff33", "0x008000");
}

// Add an Transparent invisible layer to ensure the axis is auto-scaled using the
// data
c.addLineLayer(data, cd.Transparent);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Simple Rose Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" />
</cfoutput>
</body>
</html>


Stacked Rose Chart

Stacked Rose Chart

This example demonstrates how to create a stacked rose chart.

This example employs the same approach as the previous Simple Rose Chart example. It creates a PolarChart object as the graph paper, and adding sector zones on it using AngularAxis.addZone. A transparent line layer is used for enabling auto-scaling.

In this example, multiple sectors are added for each angular direction, creating a "stacked" effect.

Source Code Listing

[File: cfdemo/stackrose.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// Data for the chart
data0 = Array(5, 3, 10, 4, 3, 5, 2, 5);
data1 = Array(12, 6, 17, 6, 7, 9, 4, 7);
data2 = Array(17, 7, 22, 7, 18, 13, 5, 11);

angles = Array(0, 45, 90, 135, 180, 225, 270, 315);
labels = Array("North", "North<*br*>East", "East", "South<*br*>East", "South",
    "South<*br*>West", "West", "North<*br*>West");

// Create a PolarChart object of size 460 x 500 pixels, with a grey (e0e0e0)
// background and a 1 pixel 3D border
c = cd.PolarChart(460, 500, "0xe0e0e0", "0x000000", 1);

// Add a title to the chart at the top left corner using 15pts Arial Bold Italic
// font. Use white text on deep blue background.
c.addTitle("Wind Direction", "Arial Bold Italic", 15, "0xffffff").setBackground(
    "0x000080");

legendBox = c.addLegend(230, 35, False, "Arial Bold", 9);
legendBox.setAlignment(cd.TopCenter);
legendBox.setBackground(cd.Transparent, cd.Transparent, 1);

legendBox.addKey("5 m/s or above", "0xff3333");
legendBox.addKey("1 - 5 m/s", "0x33ff33");
legendBox.addKey("less than 1 m/s", "0x3333ff");

// Set plot area center at (230, 280) with radius 180 pixels and white background
c.setPlotArea(230, 280, 180, "0xffffff");

// Set the grid style to circular grid
c.setGridStyle(False);

// Set angular axis as 0 - 360, with a spoke every 30 units
c.angularAxis().setLinearScale2(0, 360, labels);

for (i = 0; i LT ArrayLen(angles); i = i + 1) {
    c.angularAxis().addZone(angles[i + 1] - 10, angles[i + 1] + 10, 0, data0[i + 1],
        "0x3333ff", 0);
    c.angularAxis().addZone(angles[i + 1] - 10, angles[i + 1] + 10, data0[i + 1],
        data1[i + 1], "0x33ff33", 0);
    c.angularAxis().addZone(angles[i + 1] - 10, angles[i + 1] + 10, data1[i + 1],
        data2[i + 1], "0xff3333", 0);
}

// Add an Transparent invisible layer to ensure the axis is auto-scaled using the
// data
c.addLineLayer(data2, cd.Transparent);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Stacked Rose Chart
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" />
</cfoutput>
</body>
</html>


Circular Zones

Circular Zones

This example demonstrates adding circular zones to a polar chart.

In ChartDirector, a zone defined on the radial axis will mark a radius range, and so will appear as ring on a polar chart.

This example contains three circular zones in the plot area background, colored as red, green and blue. The blue region is the original background of the plot area, while the red and green regions are added using Axis.addZone of the radial axis object.

Source Code Listing

[File: cfdemo/polarzones.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the chart
data = Array(51, 15, 51, 40, 17, 87, 94, 21, 35, 88, 50, 60);

// The labels for the chart
labels = Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct",
    "Nov", "Dec");

// Create a PolarChart object of size 400 x 420 pixels
c = cd.PolarChart(400, 420);

// Set background color to a 2 pixel pattern color, with a black border and 1 pixel
// 3D border effect
c.setBackground(c.patternColor(Array("0xffffff", "0xe0e0e0"), 2), 0, 1);

// Add a title to the chart using 16 pts Arial Bold Italic font. The title text is
// white (0xffffff) on 2 pixel pattern background
c.addTitle("Chemical Concentration", "Arial Bold Italic", 16, "0xffffff"
    ).setBackground(c.patternColor(Array("0x000000", "0x000080"), 2));

// Set center of plot area at (200, 240) with radius 145 pixels. Set background color
// to blue (9999ff)
c.setPlotArea(200, 240, 145, "0x9999ff");

// Color the region between radius = 40 to 80 as green (99ff99)
c.radialAxis().addZone(40, 80, "0x99ff99");

// Color the region with radius > 80 as red (ff9999)
c.radialAxis().addZone(80, 999, "0xff9999");

// Set the grid style to circular grid
c.setGridStyle(False);

// Set the radial axis label format
c.radialAxis().setLabelFormat("{value} ppm");

// Use semi-transparent (40ffffff) label background so as not to block the data
c.radialAxis().setLabelStyle().setBackground("0x40ffffff", "0x40000000");

// Add a legend box at (200, 30) top center aligned, using 9 pts Arial Bold font.
// with a black border.
legendBox = c.addLegend(200, 30, False, "Arial Bold", 9);
legendBox.setAlignment(cd.TopCenter);

// Add legend keys to represent the red/green/blue zones
legendBox.addKey("Under-Absorp", "0x9999ff");
legendBox.addKey("Normal", "0x99ff99");
legendBox.addKey("Over-Absorp", "0xff9999");

// Add a blue (000080) spline line layer with line width set to 3 pixels and using
// yellow (ffff00) circles to represent the data points
layer = c.addSplineLineLayer(data, "0x000080");
layer.setLineWidth(3);
layer.setDataSymbol(cd.CircleShape, 11, "0xffff00");

// Set the labels to the angular axis as spokes.
c.angularAxis().setLabels(labels);

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart.
imageMap1 = layer.getHTMLImageMap("", "",
    "title='Concentration on {label}: {value} ppm'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Circular Zones
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Sector Zones

Sector Zones

This example demonstrates adding sector zones to a polar chart.

In ChartDirector, a zone defined on the angular axis will mark an angular range, and so will appear as sectors on a polar chart.

This example contains three sector zones in the plot area background, colored as red, yellow and green. The green region is the original background of the plot area, while the red and yellow regions are added using AngularAxis.addZone.

Source Code Listing

[File: cfdemo/polarzones2.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the chart
data = Array(5.1, 1.5, 5.1, 4.0, 1.7, 8.7, 9.4, 2.1, 3.5, 8.8, 5.0, 6.0);

// The labels for the chart
labels = Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct",
    "Nov", "Dec");

// Create a PolarChart object of size 400 x 420 pixels. with a metallic blue (9999ff)
// background color and 1 pixel 3D border
c = cd.PolarChart(400, 420, cd.metalColor("0x9999ff"), "0x000000", 1);

// Add a title to the chart using 16 pts Arial Bold Italic font. The title text is
// white (0xffffff) on deep blue (000080) background
c.addTitle("Chemical Concentration", "Arial Bold Italic", 16, "0xffffff"
    ).setBackground("0x000080");

// Set center of plot area at (200, 240) with radius 145 pixels. Set background color
// to green (0x33ff33)
c.setPlotArea(200, 240, 145, "0x33ff33");

// Set the labels to the angular axis
c.angularAxis().setLabels(labels);

// Color the sector between label index = 5.5 to 7.5 as red (ff3333) zone
c.angularAxis().addZone(5.5, 7.5, "0xff3333");

// Color the sector between label index = 4.5 to 5.5, and also between 7.5 to 8.5, as
// yellow (ff3333) zones
c.angularAxis().addZone(4.5, 5.5, "0xffff00");
c.angularAxis().addZone(7.5, 8.5, "0xffff00");

// Set the grid style to circular grid
c.setGridStyle(False);

// Use semi-transparent (40ffffff) label background so as not to block the data
c.radialAxis().setLabelStyle().setBackground("0x40ffffff", "0x40000000");

// Add a legend box at (200, 30) top center aligned, using 9 pts Arial Bold font.
// with a black border.
legendBox = c.addLegend(200, 30, False, "Arial Bold", 9);
legendBox.setAlignment(cd.TopCenter);

// Add legend keys to represent the red/yellow/green zones
legendBox.addKey("Very Dry", "0xff3333");
legendBox.addKey("Critical", "0xffff00");
legendBox.addKey("Moderate", "0x33ff33");

// Add a blue (0x80) line layer with line width set to 3 pixels and use purple
// (ff00ff) cross symbols for the data points
layer = c.addLineLayer(data, "0x000080");
layer.setLineWidth(3);
layer.setDataSymbol(cd.Cross2Shape(), 15, "0xff00ff");

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart.
imageMap1 = layer.getHTMLImageMap("", "",
    "title='Concentration on {label}: {value} ppm'");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Sector Zones
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>
</cfoutput>
</body>
</html>


Meters and Gauges

Meters and Gauges

In this section, we will discuss how to create meters and gauges using ChartDirector through a number of examples.

Title | Description
Semi-Circle Meter | Demonstrates a simple half circle angular meter.
Round Meter | Demonstrates a round meter.
Wide Angular Meters | Demonstrates angular meters of which the width is large compared to the height. Also demonstrates various background effects.
Square Angular Meters | Demonstrates angular meters of which the pointers are pivoted at the corners of squares.
Multi-Pointer Angular Meter | Demonstrates adding multiple pointers of different styles to a meter.
Icon Angular Meter | Demonstrates a fuel-tank like meters, in which the meter is labelled by an icon and the scale shows text abbreviations.
Horizontal Linear Meter | Demonstrates a simple horizontal linear meter.
Vertical Linear Meter | Demonstrates a simple vertical linear meter.
Multi-Pointer Horizontal Meter | Demonstrates a horizontal linear meter with multiple pointers.
Multi-Pointer Vertical Meter | Demonstrates a vertical linear meter with multiple pointers.
Linear Zone Meter | Demonstrates a linear meter which is labelled with zones.


Semi-Circle Meter

Semi-Circle Meter

This example demonstrates a simple half circle angular meter.

A basic angular meter can be created using the following steps:

  • Create an AngularMeter object using AngularMeter.AngularMeter. In this example, the background color is set to silver using ChartDirector.CFChart.silverColor and the meter border is set to have a raised effect.

  • Specify the orientation of the meter using AngularMeter.setMeter. This specifies the center, the radius, and the angular span of the meter.

  • Set the numeric scale of the meter using BaseMeter.setScale

  • Add a pointer to the meter using BaseMeter.addPointer
In addition to the basic angular meter, this example demonstrates the following features:

  • Define zones on the meter using AngularMeter.addZone. In this example, 3 zones (red, yellow and green) are defined.

  • Add arbitrary text boxes to the meter using BaseChart.addText. In this example, a text box is added to specify the meter unit "PSI", and another text box is added to display the data value as text.
Note that by default, the drawing ordering of the text box objects and meter pointer follow the order in which they are added to the chart. Thus this sample code adds the meter pointer last, to ensure it stays on top of the custom text boxes.

Source Code Listing

[File: cfdemo/semicirclemeter.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The value to display on the meter
value = 27.48;

// Create an AngularMeter object of size 200 x 115 pixels, with silver background
// color, black border, 2 pixel 3D border border and rounded corners
m = cd.AngularMeter(200, 115, cd.silverColor(), "0x000000", 2);
m.setRoundedFrame();

// Set the meter center at (100, 100), with radius 85 pixels, and span from -90 to
// +90 degress (semi-circle)
m.setMeter(100, 100, 85, -90, 90);

// Meter scale is 0 - 100, with major tick every 20 units, minor tick every 10 units,
// and micro tick every 5 units
m.setScale(0, 100, 20, 10, 5);

// Set 0 - 60 as green (66FF66) zone
m.addZone(0, 60, 0, 85, "0x66ff66");

// Set 60 - 80 as yellow (FFFF33) zone
m.addZone(60, 80, 0, 85, "0xffff33");

// Set 80 - 100 as red (FF6666) zone
m.addZone(80, 100, 0, 85, "0xff6666");

// Add a text label centered at (100, 60) with 12 pts Arial Bold font
m.addText(100, 60, "PSI", "Arial Bold", 12, cd.TextColor, cd.Center);

// Add a text box at the top right corner of the meter showing the value formatted to
// 2 decimal places, using white text on a black background, and with 1 pixel 3D
// depressed border
m.addText(156, 8, m.formatValue(value, "2"), "Arial", 8, "0xffffff").setBackground(
    "0x000000", 0, -1);

// Add a semi-transparent blue (40666699) pointer with black border at the specified
// value
m.addPointer(value, "0x40666699", "0x000000");

// Output the chart
chart1URL = m.makeSession(GetPageContext(), "chart1");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Semi-Circle Meter
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" />
</cfoutput>
</body>
</html>


Round Meter

Round Meter

This example demonstrates a round meter.

This example is similar to the Semi-Circle Meter example, but with the angular range set to much wider. There are also more chart formatting and decorations.

First, a basic angular meter is created using the following steps:

  • Create an AngularMeter object using AngularMeter.AngularMeter. In this example, the background color is set to silver using ChartDirector.CFChart.silverColor and the meter border is set to have a depressed effect.

  • Specify the orientation of the meter using AngularMeter.setMeter. This specifies the center, the radius, and the angular span of the meter.

  • Set the numeric scale of the meter using BaseMeter.setScale

  • Add a pointer to the meter using BaseMeter.addPointer
Then more formatting and decorations are added. In this example, the following features are used:

  • Define zones on the meter using AngularMeter.addZone. In this example, 3 zones (red, yellow and green) are defined.

  • Add arbitrary text boxes to the meter using BaseChart.addText. In this example, a text box is added to label the meter as "CPU", and another text box is added to display the data value as text.

  • Set the scale and tick and line widths with BaseMeter.setLineWidth. The meter scale line is disabled by setting its line width to 0 (note there is no arc along the scale). The major tick width is set to 2 pixels, so the major ticks are thicker than the minor ticks.

  • Add a light blue ring to encircle the meter using AngularMeter.addRing.

  • Add a metallic blue circle as the meter face using AngularMeter.addRing.

Source Code Listing

[File: cfdemo/roundmeter.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The value to display on the meter
value = 45.17;

// Create an AugularMeter object of size 200 x 200 pixels, with silver background,
// black border, 2 pixel 3D depressed border and rounded corners.
m = cd.AngularMeter(200, 200, cd.silverColor(), "0x000000", -2);
m.setRoundedFrame();

// Set the meter center at (100, 100), with radius 85 pixels, and span from -135 to
// +135 degress
m.setMeter(100, 100, 85, -135, 135);

// Meter scale is 0 - 100, with major tick every 10 units, minor tick every 5 units,
// and micro tick every 1 units
m.setScale(0, 100, 10, 5, 1);

// Disable default angular arc by setting its width to 0. Set 2 pixels line width for
// major tick, and 1 pixel line width for minor ticks.
m.setLineWidth(0, 2, 1);

// Set the circular meter surface as metallic blue (9999DD)
m.addRing(0, 90, cd.metalColor("0x9999dd"));

// Add a blue (6666FF) ring between radii 88 - 90 as decoration
m.addRing(88, 90, "0x6666ff");

// Set 0 - 60 as green (99FF99) zone, 60 - 80 as yellow (FFFF00) zone, and 80 - 100
// as red (FF3333) zone
m.addZone(0, 60, "0x99ff99");
m.addZone(60, 80, "0xffff00");
m.addZone(80, 100, "0xff3333");

// Add a text label centered at (100, 135) with 15 pts Arial Bold font
m.addText(100, 135, "CPU", "Arial Bold", 15, cd.TextColor, cd.Center);

// Add a text box centered at (100, 165) showing the value formatted to 2 decimal
// places, using white text on a black background, and with 1 pixel 3D depressed
// border
m.addText(100, 165, m.formatValue(value, "2"), "Arial", 8, "0xffffff", cd.Center
    ).setBackground("0x000000", "0x000000", -1);

// Add a semi-transparent blue (40333399) pointer at the specified value
m.addPointer(value, "0x40333399");

// Output the chart
chart1URL = m.makeSession(GetPageContext(), "chart1");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Round Meter
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" />
</cfoutput>
</body>
</html>


Wide Angular Meters

Wide Angular Meters

This example demonstrates angular meters of which the width is large compared to the height. It also demonstrates various background effects.

The meters in this example are created by using large meter radii, but small angular spans. The center (pivot for the pointer) can then be put outside the meter region and the meters can be reduced in height.

This example also demonstrates metallic background effects and background patterns. The backgrounds are configured using BaseChart.setBackground. The metallic colors are created using ChartDirector.CFChart.goldColor, ChartDirector.CFChart.silverColor and ChartDirector.CFChart.metalColor. The background patterns are created by loading image files as pattern colors using BaseChart.patternColor2.

This example also shows the effect of the semi-transparent pointers, which can avoid blocking the labels on the meter.

Source Code Listing

[File: cfdemo/wideameter.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// Function to create the demo charts
function createChart(img)
{
    // Declare local variables
    var value = 0;
    var m = 0;

    // The value to display on the meter
    value = 6.5;

    // Create an AugularMeter object of size 200 x 100 pixels with rounded corners
    m = cd.AngularMeter(200, 100);

    // Set search path to current directory for loading icon images
    m.setSearchPath(GetPageContext());
    m.setRoundedFrame();

    // Set meter background according to a parameter
    if (img EQ "0") {
        // Use gold background color
        m.setBackground(cd.goldColor(), "0x000000", -2);
    } else if (img EQ "1") {
        // Use silver background color
        m.setBackground(cd.silverColor(), "0x000000", -2);
    } else if (img EQ "2") {
        // Use metallic blue (9898E0) background color
        m.setBackground(cd.metalColor("0x9898e0"), "0x000000", -2);
    } else if (img EQ "3") {
        // Use a wood pattern as background color
        m.setBackground(m.patternColor2("wood.png"), "0x000000", -2);
    } else if (img EQ "4") {
        // Use a marble pattern as background color
        m.setBackground(m.patternColor2("marble.png"), "0x000000", -2);
    } else {
        // Use a solid light purple (EEBBEE) background color
        m.setBackground("0xeebbee", "0x000000", -2);
    }

    // Set the meter center at (100, 235), with radius 210 pixels, and span from -24
    // to +24 degress
    m.setMeter(100, 235, 210, -24, 24);

    // Meter scale is 0 - 100, with a tick every 1 unit
    m.setScale(0, 10, 1);

    // Set 0 - 6 as green (99ff99) zone, 6 - 8 as yellow (ffff00) zone, and 8 - 10 as
    // red (ff3333) zone
    m.addZone(0, 6, "0x99ff99", "0x808080");
    m.addZone(6, 8, "0xffff00", "0x808080");
    m.addZone(8, 10, "0xff3333", "0x808080");

    // Add a title at the bottom of the meter using 10 pts Arial Bold font
    m.addTitle2(cd.Bottom, "OUTPUT POWER LEVEL<*br*>", "Arial Bold", 10);

    // Add a semi-transparent black (80000000) pointer at the specified value
    m.addPointer(value, "0x80000000");

    // Output the chart
    return m.makeSession(GetPageContext(), "chart" & img);
}

chart0URL = createChart(0);
chart1URL = createChart(1);
chart2URL = createChart(2);
chart3URL = createChart(3);
chart4URL = createChart(4);
chart5URL = createChart(5);

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Wide Angular Meters
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart0URL#" />
<img src="getchart.cfm?#chart1URL#" />
<img src="getchart.cfm?#chart2URL#" />
<img src="getchart.cfm?#chart3URL#" />
<img src="getchart.cfm?#chart4URL#" />
<img src="getchart.cfm?#chart5URL#" />
</cfoutput>
</body>
</html>


Square Angular Meters

Square Angular Meters

This example demonstrates angular meters of which the pointers are pivoted at the corners of squares.

The meters in this example are achieved by using various start angles and end angles with 90 degrees angular span between them.

Source Code Listing

[File: cfdemo/squareameter.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// Function to create the demo charts
function createChart(img)
{
    // Declare local variables
    var value = 0;
    var m = 0;

    // The value to display on the meter
    value = 4.75;

    // Create an AugularMeter object of size 110 x 110 pixels, using silver
    // background color with a black 2 pixel 3D depressed border.
    m = cd.AngularMeter(110, 110, cd.silverColor(), "0x000000", -2);

    // Set meter appearance according to a parameter
    if (img EQ "0") {
        // Set the meter center at bottom left corner (15, 95), with radius 85
        // pixels. Meter spans from 90 - 0 degrees.
        m.setMeter(15, 95, 85, 90, 0);
        // Add a label to the meter centered at (35, 75)
        m.addText(35, 75, "VDC", "Arial Bold", 12, cd.TextColor, cd.Center);
        // Add a text box to show the value at top right corner (103, 7)
        m.addText(103, 7, m.formatValue(value, "2"), "Arial", 8, "0xffffff",
            cd.TopRight).setBackground(0, 0, -1);
    } else if (img EQ "1") {
        // Set the meter center at top left corner (15, 15), with radius 85 pixels.
        // Meter spans from 90 - 180 degrees.
        m.setMeter(15, 15, 85, 90, 180);
        // Add a label to the meter centered at (35, 35)
        m.addText(35, 35, "AMP", "Arial Bold", 12, cd.TextColor, cd.Center);
        // Add a text box to show the value at bottom right corner (103, 103)
        m.addText(103, 103, m.formatValue(value, "2"), "Arial", 8, "0xffffff",
            cd.BottomRight).setBackground(0, 0, -1);
    } else if (img EQ "2") {
        // Set the meter center at top right corner (15, 95), with radius 85 pixels.
        // Meter spans from 270 - 180 degrees.
        m.setMeter(95, 15, 85, 270, 180);
        // Add a label to the meter centered at (75, 35)
        m.addText(75, 35, "KW", "Arial Bold", 12, cd.TextColor, cd.Center);
        // Add a text box to show the value at bottom left corner (7, 103)
        m.addText(7, 103, m.formatValue(value, "2"), "Arial", 8, "0xffffff",
            cd.BottomLeft).setBackground(0, 0, -1);
    } else {
        // Set the meter center at bottom right corner (95, 95), with radius 85
        // pixels. Meter spans from 270 - 360 degrees.
        m.setMeter(95, 95, 85, 270, 360);
        // Add a label to the meter centered at (75, 75)
        m.addText(75, 75, "RPM", "Arial Bold", 12, cd.TextColor, cd.Center);
        // Add a text box to show the value at top left corner (7, 7)
        m.addText(7, 7, m.formatValue(value, "2"), "Arial", 8, "0xffffff", cd.TopLeft
            ).setBackground(0, 0, -1);
    }

    // Meter scale is 0 - 10, with a major tick every 2 units, and minor tick every 1
    // unit
    m.setScale(0, 10, 2, 1);

    // Set 0 - 6 as green (99ff99) zone, 6 - 8 as yellow (ffff00) zone, and 8 - 10 as
    // red (ff3333) zone
    m.addZone(0, 6, "0x99ff99", "0x808080");
    m.addZone(6, 8, "0xffff00", "0x808080");
    m.addZone(8, 10, "0xff3333", "0x808080");

    // Add a semi-transparent black (80000000) pointer at the specified value
    m.addPointer(value, "0x80000000");

    // Output the chart
    return m.makeSession(GetPageContext(), "chart" & img);
}

chart0URL = createChart(0);
chart1URL = createChart(1);
chart2URL = createChart(2);
chart3URL = createChart(3);

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Square Angular Meters
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart0URL#" />
<img src="getchart.cfm?#chart1URL#" />
<img src="getchart.cfm?#chart2URL#" />
<img src="getchart.cfm?#chart3URL#" />
</cfoutput>
</body>
</html>


Multi-Pointer Angular Meter

Multi-Pointer Angular Meter

This example demonstrates adding multiple pointers of different styles to a meter.

ChartDirector supports adding arbitrary number of pointers to a meter using BaseMeter.addPointer. The shape of each pointer is configurable by using MeterPointer.setShape or MeterPointer.setShape2.

This example demonstrates the 5 different built-in angular pointer styles in ChartDirector. Note the use of semi-transparent colors to avoid the pointers blocking the labels or each others.

Source Code Listing

[File: cfdemo/multiameter.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// Create an AugularMeter object of size 200 x 200 pixels
m = cd.AngularMeter(200, 200);

// Use white on black color palette for default text and line colors
m.setColors(cd.whiteOnBlackPalette);

// Set the meter center at (100, 100), with radius 85 pixels, and span from 0 to 360
// degress
m.setMeter(100, 100, 85, 0, 360);

// Meter scale is 0 - 100, with major tick every 10 units, minor tick every 5 units,
// and micro tick every 1 units
m.setScale(0, 100, 10, 5, 1);

// Set angular arc, major tick and minor tick line widths to 2 pixels.
m.setLineWidth(2, 2, 2);

// Add a blue (9999ff) ring between radii 88 - 90 as decoration
m.addRing(88, 90, "0x9999ff");

// Set 0 - 60 as green (00AA00) zone, 60 - 80 as yellow (CCCC00) zone, and 80 - 100
// as red (AA0000) zone
m.addZone(0, 60, "0x00aa00");
m.addZone(60, 80, "0xcccc00");
m.addZone(80, 100, "0xaa0000");

// Add a text label centered at (100, 70) with 12 pts Arial Bold font
m.addText(100, 70, "PSI", "Arial Bold", 12, cd.TextColor, cd.Center);

// Add a semi-transparent blue (806666FF) pointer    using the default shape
m.addPointer(25, "0x806666ff", "0x6666ff");

// Add a semi-transparent red (80FF6666) pointer using the arrow shape
m.addPointer(9, "0x80ff6666", "0xff6666").setShape(cd.ArrowPointer2);

// Add a semi-transparent yellow (80FFFF66) pointer using another arrow shape
m.addPointer(51, "0x80ffff66", "0xffff66").setShape(cd.ArrowPointer);

// Add a semi-transparent green (8066FF66) pointer using the line shape
m.addPointer(72, "0x8066ff66", "0x66ff66").setShape(cd.LinePointer);

// Add a semi-transparent grey (80CCCCCC) pointer using the pencil shape
m.addPointer(85, "0x80cccccc", "0xcccccc").setShape(cd.PencilPointer);

// Output the chart
chart1URL = m.makeSession(GetPageContext(), "chart1");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Multi-Pointer Angular Meter
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" />
</cfoutput>
</body>
</html>


Icon Angular Meter

Icon Angular Meter

This example demonstrates a fuel-tank like meters, in which the meter is labelled by an icon and the scale shows text abbreviations.

The scale labels on the meter is created by using BaseMeter.setScale2. The icon is created by adding a custom text box with BaseChart.addText and using CDML to specify an icon.

Source Code Listing

[File: cfdemo/iconameter.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The value to display on the meter
value = 85;

// Create an AugularMeter object of size 70 x 90 pixels, using black background with
// a 2 pixel 3D depressed border.
m = cd.AngularMeter(70, 90, 0, 0, -2);

// Set search path to current directory for loading icon images
m.setSearchPath(GetPageContext());

// Use white on black color palette for default text and line colors
m.setColors(cd.whiteOnBlackPalette);

// Set the meter center at (10, 45), with radius 50 pixels, and span from 135 to 45
// degress
m.setMeter(10, 45, 50, 135, 45);

// Set meter scale from 0 - 100, with the specified labels
m.setScale2(0, 100, Array("E", " ", " ", " ", "F"));

// Set the angular arc and major tick width to 2 pixels
m.setLineWidth(2, 2);

// Add a red zone at 0 - 15
m.addZone(0, 15, "0xff3333");

// Add an icon at (25, 35)
m.addText(25, 35, "<*img=gas.gif*>");

// Add a yellow (ffff00) pointer at the specified value
m.addPointer(value, "0xffff00");

// Output the chart
chart1URL = m.makeSession(GetPageContext(), "chart1");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Icon Angular Meter
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" />
</cfoutput>
</body>
</html>


Horizontal Linear Meter

Horizontal Linear Meter

This example demonstrates a simple horizontal linear meter.

A basic linear meter can be created using the following steps:

  • Create a LinearMeter object using LinearMeter.LinearMeter. In this example, the background color is set to silver using ChartDirector.CFChart.silverColor and the meter border is set to have a depressed effect.

  • Specify the size of the meter scale region using LinearMeter.setMeter and the orientation of the scale labels. In this example, the scale labels are set at the top of the meter scale region. This automatically sets the meter as horizontal.

  • Set the numeric scale of the meter using BaseMeter.setScale

  • Add a pointer to the meter using BaseMeter.addPointer
In addition to the basic linear meter, this example demonstrates the following features:

  • Define zones on the meter using LinearMeter.addZone. In this example, 3 zones (red, yellow and green) are defined.

  • Add arbitrary text boxes to the meter using BaseChart.addText. In this example, a text box is added to specify the meter as showing temperature, and another text box is added to display the data value as text.

Source Code Listing

[File: cfdemo/hlinearmeter.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The value to display on the meter
value = 75.35;

// Create an LinearMeter object of size 250 x 75 pixels, using silver background with
// a 2 pixel black 3D depressed border.
m = cd.LinearMeter(250, 75, cd.silverColor(), 0, -2);

// Set the scale region top-left corner at (15, 25), with size of 200 x 50 pixels.
// The scale labels are located on the top (implies horizontal meter)
m.setMeter(15, 25, 220, 20, cd.Top);

// Set meter scale from 0 - 100, with a tick every 10 units
m.setScale(0, 100, 10);

// Set 0 - 50 as green (99ff99) zone, 50 - 80 as yellow (ffff66) zone, and 80 - 100
// as red (ffcccc) zone
m.addZone(0, 50, "0x99ff99");
m.addZone(50, 80, "0xffff66");
m.addZone(80, 100, "0xffcccc");

// Add a blue (0000cc) pointer at the specified value
m.addPointer(value, "0x0000cc");

// Add a label at bottom-left (10, 68) using Arial Bold/8 pts/red (c00000)
m.addText(10, 68, "Temperature C", "Arial Bold", 8, "0xc00000", cd.BottomLeft);

// Add a text box to show the value formatted to 2 decimal places at bottom right.
// Use white text on black background with a 1 pixel depressed 3D border.
m.addText(238, 70, m.formatValue(value, "2"), "Arial", 8, "0xffffff", cd.BottomRight
    ).setBackground(0, 0, -1);

// Output the chart
chart1URL = m.makeSession(GetPageContext(), "chart1");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Horizontal Linear Meter
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" />
</cfoutput>
</body>
</html>


Vertical Linear Meter

Vertical Linear Meter

This example demonstrates a simple vertical linear meter.

A basic linear meter can be created using the following steps:

  • Create a LinearMeter object using LinearMeter.LinearMeter. In this example, the background color is set to silver using ChartDirector.CFChart.silverColor and the meter border is set to have a depressed effect.

  • Specify the size of the meter scale region using LinearMeter.setMeter and the orientation of the scale labels. In this example, the scale labels are set at the left of the meter scale region. This automatically sets the meter as vertical.

  • Set the numeric scale of the meter using BaseMeter.setScale

  • Add a pointer to the meter using BaseMeter.addPointer
In addition to the basic linear meter, this example demonstrates the following features:

  • Define zones on the meter using LinearMeter.addZone. In this example, 3 zones (red, yellow and green) are defined.

  • Add arbitrary text boxes to the meter using BaseChart.addText. In this example, a text box is added to specify the meter as showing temperature, and another text box is added to display the data value as text.

Source Code Listing

[File: cfdemo/vlinearmeter.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The value to display on the meter
value = 75.35;

// Create an LinearMeter object of size 60 x 265 pixels, using silver background with
// a 2 pixel black 3D depressed border.
m = cd.LinearMeter(60, 265, cd.silverColor(), 0, -2);

// Set the scale region top-left corner at (25, 30), with size of 20 x 200 pixels.
// The scale labels are located on the left (default - implies vertical meter)
m.setMeter(25, 30, 20, 200);

// Set meter scale from 0 - 100, with a tick every 10 units
m.setScale(0, 100, 10);

// Set 0 - 50 as green (99ff99) zone, 50 - 80 as yellow (ffff66) zone, and 80 - 100
// as red (ffcccc) zone
m.addZone(0, 50, "0x99ff99");
m.addZone(50, 80, "0xffff66");
m.addZone(80, 100, "0xffcccc");

// Add a deep blue (000080) pointer at the specified value
m.addPointer(value, "0x000080");

// Add a text box label at top-center (30, 5) using Arial Bold/8 pts/deep blue
// (000088), with a light blue (9999ff) background
m.addText(30, 5, "Temp C", "Arial Bold", 8, "0x000088", cd.TopCenter).setBackground(
    "0x9999ff");

// Add a text box to show the value formatted to 2 decimal places at bottom center
// (30, 260). Use white text on black background with a 1 pixel depressed 3D border.
m.addText(30, 260, m.formatValue(value, "2"), "Arial", 8, "0xffffff", cd.BottomCenter
    ).setBackground(0, 0, -1);

// Output the chart
chart1URL = m.makeSession(GetPageContext(), "chart1");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Vertical Linear Meter
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" />
</cfoutput>
</body>
</html>


Multi-Pointer Horizontal Meter

Multi-Pointer Horizontal Meter

This example demonstrates a horizontal linear meter with multiple pointers.

ChartDirector supports adding arbitrary number of pointers to a meter using BaseMeter.addPointer. The shape of each pointer is configurable by using MeterPointer.setShape or MeterPointer.setShape2.

Source Code Listing

[File: cfdemo/multihmeter.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The values to display on the meter
value0 = 30.99;
value1 = 45.35;
value2 = 77.64;

// Create an LinearMeter object of size 250 x 75 pixels, using silver background with
// a 2 pixel black 3D depressed border.
m = cd.LinearMeter(250, 75, cd.silverColor(), 0, -2);

// Set the scale region top-left corner at (15, 25), with size of 220 x 20 pixels.
// The scale labels are located on the top (implies horizontal meter)
m.setMeter(15, 25, 220, 20, cd.Top);

// Set meter scale from 0 - 100, with a tick every 10 units
m.setScale(0, 100, 10);

// Set 0 - 50 as green (99ff99) zone, 50 - 80 as yellow (ffff66) zone, and 80 - 100
// as red (ffcccc) zone
m.addZone(0, 50, "0x99ff99");
m.addZone(50, 80, "0xffff66");
m.addZone(80, 100, "0xffcccc");

// Add deep red (000080), deep green (008000) and deep blue (800000) pointers to
// reflect the values
m.addPointer(value0, "0x000080");
m.addPointer(value1, "0x008000");
m.addPointer(value2, "0x800000");

// Add a label at bottom-left (10, 68) using Arial Bold/8 pts/red (c00000)
m.addText(10, 68, "Temp C", "Arial Bold", 8, "0xc00000", cd.BottomLeft);

// Add three text boxes to show the values in this meter
m.addText(148, 70, m.formatValue(value0, "2"), "Arial", 8, "0x6666ff", cd.BottomRight
    ).setBackground(0, 0, -1);
m.addText(193, 70, m.formatValue(value1, "2"), "Arial", 8, "0x33ff33", cd.BottomRight
    ).setBackground(0, 0, -1);
m.addText(238, 70, m.formatValue(value2, "2"), "Arial", 8, "0xff3333", cd.BottomRight
    ).setBackground(0, 0, -1);

// Output the chart
chart1URL = m.makeSession(GetPageContext(), "chart1");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Multi-Pointer Horizontal Meter
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" />
</cfoutput>
</body>
</html>


Multi-Pointer Vertical Meter

Multi-Pointer Vertical Meter

This example demonstrates a vertical linear meter with multiple pointers.

ChartDirector supports adding arbitrary number of pointers to a meter using BaseMeter.addPointer. The shape of each pointer is configurable by using MeterPointer.setShape or MeterPointer.setShape2.

Source Code Listing

[File: cfdemo/multivmeter.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The values to display on the meter
value0 = 30.99;
value1 = 45.35;
value2 = 77.64;

// Create an LinearMeter object of size 60 x 245 pixels, using silver background with
// a 2 pixel black 3D depressed border.
m = cd.LinearMeter(60, 245, cd.silverColor(), 0, -2);

// Set the scale region top-left corner at (25, 30), with size of 20 x 200 pixels.
// The scale labels are located on the left (default - implies vertical meter)
m.setMeter(25, 30, 20, 200);

// Set meter scale from 0 - 100, with a tick every 10 units
m.setScale(0, 100, 10);

// Set 0 - 50 as green (99ff99) zone, 50 - 80 as yellow (ffff66) zone, and 80 - 100
// as red (ffcccc) zone
m.addZone(0, 50, "0x99ff99");
m.addZone(50, 80, "0xffff66");
m.addZone(80, 100, "0xffcccc");

// Add deep red (000080), deep green (008000) and deep blue (800000) pointers to
// reflect the values
m.addPointer(value0, "0x000080");
m.addPointer(value1, "0x008000");
m.addPointer(value2, "0x800000");

// Add a text box label at top-center (30, 5) using Arial Bold/8 pts/deep blue
// (000088), with a light blue (9999ff) background
m.addText(30, 5, "Temp C", "Arial Bold", 8, "0x000088", cd.TopCenter).setBackground(
    "0x9999ff");

// Output the chart
chart1URL = m.makeSession(GetPageContext(), "chart1");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Multi-Pointer Vertical Meter
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" />
</cfoutput>
</body>
</html>


Linear Zone Meter

Linear Zone Meter

This example demonstrates a linear meter which is labelled with zones.

The above meter is achieved by using LinearMeter.addZone to add labelled zone. The black lines separating the zones are added by using BaseMeter.addLabel with empty spaces as labels.

Source Code Listing

[File: cfdemo/linearzonemeter.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The value to display on the meter
value = 85;

// Create an LinearMeter object of size 210 x 45 pixels, using silver background with
// a 2 pixel black 3D depressed border.
m = cd.LinearMeter(210, 45, cd.silverColor(), 0, -2);

// Set the scale region top-left corner at (5, 5), with size of 200 x 20 pixels. The
// scale labels are located on the bottom (implies horizontal meter)
m.setMeter(5, 5, 200, 20, cd.Bottom);

// Set meter scale from 0 - 100
m.setScale(0, 100);

// Add a title at the bottom of the meter with a 1 pixel raised 3D border
m.addTitle2(cd.Bottom, "Battery Level", "Arial Bold", 8).setBackground(
    cd.Transparent, -1, 1);

// Set 3 zones of different colors to represent Good/Weak/Bad data ranges
m.addZone(50, 100, "0x99ff99", "Good");
m.addZone(20, 50, "0xffff66", "Weak");
m.addZone(0, 20, "0xffcccc", "Bad");

// Add empty labels (just need the ticks) at 0/20/50/80 as separators for zones
m.addLabel(0, " ");
m.addLabel(20, " ");
m.addLabel(50, " ");
m.addLabel(100, " ");

// Add a semi-transparent blue (800000ff) pointer at the specified value, using
// triangular pointer shape
m.addPointer(value, "0x800000ff").setShape(cd.TriangularPointer);

// Output the chart
chart1URL = m.makeSession(GetPageContext(), "chart1");

</cfscript>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Linear Zone Meter
</div>
<hr style="border:solid 1px #000080" />
<cfoutput>
<div style="font-size:9pt; font-family:verdana; margin-bottom:1.5em">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" />
</cfoutput>
</body>
</html>


Using Data Sources with ChartDirector

Using Data Sources with ChartDirector

The ChartDirector API is designed to accept data values as array variables. This is the most flexible way of accepting data. This flexibility permits ChartDirector to accept data from all kinds of data sources. For example, ChartDirector can accept data from a database, a text file, XML, or as HTTP query parameters. All is needed is to read the data into array variables, and pass them to ChartDirector.

In this section

Database Sample Code Overview
Background information for running the database sample codes in this documentation.

Simple Database Chart
Complete example demonstrating how to perform database queries and create charts in the same script in a web environment.

Producing Multiple Charts With One Database Query
Complete example demonstrating how to perform database queries in the containing HTML page, and pass data to the ChartDirector scripts as HTTP query parameters.

Database Clickable Charts
This is a link to an example in the Clickable Charts section. This example demonstrates creating clickable charts with data coming from a database.


Database Sample Code Overview

Database Sample Code Overview

All ChartDirector database sample scripts described in this documentation are based on the sample MS Access database "sample.mdb" included in the "cfdemo" subdirectory.

To run this example, you need to set up the sample data source first. Please use your ColdFusion Administrator to create a data source as follows:

  • Use "cdsample" as the data source name

  • Use "Microsoft Access" as the driver

  • Use "ChartDirector/cfdemo/sample.mdb" as the database file

The "sample.mdb" is a MS Access database that contains only one table called "Revenue" . The table stores the monthly revenue data for three business units - Hardware, Software and Services. It contains four columns as follows:

Column Name | Type
TimeStamp | Date/Time
Hardware | Number
Software | Number
Services | Number

Each row in the database table contains monthly revenues for the business units, where the date is stored in the "TimeStamp" column. The sample database contains rows from Jan 1990 to Dec 2001.


Simple Database Chart

Simple Database Chart

In this example, we will demonstrate how to create a web page to show the monthly revenue for a given year. The user will select a year from a drop down list box, and press OK. The web server will query a database to obtain the necessary data, and return a web page containing the bar chart for the selected year.

Note: To run this example, you need to set up the sample data source first. Please refer to "Database Sample Code Overview" for details.

[File: cfdemo/dbdemo1.cfm]
<!--- All the years in the sample database --->
<cfquery name="allYears" datasource="cdsample">
    SELECT Year(timeStamp) As Year FROM Revenue GROUP BY Year(timeStamp)
    ORDER BY Year(timeStamp)
</cfquery>

<!--- Set currently selected year as according to user input, or to the latest year
      in the database if there is no user input --->
<cfset selectedYear = IIf(IsDefined("URL.year"), "URL.year",
    allYears["Year"][ArrayLen(allYears["Year"])])>

<!--- Query data from the selected year and read them into arrays --->
<cfquery name="selectedData" datasource="cdsample">
    SELECT * FROM Revenue WHERE Year(timeStamp) = #selectedYear# Order By timeStamp
</cfquery>
<cfset software = selectedData["Software"].toArray()>
<cfset hardware = selectedData["Hardware"].toArray()>
<cfset services = selectedData["Services"].toArray()>

<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// Create a XYChart object of size 600 x 300 pixels, with a light grey (eeeeee)
// background, black border, 1 pixel 3D border effect and rounded corners.
c = cd.XYChart(600, 300, "0xeeeeee", "0x000000", 1);
c.setRoundedFrame();

// Set the plotarea at (60, 60) and of size 520 x 200 pixels. Set background color to
// white (ffffff) and border and grid colors to grey (cccccc)
c.setPlotArea(60, 60, 520, 200, "0xffffff", -1, "0xcccccc", "0xccccccc");

// Add a title to the chart using 15pts Times Bold Italic font, with a light blue
// (ccccff) background and with glass lighting effects.
c.addTitle("Global Revenue for Year " & selectedYear, "Times New Roman Bold Italic",
    15).setBackground("0xccccff", "0x000000", cd.glassEffect());

// Add a legend box at (70, 32) (top of the plotarea) with 9pts Arial Bold font
c.addLegend(70, 32, False, "Arial Bold", 9).setBackground(cd.Transparent);

// Add a stacked bar chart layer using the supplied data
layer = c.addBarLayer2(cd.Stack);
layer.addDataSet(software, "0xff0000", "Software");
layer.addDataSet(hardware, "0x00ff00", "Hardware");
layer.addDataSet(services, "0xffaa00", "Services");

// Use soft lighting effect with light direction from the left
layer.setBorderColor(cd.Transparent, cd.softLighting(cd.Left));

// Set the x axis labels. In this example, the labels must be Jan - Dec.
labels = Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct",
    "Nov", "Dec");
c.xAxis().setLabels(labels);

// Draw the ticks between label positions (instead of at label positions)
c.xAxis().setTickOffset(0.5);

// Set the y axis title
c.yAxis().setTitle("USD (Millions)");

// Set axes width to 2 pixels
c.xAxis().setWidth(2);
c.yAxis().setWidth(2);

// Output the chart in PNG format
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Include tool tip for the chart
imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName} Revenue for {xLabel} = USD {value}M'");

</cfscript>

<html>
<cfoutput>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Database Integration Demo (1)
</div>
<hr style="border:solid 1px ##000080" />
<div style="font-size:10pt; font-family:verdana; margin-bottom:20px">
<a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>
    View Source Code
</a>
<br />
<br />
</div>

<form>
    I want to obtain the revenue data for the year
    <select name="year"><cfloop query="allYears">
        <option value="#Year#" #IIf(Year EQ selectedYear, """Selected""", """""")#>
            #Year#
        </option>
    </cfloop></select>
    <input type="submit" value="OK">
</form>

<img src="getchart.cfm?#chart1URL#" usemap="##map1" border="0" />
<map name="map1">#imageMap1#</map>

</body>
</cfoutput>
</html>

At the beginning of the above code are two ColdFusion database queries. The first query gets all the years in the database to fill up the drop down list box, so the user can select the year. The second query gets the data for the selected year for creating the chart. The query columns are read into array variables (using the "toArray" method) for passing to ChartDirector.

<!--- All the years in the sample database --->
<cfquery name="allYears" datasource="cdsample">
    SELECT Year(timeStamp) As Year FROM Revenue GROUP BY Year(timeStamp)
    ORDER BY Year(timeStamp)
</cfquery>

<!--- Set currently selected year as according to user input, or to the latest year
      in the database if there is no user input --->
<cfset selectedYear = IIf(IsDefined("URL.year"), "URL.year",
    allYears["Year"][ArrayLen(allYears["Year"])])>

<!--- Query data from the selected year and read them into arrays --->
<cfquery name="selectedData" datasource="cdsample">
    SELECT * FROM Revenue WHERE Year(timeStamp) = #selectedYear# Order By timeStamp
</cfquery>
<cfset software = selectedData["Software"].toArray()>
<cfset hardware = selectedData["Hardware"].toArray()>
<cfset services = selectedData["Services"].toArray()>

After we read the data into arrays, the second part of the code is to create a stacked bar chart using the given data. This is very similar to the examples in other parts of this documentation, so it will not be explained further.


Producing Multiple Charts With One Database Query

Producing Multiple Charts With One Database Query

In this example, we will demonstrate how to produce multiple charts on the same page, in which the data come from the same database query.

As similar to the last example, the user will select a year from a drop down list box and press OK. The web server will query a database to obtain the necessary data, and return a web page containing two charts about the selected year.

Note: To run this example, you need to set up the sample data source first. Please refer to "Database Sample Code Overview" for details.

[File: cfdemo/dbdemo2.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

//
// Create the first chart based on the given data
//
function createChart1(selectedYear, software, hardware, services)
{
    // Declare local variables
    var c = 0;
    var layer = 0;
    var labels = 0;

    // Create a XYChart object of size 600 x 300 pixels, with a light grey (eeeeee)
    // background, black border, 1 pixel 3D border effect and rounded corners.
    c = cd.XYChart(600, 300, "0xeeeeee", "0x000000", 1);
    c.setRoundedFrame();

    // Set the plotarea at (60, 60) and of size 520 x 200 pixels. Set background
    // color to white (ffffff) and border and grid colors to grey (cccccc)
    c.setPlotArea(60, 60, 520, 200, "0xffffff", -1, "0xcccccc", "0xccccccc");

    // Add a title to the chart using 15pts Times Bold Italic font, with a light blue
    // (ccccff) background and with glass lighting effects.
    c.addTitle("Global Revenue for Year " & selectedYear,
        "Times New Roman Bold Italic", 15).setBackground("0xccccff", "0x000000",
        cd.glassEffect());

    // Add a legend box at (70, 32) (top of the plotarea) with 9pts Arial Bold font
    c.addLegend(70, 32, False, "Arial Bold", 9).setBackground(cd.Transparent);

    // Add a line chart layer using the supplied data
    layer = c.addLineLayer2();
    layer.addDataSet(software, "0xff0000", "Software").setDataSymbol(cd.CircleShape,
        9);
    layer.addDataSet(hardware, "0x00ff00", "Hardware").setDataSymbol(cd.DiamondShape,
        11);
    layer.addDataSet(services, "0xffaa00", "Services").setDataSymbol(cd.Cross2Shape(
        ), 11);

    // Set the line width to 3 pixels
    layer.setLineWidth(3);

    // Set the x axis labels. In this example, the labels must be Jan - Dec.
    labels = Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept",
        "Oct", "Nov", "Dec");
    c.xAxis().setLabels(labels);

    // Set the y axis title
    c.yAxis().setTitle("USD (Millions)");

    // Set axes width to 2 pixels
    c.xAxis().setWidth(2);
    c.yAxis().setWidth(2);

    // Output the chart
    ret = StructNew();
    ret.imageURL = c.makeSession(getPageContext(), "chart1");

    // Include tool tip for the chart
    ret.imageMap = c.getHTMLImageMap("", "",
        "title='{dataSetName} Revenue for {xLabel} = USD {value}M'");
    return ret;
}

//
// Create the second chart based on the given data
//
function createChart2(selectedYear, software, hardware, services)
{
    // Declare local variables
    var c = 0;
    var layer = 0;
    var labels = 0;

    // Create a XYChart object of size 600 x 300 pixels, with a light grey (eeeeee)
    // background, black border, 1 pixel 3D border effect and rounded corners.
    c = cd.XYChart(600, 300, "0xeeeeee", "0x000000", 1);
    c.setRoundedFrame();

    // Set the plotarea at (60, 60) and of size 520 x 200 pixels. Set background
    // color to white (ffffff) and border and grid colors to grey (cccccc)
    c.setPlotArea(60, 60, 520, 200, "0xffffff", -1, "0xcccccc", "0xccccccc");

    // Add a title to the chart using 15pts Times Bold Italic font, with a dark green
    // (006600) background and with glass lighting effects.
    c.addTitle("Global Revenue for Year " & selectedYear,
        "Times New Roman Bold Italic", 15, "0xffffff").setBackground("0x006600",
        "0x000000", cd.glassEffect(cd.ReducedGlare));

    // Add a legend box at (70, 32) (top of the plotarea) with 9pts Arial Bold font
    c.addLegend(70, 32, False, "Arial Bold", 9).setBackground(cd.Transparent);

    // Add a stacked area chart layer using the supplied data
    layer = c.addAreaLayer2(cd.Stack);
    layer.addDataSet(software, "0x40ff0000", "Software");
    layer.addDataSet(hardware, "0x4000ff00", "Hardware");
    layer.addDataSet(services, "0x40ffaa00", "Services");

    // Set the area border color to the same as the fill color
    layer.setBorderColor(cd.SameAsMainColor);

    // Set the x axis labels. In this example, the labels must be Jan - Dec.
    labels = Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept",
        "Oct", "Nov", "Dec");
    c.xAxis().setLabels(labels);

    // Set the y axis title
    c.yAxis().setTitle("USD (Millions)");

    // Set axes width to 2 pixels
    c.xAxis().setWidth(2);
    c.yAxis().setWidth(2);

    // Output the chart
    ret = StructNew();
    ret.imageURL = c.makeSession(getPageContext(), "chart2");

    // Include tool tip for the chart
    ret.imageMap = c.getHTMLImageMap("", "",
        "title='{dataSetName} Revenue for {xLabel} = USD {value}M'");
    return ret;
}

</cfscript>

<!--- All the years in the sample database --->
<cfquery name="allYears" datasource="cdsample">
    SELECT Year(timeStamp) As Year FROM Revenue GROUP BY Year(timeStamp)
    ORDER BY Year(timeStamp)
</cfquery>

<!--- Set currently selected year as according to user input, or to the latest year
      in the database if there is no user input --->
<cfset selectedYear = IIf(IsDefined("URL.year"), "URL.year",
    allYears["Year"][ArrayLen(allYears["Year"])])>

<!--- Query data from the selected year and read them into arrays --->
<cfquery name="selectedData" datasource="cdsample">
    SELECT * FROM Revenue WHERE Year(timeStamp) = #selectedYear# Order By timeStamp
</cfquery>
<cfset software = selectedData["Software"].toArray()>
<cfset hardware = selectedData["Hardware"].toArray()>
<cfset services = selectedData["Services"].toArray()>

<!--- Draw the charts --->
<cfset chart1 = createChart1(selectedYear, software, hardware, services)>
<cfset chart2 = createChart2(selectedYear, software, hardware, services)>

<html>
<cfoutput>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Database Integration Demo (2)
</div>
<hr style="border:solid 1px ##000080" />
<div style="font-size:10pt; font-family:verdana; width:600px">
<form>
    I want to obtain the revenue data for the year
    <select name="year"><cfloop query="allYears">
        <option value="#Year#" #IIf(Year EQ selectedYear, """Selected""", """""")#>
            #Year#
        </option>
    </cfloop></select>
    <input type="submit" value="OK">
</form>
</div>

<img src="getchart.cfm?#chart1.imageURL#" usemap="##map1" border="0" />
<map name="map1">#chart1.imageMap#</map>
<br><b>
<img src="getchart.cfm?#chart2.imageURL#" usemap="##map2" border="0" />
<map name="map2">#chart2.imageMap#</map>

</body>
</cfoutput>
</html>

The above code contains two methods for generating charts and putting the charts. The data for the charts are passed in as arguments.

function createChart1(selectedYear, software, hardware, services) { ... }
function createChart2(selectedYear, software, hardware, services) { ... }

In the code, database queries are used to obtain the data. The resulting query columns are read into array variables. This is the same as the previous example.

In this example, the data are passed to the two chart generating methods to create two charts.

<cfset chart1 = createChart1(selectedYear, software, hardware, services)>
<cfset chart2 = createChart2(selectedYear, software, hardware, services)>

The outputs are then used in the <IMG> and <MAP> tags for including the chart images and the image map in the HTML web page.


Clickable Charts

Clickable Charts

This section describes the clickable chart features of ChartDirector.

In this section

Introduction to Clickable Charts
Describes how image maps are used to make charts clickable.

Simple Clickable Charts
Sample code demonstrating drill-down capabilities with a series of clickable charts.

Javascript Clickable Charts
Sample code demonstrating using clickable charts with onMouseOut and onMouseOver events to invoke client side Javascript.

Custom Clickable Objects
Sample code demonstrating how to made custom objects clickable.

Database Clickable Charts
A clickable chart example with data coming from a database.

Using Multiple Click Handlers
Describes how to support multiple click handlers in one chart.

Making Other Objects Clickable
Describes how to make various other chart objects clickable.


Introduction to Clickable Charts

Introduction to Clickable Charts

ChartDirector creates charts as images in PNG, GIF, JPEG, BMP or WBMP format. These images are incorporated into HTML web pages by using <IMG> tags. In HTML, an image can be made "clickable" by using an "image map" to define the "hot spots" on the image. An "image map" is defined using <MAP> and <AREA> tags.

The "hot spots" defined can response to mouse events like ordinary HTML links or buttons. These events include mouse clicks, and other mouse events such as "onMouseOver" or "onMouseOut". The "hot spots" can also be used to show tool tips or to activate client-side Javascript.

ChartDirector can automatically generate image maps for the charts it produces, thereby making the charts clickable. ChartDirector can generate image maps for the data contents of the chart (that is, bars for bar charts, sectors for pie charts, areas for area charts, etc.), for the legend keys, title boxes, or custom text boxes.

ChartDirector image maps are "open-ended". That means developers can add custom image map entries (<AREA> tags). For example, one can create custom clickable buttons or custom clickable shapes or logos in the chart by drawing them and then defining image maps for them.

Clickable charts are most often used to produce charts that have "drill down" or "zoom in" capabilities. For example, a pie chart could be created such that when a user clicks on the sectors, the browser will load another web page containing a more detail chart regarding that sector. Similarly, a day-of-week bar chart could be created such that when a user clicks on a bar, the browser will load an hour-of-day chart for the day that the user has clicked.


Clickable Charts Operation Overview

Clickable Charts Operation Overview

For a browser to display an image with an image map, the following sequence of events must have occurred:

  1. The browser sends a HTTP request to the server.

  2. The server returns a HTML web page that contains an <IMG> tag for the image, and the <MAP> and <AREA> tags for the image map.

  3. The browser receives the HTML web page. It then sends another HTTP request to the server using the URL in the <IMG> tag for the actual image.

  4. The server returns the actual image to the browser.


Simple Clickable Charts

Simple Clickable Charts

In this example, we will create a bar chart that displays the annual revenue of a company for the last 10 years. When a bar is clicked, the browser will load a line chart showing the monthly revenue for the selected year. When the line chart is clicked, the browser will load a pie chart showing the breakdown of the revenue for the selected month. When the pie chart is clicked, it will show the sector details in a web page.

The capability is often called "drill-down", because the user can "zoom-in" to get more details by clicking on the chart.

Clickable Bar Chart

[File: cfdemo/clickbar.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the bar chart
data = Array(450, 560, 630, 800, 1100, 1350, 1600, 1950, 2300, 2700);

// The labels for the bar chart
labels = Array("1996", "1997", "1998", "1999", "2000", "2001", "2002", "2003",
    "2004", "2005");

// Create a XYChart object of size 600 x 360 pixels
c = cd.XYChart(600, 360);

// Add a title to the chart using 18pts Times Bold Italic font
c.addTitle("Annual Revenue for Star Tech", "Times New Roman Bold Italic", 18);

// Set the plotarea at (60, 40) and of size 500 x 280 pixels. Use a vertical gradient
// color from light blue (eeeeff) to deep blue (0000cc) as background. Set border and
// grid lines to white (ffffff).
c.setPlotArea(60, 40, 500, 280, c.linearGradientColor(60, 40, 60, 280, "0xeeeeff",
    "0x0000cc"), -1, "0xffffff", "0xffffff");

// Add a multi-color bar chart layer using the supplied data. Use soft lighting
// effect with light direction from top.
c.addBarLayer3(data).setBorderColor(cd.Transparent, cd.softLighting(cd.Top));

// Set x axis labels using the given labels
c.xAxis().setLabels(labels);

// Draw the ticks between label positions (instead of at label positions)
c.xAxis().setTickOffset(0.5);

// When auto-scaling, use tick spacing of 40 pixels as a guideline
c.yAxis().setTickDensity(40);

// Add a title to the y axis with 12pts Times Bold Italic font
c.yAxis().setTitle("USD (millions)", "Times New Roman Bold Italic", 12);

// Set axis label style to 8pts Arial Bold
c.xAxis().setLabelStyle("Arial Bold", 8);
c.yAxis().setLabelStyle("Arial Bold", 8);

// Set axis line width to 2 pixels
c.xAxis().setWidth(2);
c.yAxis().setWidth(2);

// Create the image and save it in a temporary location
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Create an image map for the chart
imageMap = c.getHTMLImageMap("clickline.cfm", "", "title='{xLabel}: US$ {value|0}M'")
    ;

</cfscript>
<html>
<cfoutput>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Simple Clickable Bar Chart
</div>
<hr style="border:solid 1px ##000080" />
<div style="font-size:10pt; font-family:verdana; margin-bottom:20">
    <a href="viewsource.cfm?file=#CGI.SCRIPT_NAME#">View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" border="0" usemap="##map1">
<map name="map1">
#imageMap#
</map>
</body>
</cfoutput>
</html>

The above code is quite similar to most of the sample codes in this documentation, so it will not be discussed in detail. The main difference is the code for creating the image map.

The image map for the chart is created using the following code:

imageMap = c.getHTMLImageMap("clickline.cfm", "", "title='{xLabel}: US$ {value|0}M'");

As seen above, only one line of code is needed. BaseChart.getHTMLImageMap will generate the image map for the entire chart. The image map will use "clickline.cfm" as the handler when a bar is clicked.

If you right click on the browser and choose "View Source" to look at the HTML of the web page as received by the browser, you can see that the image map generated above will be something like:

<area shape="rect" coords="67,278,103,320" title='1996: US$ 450M'
    href="clickline.cfm?x=0&xLabel=1996&dataSet=0&dataSetName=&value=450">

<area shape="rect" coords="117,268,153,320" title='1997: US$ 560M'
    href="clickline.cfm?x=1&xLabel=1997&dataSet=1&dataSetName=&value=560">

<area shape="rect" coords="167,261,203,320" title='1998: US$ 630M'
    href="clickline.cfm?x=2&xLabel=1998&dataSet=2&dataSetName=&value=630">

<area shape="rect" coords="217,245,253,320" title='1999: US$ 800M'
    href="clickline.cfm?x=3&xLabel=1999&dataSet=3&dataSetName=&value=800">

...... (one <area> tag for each bar) ......

The image map generated by ChartDirector contains one <AREA> tag per bar. This defines the bars as hot spots. The "href" attributes of the <AREA> tags use "clickline.cfm" as the URL, with query parameters appended to describe the bars. In this way, "clickline.cfm" can distinguish which bar the user has clicked.

The <AREA> tags also include "title" attributes, which act as tool tips when the mouse pointer moves over the bars. In this example, the tool tips are in the format:

"title='{xLabel}: US$ {value|0}M'"

which is specified as the third argument of BaseChart.getHTMLImageMap.

Clickable Line Chart

In the previous Clickable Bar Chart sample code, when a bar is clicked, "clickline.cfm" will be invoked.

The code for "clickline.cfm" is listed below. It determines which year the user has clicked from query parameters. It then draws a line chart based on the selected year.

As "clickline.cfm" is very similar to "clickbar.cfm", it will not be explained further here.

[File: cfdemo/clickline.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// Get the selected year.
selectedYear = URL.xLabel;

//
// In this demo, we just split the annual revenue into 12 months using random ratios.
// In real life, the data can come from a database based on selectedYear.
//

// Get the annual revenue
annualRevenue = Val(URL.value);

// Split into 12 months
Randomize(Int(selectedYear));
data = ArrayNew(1);
for (i = 0; i LT 11; i = i + 1) {
    data[i + 1] = annualRevenue * (Rand() * 0.6 + 0.6) / (12 - i);
    annualRevenue = annualRevenue - data[i + 1];
}
data[12] = annualRevenue;

//
// Now we obtain the data into arrays, we can start to draw the chart using
// ChartDirector
//

// Create a XYChart object of size 600 x 320 pixels
c = cd.XYChart(600, 360);

// Add a title to the chart using 18pts Times Bold Italic font
c.addTitle("Month Revenue for Star Tech for " & selectedYear,
    "Times New Roman Bold Italic", 18);

// Set the plotarea at (60, 40) and of size 500 x 280 pixels. Use a vertical gradient
// color from light blue (eeeeff) to deep blue (0000cc) as background. Set border and
// grid lines to white (ffffff).
c.setPlotArea(60, 40, 500, 280, c.linearGradientColor(60, 40, 60, 280, "0xeeeeff",
    "0x0000cc"), -1, "0xffffff", "0xffffff");

// Add a red line (ff0000) chart layer using the data
dataSet = c.addLineLayer().addDataSet(data, "0xff0000", "Revenue");

// Set the line width to 3 pixels
dataSet.setLineWidth(3);

// Use a 13 point circle symbol to plot the data points
dataSet.setDataSymbol(cd.CircleSymbol, 13);

// Set the labels on the x axis. In this example, the labels must be Jan - Dec.
labels = Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct",
    "Nov", "Dec");
c.xAxis().setLabels(labels);

// When auto-scaling, use tick spacing of 40 pixels as a guideline
c.yAxis().setTickDensity(40);

// Add a title to the x axis to reflect the selected year
c.xAxis().setTitle("Year " & selectedYear, "Times New Roman Bold Italic", 12);

// Add a title to the y axis
c.yAxis().setTitle("USD (millions)", "Times New Roman Bold Italic", 12);

// Set axis label style to 8pts Arial Bold
c.xAxis().setLabelStyle("Arial Bold", 8);
c.yAxis().setLabelStyle("Arial Bold", 8);

// Set axis line width to 2 pixels
c.xAxis().setWidth(2);
c.yAxis().setWidth(2);

// Create the image and save it in a temporary location
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Create an image map for the chart
imageMap = c.getHTMLImageMap("clickpie.cfm?year=" & selectedYear, "",
    "title='{xLabel}: US$ {value|0}M'");

</cfscript>
<html>
<cfoutput>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Simple Clickable Line Chart
</div>
<hr style="border:solid 1px ##000080" />
<div style="font-size:10pt; font-family:verdana; margin-bottom:20">
    <a href="viewsource.cfm?file=#CGI.SCRIPT_NAME#">View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" border="0" usemap="##map1">
<map name="map1">
#imageMap#
</map>
</body>
</cfoutput>
</html>

Clickable Pie Chart

In the previous Clickable Line Chart sample code, when a line is clicked, the "clickpie.cfm" will be invoked.

The code for "clickpie.cfm" is listed below. It determines which year and month the user has clicked from query parameters. It then draws a pie chart based on those parameters.

As "clickpie.cfm" is very similar to "clickbar.cfm" and "clickline.cfm", it will not be explained further here.

[File: cfdemo/clickpie.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// Get the selected year and month
selectedYear = Int(URL.year);
selectedMonth = Int(URL.x) + 1;

//
// In this demo, we just split the monthly revenue into 3 parts using random ratios.
// In real life, the data probably can come from a database based on selectedYear and
// selectedMonth.
//

// Get the monthly revenue
monthlyRevenue = Val(URL.value);

// Split into 3 parts
Randomize(selectedMonth * 2000 + selectedYear);
data = ArrayNew(1);
data[1] = (Rand() * 0.1 + 0.3) * monthlyRevenue;
data[2] = (Rand() * 0.1 + 0.2) * (monthlyRevenue - data[1]);
data[3] = (Rand() * 0.4 + 0.3) * (monthlyRevenue - data[1] - data[2]);
data[4] = monthlyRevenue - data[1] - data[2] - data[3];

// The labels for the pie chart
labels = Array("Services", "Hardware", "Software", "Others");

// Create a PieChart object of size 600 x 240 pixels
c = cd.PieChart(600, 280);

// Set the center of the pie at (300, 140) and the radius to 120 pixels
c.setPieSize(300, 140, 120);

// Add a title to the pie chart using 18 pts Times Bold Italic font
c.addTitle("Revenue Breakdown for " & selectedMonth & "/" & selectedYear,
    "Times New Roman Bold Italic", 18);

// Draw the pie in 3D with 20 pixels 3D depth
c.set3D(20);

// Set label format to display sector label, value and percentage in two lines
c.setLabelFormat("{label}<*br*>${value|2}M ({percent}%)");

// Set label style to 10 pts Arial Bold Italic font. Set background color to the same
// as the sector color, with reduced-glare glass effect and rounded corners.
t = c.setLabelStyle("Arial Bold Italic", 10);
t.setBackground(cd.SameAsMainColor, cd.Transparent, cd.glassEffect(cd.ReducedGlare));
t.setRoundedCorners();

// Use side label layout method
c.setLabelLayout(cd.SideLayout);

// Set the pie data and the pie labels
c.setData(data, labels);

// Create the image and save it in a temporary location
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Create an image map for the chart
imageMap = c.getHTMLImageMap("piestub.cfm", "", "title='{label}:US$ {value|2}M'");

</cfscript>
<html>
<cfoutput>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Simple Clickable Pie Chart
</div>
<hr style="border:solid 1px ##000080" />
<div style="font-size:10pt; font-family:verdana; margin-bottom:20">
    <a href="viewsource.cfm?file=#CGI.SCRIPT_NAME#">View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" border="0" usemap="##map1">
<map name="map1">
#imageMap#
</map>
</body>
</cfoutput>
</html>

Clickable Pie Chart Handler

In the previous Clickable Pie Chart sample code, when a sector is clicked, "piestub.cfm" will be invoked. Its code is listed below. In this example, it simply displays some data about the sector clicked.

[File: cfdemo/piestub.cfm]
<html>
<cfoutput>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Simple Clickable Pie Chart Handler
</div>
<hr style="border:solid 1px ##000080" />
<div style="font-size:10pt; font-family:verdana; margin-bottom:20">
    <a href="viewsource.cfm?file=#CGI.SCRIPT_NAME#">View Source Code</a>
</div>
<div style="font-size:10pt; font-family:verdana;">
<b>You have clicked on the following sector :</b><br />
<ul>
    <li>Sector Number : #URL.sector#</li>
    <li>Sector Name : #URL.label#</li>
    <li>Sector Value : #URL.value#</li>
    <li>Sector Percentage : #URL.percent#%</li>
</ul>
</div>
</body>
</cfoutput>
</html>


Javascript Clickable Charts

Javascript Clickable Charts

This example demonstrates using ChartDirector image maps to invoke client side Javascript functions.

In this example, a clickable area chart will be produced. Apart from responding to mouse clicks, detail information about the data points will be displayed in a dynamic HTML block when the mouse pointer moves over the chart. This is accomplished using "onMouseOver" and "onMouseOut" event handlers with client side Javascript.

The code for this example is listed below.

[File: cfdemo/jsclick.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

//
// For demo purpose, we use hard coded data. In real life, the following data could
// come from a database.
//
revenue = Array(4500, 5600, 6300, 8000, 12000, 14000, 16000, 20000, 24000, 28000);
grossMargin = Array(62, 65, 63, 60, 55, 56, 57, 53, 52, 50);
backLog = Array(563, 683, 788, 941, 1334, 1522, 1644, 1905, 2222, 2544);
labels = Array("1996", "1997", "1998", "1999", "2000", "2001", "2002", "2003",
    "2004", "2005");

// Create a XYChart object of size 600 x 360 pixels
c = cd.XYChart(600, 360);

// Add a title to the chart using 18pts Times Bold Italic font
c.addTitle("Annual Revenue for Star Tech", "Times New Roman Bold Italic", 18);

// Set the plotarea at (60, 40) and of size 480 x 280 pixels. Use a vertical gradient
// color from light green (eeffee) to dark green (008800) as background. Set border
// and grid lines to white (ffffff).
c.setPlotArea(60, 40, 480, 280, c.linearGradientColor(60, 40, 60, 280, "0xeeffee",
    "0x008800"), -1, "0xffffff", "0xffffff");

// Add a multi-color bar chart layer using the revenue data.
layer = c.addBarLayer3(revenue);

// Set cylinder bar shape
layer.setBarShape(cd.CircleShape);

// Add extra field to the bars. These fields are used for showing additional
// information.
layer.addExtraField2(grossMargin);
layer.addExtraField2(backLog);

// Set the labels on the x axis.
c.xAxis().setLabels(labels);

// In this example, we show the same scale using both axes
c.syncYAxis();

// Set the axis line to transparent
c.xAxis().setColors(cd.Transparent);
c.yAxis().setColors(cd.Transparent);
c.yAxis2().setColors(cd.Transparent);

// Set the axis label to using 8pt Arial Bold as font
c.yAxis().setLabelStyle("Arial Bold", 8);
c.yAxis2().setLabelStyle("Arial Bold", 8);
c.xAxis().setLabelStyle("Arial Bold", 8);

// Add title to the y axes
c.yAxis().setTitle("USD (millions)", "Arial Bold", 10);
c.yAxis2().setTitle("USD (millions)", "Arial Bold", 10);

// Create the image and save it in a temporary location
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Client side Javascript to show detail information "onmouseover"
showText = "onmouseover='showInfo(""{xLabel}"", {value}, {field0}, {field1});' ";

// Client side Javascript to hide detail information "onmouseout"
hideText = "onmouseout='showInfo(null);' ";

// "title" attribute to show tool tip
toolTip = "title='{xLabel}: US$ {value|0}M'";

// Create an image map for the chart
imageMap = c.getHTMLImageMap("xystub.cfm", "", showText & hideText & toolTip);

</cfscript>
<html>
<cfoutput>
<body style="margin:5px 0px 0px 5px">
<script type="text/javascript">
//
//Client side script function to show and hide detail information.
//
function showInfo(year, revenue, grossMargin, backLog) {
    var obj;
    if (document.getElementById)
        //IE 5.x or NS 6.x or above
        obj = document.getElementById('detailInfo');
    else
        //IE 4.x
        obj = document.all['detailInfo'];

    if (!year)
    {
        obj.style.visibility = "hidden";
        return;
    }

    var content = "<table border='1' cellpadding='3' style='font-size:10pt; " +
       "font-family:verdana; background-color:##CCCCFF' width='480'>";
    content += "<tr><td><b>Year</b></td><td width='300'>" + year + "</td></tr>";
    content += "<tr><td><b>Revenue</b></td><td>US$ " + revenue + "M</td></tr>";
    content += "<tr><td><b>Gross Margin</b></td><td>" + grossMargin + "%</td></tr>";
    content += "<tr><td><b>Back Log</b></td><td>US$ " + backLog + "M</td></tr>";
    content += "</table>";

    obj.innerHTML = content;
    obj.style.visibility = "visible";
}
</script>
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Javascript Clickable Chart
</div>
<hr style="border:solid 1px ##000080" />
<div style="font-size:10pt; font-family:verdana; margin-bottom:20">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<img src="getchart.cfm?#chart1URL#" border="0" usemap="##map1">
<map name="map1">
#imageMap#
</map>
<div id="detailInfo" style="margin-left:60"></div>
</body>
</cfoutput>
</html>

The above code is quite similar to most of the sample codes in this documentation, so it will not be discussed in detail. The main difference is the code for creating the image map.

The image map for the chart is created using the following code:

// Client side Javascript to show detail information "onmouseover"
showText = "onmouseover='showInfo(""{xLabel}"", {value}, {field0}, {field1});' ";

// Client side Javascript to hide detail information "onmouseout"
hideText = "onmouseout='showInfo(null);' ";

// "title" attribute to show tool tip
toolTip = "title='{xLabel}: US$ {value|0}M'";

// Create an image map for the chart
imageMap = c.getHTMLImageMap("xystub.cfm", "", showText & hideText & toolTip);

Note that in additional to the "title" attribute for the "tool tip", the image map also includes event handlers "onmouseover" and "onmouseout". These event handles call the client side Javascript function "showInfo", which creates and hides the dynamic HTML block for displaying the additional information.

<script>
//
//Client side script function to show and hide detail information.
//
function showInfo(year, revenue, grossMargin, backLog) {
    var obj;
    if (document.getElementById)
        //IE 5.x or NS 6.x or above
        obj = document.getElementById('detailInfo');
    else
        //IE 4.x
        obj = document.all['detailInfo'];

    if (!year)
    {
        obj.style.visibility = "hidden";
        return;
    }

    var content = "<table border='1' cellpadding='3' style='font-size:10pt; " +
       "font-family:verdana; background-color:#CCCCFF' width='480'>";
    content += "<tr><td><b>Year</b></td><td width='300'>" + year + "</td></tr>";
    content += "<tr><td><b>Revenue</b></td><td>US$ " + revenue + "M</td></tr>";
    content += "<tr><td><b>Gross Margin</b></td><td>" + grossMargin + "%</td></tr>";
    content += "<tr><td><b>Back Log</b></td><td>US$ " + backLog + "M</td></tr>";
    content += "</table>";

    obj.innerHTML = content;
    obj.style.visibility = "visible";
}
</script>

Note that in this example, we are displaying extra information, such as the "grossMargin" and "backLog" fields, which does not come from the x or y value of the bars. This is achieved by associated these fields as "extra fields" to the data items with Layer.addExtraField2. These extra fields can then be represented using the template "{fieldN}", where "N" represents the field number. (The first field is 0, the second field is 1, etc.)

In addition to responding to mouse over and mouse out events, the chart is also clickable using "xystub.cfm" as the handler.

For demo purpose, "xystub.cfm" simply displays information on what is clicked. It's source code is as follows.

[File: cfdemo/xystub.cfm]
<html>
<cfoutput>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Simple Clickable XY Chart Handler
</div>
<hr style="border:solid 1px ##000080" />
<div style="font-size:10pt; font-family:verdana; margin-bottom:20">
    <a href="viewsource.cfm?file=#CGI.SCRIPT_NAME#">View Source Code</a>
</div>
<div style="font-size:10pt; font-family:verdana;">
<b>You have clicked on the following chart element :</b><br />
<ul>
    <li>Data Set : #URL.dataSetName#</li>
    <li>X Position : #URL.x#</li>
    <li>X Label : #URL.xLabel#</li>
    <li>Data Value : #URL.value#</li>
</ul>
</div>
</body>
</cfoutput>
</html>


Custom Clickable Objects

Custom Clickable Objects

In this example, a clickable line chart will be created with legend keys, a title box, a vertical mark with label, and a custom text box. All these objects will be clickable in addition to the lines and the data points.

This example also demonstrate how to use client side Javascript as the click handler.

The code for this example is listed below.

[File: cfdemo/customclick.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// The data for the line chart
data0 = Array(50, 55, 47, 36, 42, 49, 63, 62, 73, 59, 56, 50, 64, 60, 67, 67, 58, 59,
    73, 77, 84, 82, 80, 84);
data1 = Array(36, 28, 25, 33, 38, 20, 22, 30, 25, 33, 30, 24, 28, 36, 30, 45, 46, 42,
    48, 45, 43, 52, 64, 70);

// The labels for the line chart
labels = Array("Jan-04", "Feb-04", "Mar-04", "Apr-04", "May-04", "Jun-04", "Jul-04",
    "Aug-04", "Sep-04", "Oct-04", "Nov-04", "Dec-04", "Jan-05", "Feb-05", "Mar-05",
    "Apr-05", "May-05", "Jun-05", "Jul-05", "Aug-05", "Sep-05", "Oct-05", "Nov-05",
    "Dec-05");

// Create an XYChart object of size 600 x 360 pixels, with a light blue (EEEEFF)
// background, black border, 1 pxiel 3D border effect and rounded corners
c = cd.XYChart(600, 360, "0xeeeeff", "0x000000", 1);
c.setRoundedFrame();

// Set plotarea at (55, 60) with size of 520 x 240 pixels. Use white (ffffff) as
// background and grey (cccccc) for grid lines
c.setPlotArea(55, 60, 520, 240, "0xffffff", -1, -1, "0xcccccc", "0xcccccc");

// Add a legend box at (55, 58) (top of plot area) using 9 pts Arial Bold font with
// horizontal layout Set border and background colors of the legend box to
// Transparent
legendBox = c.addLegend(55, 58, False, "Arial Bold", 9);
legendBox.setBackground(cd.Transparent);

// Reserve 10% margin at the top of the plot area during auto-scaling to leave space
// for the legends.
c.yAxis().setAutoScale(0.1);

// Add a title to the chart using 15 pts Times Bold Italic font. The text is white
// (ffffff) on a blue (0000cc) background, with glass effect.
title = c.addTitle("Monthly Revenue for Year 2000/2001",
    "Times New Roman Bold Italic", 15, "0xffffff");
title.setBackground("0x0000cc", "0x000000", cd.glassEffect(cd.ReducedGlare));

// Add a title to the y axis
c.yAxis().setTitle("Month Revenue (USD millions)");

// Set the labels on the x axis. Draw the labels vertical (angle = 90)
c.xAxis().setLabels(labels).setFontAngle(90);

// Add a vertical mark at x = 17 using a semi-transparent purple (809933ff) color and
// Arial Bold font. Attached the mark (and therefore its label) to the top x axis.
mark = c.xAxis2().addMark(17, "0x809933ff", "Merge with Star Tech", "Arial Bold");

// Set the mark line width to 2 pixels
mark.setLineWidth(2);

// Set the mark label font color to purple (0x9933ff)
mark.setFontColor("0x9933ff");

// Add a copyright message at (575, 295) (bottom right of plot area) using Arial Bold
// font
copyRight = c.addText(575, 295, "(c) Copyright Space Travel Ltd", "Arial Bold");
copyRight.setAlignment(cd.BottomRight);

// Add a line layer to the chart
layer = c.addLineLayer();

// Set the default line width to 3 pixels
layer.setLineWidth(3);

// Add the data sets to the line layer
layer.addDataSet(data0, -1, "Enterprise");
layer.addDataSet(data1, -1, "Consumer");

// Create the image
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Create an image map for the chart
chartImageMap = c.getHTMLImageMap("xystub.cfm", "",
    "title='{dataSetName} @ {xLabel} = USD {value|0} millions'");

// Create an image map for the legend box
legendImageMap = legendBox.getHTMLImageMap(
    "javascript:popMsg('the legend key [{dataSetName}]');", " ",
    "title='This legend key is clickable!'");

// Obtain the image map coordinates for the title, mark, and copyright message. These
// will be used to define the image map inline. (See HTML code below.)
titleCoor = title.getImageCoor();
markCoor = mark.getImageCoor();
copyRightCoor = copyRight.getImageCoor();

</cfscript>
<html>
<cfoutput>
<body style="margin:5px 0px 0px 5px">
<script type="text/javascript">
function popMsg(msg) {
    alert("You have clicked on " + msg + ".");
}
</script>
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Custom Clickable Objects
</div>
<hr style="border:solid 1px ##000080" />
<div style="font-size:10pt; font-family:verdana; margin-bottom:20px">
    <a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>View Source Code</a>
</div>
<div style="font-size:10pt; font-family:verdana; width:600px; margin-bottom:20px">
    In the following chart, the lines, legend keys, title, copyright, and the "Merge
    with Star Tech" text are all clickable!
</div>
<img src="getchart.cfm?#chart1URL#" border="0" usemap="##map1">
<map name="map1">
#chartImageMap#
#legendImageMap#
<area #titleCoor#  href='javascript:popMsg("the chart title");'
    title='The title is clickable!' />
<area #markCoor# href='javascript:popMsg("the Merge with Star Tech mark");'
    title='The "Merge with Star Tech" text is clickable!' />
<area #copyRightCoor# href='javascript:popMsg("the copyright message");'
    title='The copyright text is clickable!' />
</map>
</body>
</cfoutput>
</html>

The above code is quite similar to most of the sample codes in this documentation, so it will not be discussed in detail. The main difference is the code for creating the image map.

The image map in this example consists of multiple parts. The part for the line chart is produced using BaseChart.getHTMLImageMap with "xystub.cfm" as the handler:

chartImageMap = c.getHTMLImageMap("xystub.cfm", "",
    "title='{dataSetName} @ {xLabel} = USD {value|0} millions'");

For demo purpose, "xystub.cfm" simply displays information on what is clicked. It's source code is as follows.

[File: cfdemo/xystub.cfm]
<html>
<cfoutput>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Simple Clickable XY Chart Handler
</div>
<hr style="border:solid 1px ##000080" />
<div style="font-size:10pt; font-family:verdana; margin-bottom:20">
    <a href="viewsource.cfm?file=#CGI.SCRIPT_NAME#">View Source Code</a>
</div>
<div style="font-size:10pt; font-family:verdana;">
<b>You have clicked on the following chart element :</b><br />
<ul>
    <li>Data Set : #URL.dataSetName#</li>
    <li>X Position : #URL.x#</li>
    <li>X Label : #URL.xLabel#</li>
    <li>Data Value : #URL.value#</li>
</ul>
</div>
</body>
</cfoutput>
</html>

The image map for the legend keys is produced using LegendBox.getHTMLImageMap. In this example, a client side Javascript will be executed when the user clicks on the legend key.

legendImageMap = legendBox.getHTMLImageMap(
    "javascript:popMsg('the legend key [{dataSetName}]');", " ",
    "title='This legend key is clickable!'");

As shown above, the "javascript:popMsg(...);" as used in the url parameter of "getHTMLImageMap". The browser will interpret it as a client side Javascript statement to be executed when the <AREA> tag is clicked.

Note that the second argument to LegendBox.getHTMLImageMap is set to a space character. This argument specifies the HTTP query parameters to be append to the url. In this example, since the url is actually a client side Javascript, no query parameter is necessary. So a space character is used. (We cannot use an empty string, as it means the default query parameters will be used.)

The client side Javascript executed in this example just pops up a message.

<SCRIPT>
function popMsg(msg) {
    alert("You have clicked on " + msg + ".");
}
</SCRIPT>

Most text messages in ChartDirector are represented as TextBox objects, and their image map coordinates can be retrieved using Box.getImageCoor. This allows <AREA> tags for TextBox objects be created easily.

(For TextBox, there is no "getHTMLImageMap" method. It is because each TextBox object only has one hot spot. It is more convenient to enter the handler URL and tool tip text directly into the <AREA> tag, rather than generating them using getHTMLImageMap.)

In this example, the image map coordinates of the chart title, vertical mark label, and the copyright message are obtained using Box.getImageCoor:

titleCoor = title.getImageCoor();
markCoor = mark.getImageCoor();
copyRightCoor = copyRight.getImageCoor();

The image map coordinates are then used to make <AREA> tags as follows:

<area #titleCoor#  href='javascript:popMsg("the chart title");'
    title='The title is clickable!' />
<area #markCoor# href='javascript:popMsg("the Merge with Star Tech mark");'
    title='The "Merge with Star Tech" text is clickable!' />
<area #copyRightCoor# href='javascript:popMsg("the copyright message");'
    title='The copyright text is clickable!' />


Database Clickable Charts

Database Clickable Charts

In this section, we will present an example that employs both database and image maps.

This example displays a bar chart that shows the revenue for the last 10 years. When the user clicks on a bar, it will "drill down" to another bar chart showing the monthly revenue for the year represented by the bar clicked. All data come from a database.

The code that creates the clickable bar chart for the last 10 years are as follows.

[File: cfdemo/dbdemo3.cfm]
<!--- Read the revenue from 1990 to 2001 and into arrays --->
<cfquery name="selectedData" datasource="cdsample">
    Select
        Sum(Software + Hardware + Services) As annualRevenue,
        Year(TimeStamp) As Year
    From revenue
    Where Year(TimeStamp) >= 1990 And Year(TimeStamp) <= 2001
    Group By Year(TimeStamp) Order By Year(TimeStamp)
</cfquery>
<cfset revenue = selectedData["annualRevenue"].toArray()>
<cfset timestamp = selectedData["Year"].toArray()>

<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// Create a XYChart object of size 600 x 360 pixels
c = cd.XYChart(600, 360);

// Set the plotarea at (60, 40) and of size 480 x 280 pixels. Use a vertical gradient
// color from light blue (eeeeff) to deep blue (0000cc) as background. Set border and
// grid lines to white (ffffff).
c.setPlotArea(60, 40, 480, 280, c.linearGradientColor(60, 40, 60, 280, "0xeeeeff",
    "0x0000cc"), -1, "0xffffff", "0xffffff");

// Add a title to the chart using 18pts Times Bold Italic font
c.addTitle("Annual Revenue for Star Tech", "Times New Roman Bold Italic", 18);

// Add a multi-color bar chart layer using the supplied data
layer = c.addBarLayer3(revenue);

// Use glass lighting effect with light direction from the left
layer.setBorderColor(cd.Transparent, cd.glassEffect(cd.NormalGlare, cd.Left));

// Set the x axis labels
c.xAxis().setLabels(timestamp);

// Set y-axis tick density to 30 pixels. ChartDirector auto-scaling will use this as
// the guideline when putting ticks on the y-axis.
c.yAxis().setTickDensity(30);

// Synchronize the left and right y-axes
c.syncYAxis();

// Set the y axes titles with 10pts Arial Bold font
c.yAxis().setTitle("USD (Millions)", "Arial Bold", 10);
c.yAxis2().setTitle("USD (Millions)", "Arial Bold", 10);

// Set all axes to transparent
c.xAxis().setColors(cd.Transparent);
c.yAxis().setColors(cd.Transparent);
c.yAxis2().setColors(cd.Transparent);

// Set the label styles of all axes to 8pt Arial Bold font
c.xAxis().setLabelStyle("Arial Bold", 8);
c.yAxis().setLabelStyle("Arial Bold", 8);
c.yAxis2().setLabelStyle("Arial Bold", 8);

// Create the image
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Create an image map for the chart
imageMap = c.getHTMLImageMap("dbdemo3a.cfm", "", "title='{xLabel}: US$ {value|0}M'");

</cfscript>
<html>
<cfoutput>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Database Clickable Charts
</div>
<hr style="border:solid 1px ##000080" />
<div style="font-size:10pt; font-family:verdana; width:600px; margin-bottom:20px">
    The example demonstrates creating a clickable chart using data from a database.
    Click on a bar below to "drill down" onto a particular year.
<br /><br />
<a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>
    View source code
</a>
</div>

<img src="getchart.cfm?#chart1URL#" border="0" usemap="##map1">
<map name="map1">
#imageMap#
</map>

</body>
</cfoutput>
</html>

The above code first performs a database query and read the data into arrays. It then uses the data to create a bar chart. The image map for the chart is created using BaseChart.getHTMLImageMap with "dbdemo3a.cfm" as the handler.

When the user clicks on the bar chart, "dbdemo3a.cfm" will be invoked with a number of HTTP query parameters to indicate which bar the user has clicked. In particular, the xLabel parameter will contain the x-axis label for the bar clicked. With this parameter, "dbdemo3a.cfm" can determine which year the user has clicked. It can then query the database for the data on that year, and produces the bar chart for that year.

In this example, "dbdemo3a.cfm" will produce another clickable chart using "xystub.cfm" as the handler.

[File: cfdemo/dbdemo3a.cfm]
<!--- The selected year should be in a query parameter called "xLabel" --->
<cfset selectedYear = IIf(IsDefined("URL.xLabel"), "URL.xLabel", "2001")>

<!--- Query data from the selected year and read them into arrays --->
<cfquery name="selectedData" datasource="cdsample">
    SELECT * FROM Revenue WHERE Year(timeStamp) = #selectedYear# Order By timeStamp
</cfquery>
<cfset software = selectedData["Software"].toArray()>
<cfset hardware = selectedData["Hardware"].toArray()>
<cfset services = selectedData["Services"].toArray()>

<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

// Create a XYChart object of size 600 x 360 pixels
c = cd.XYChart(600, 360);

// Set the plotarea at (60, 50) and of size 480 x 270 pixels. Use a vertical gradient
// color from light blue (eeeeff) to deep blue (0000cc) as background. Set border and
// grid lines to white (ffffff).
c.setPlotArea(60, 50, 480, 270, c.linearGradientColor(60, 50, 60, 270, "0xeeeeff",
    "0x0000cc"), -1, "0xffffff", "0xffffff");

// Add a title to the chart using 15pts Times Bold Italic font
c.addTitle("Global Revenue for Year " & selectedYear, "Times New Roman Bold Italic",
    18);

// Add a legend box at (60, 25) (top of the plotarea) with 9pts Arial Bold font
c.addLegend(60, 25, False, "Arial Bold", 9).setBackground(cd.Transparent);

// Add a line chart layer using the supplied data
layer = c.addLineLayer2();
layer.addDataSet(software, "0xffaa00", "Software").setDataSymbol(cd.CircleShape, 9);
layer.addDataSet(hardware, "0x00ff00", "Hardware").setDataSymbol(cd.DiamondShape, 11)
    ;
layer.addDataSet(services, "0xff0000", "Services").setDataSymbol(cd.Cross2Shape(), 11
    );

// Set the line width to 3 pixels
layer.setLineWidth(3);

// Set the x axis labels. In this example, the labels must be Jan - Dec.
labels = Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct",
    "Nov", "Dec");
c.xAxis().setLabels(labels);

// Set y-axis tick density to 30 pixels. ChartDirector auto-scaling will use this as
// the guideline when putting ticks on the y-axis.
c.yAxis().setTickDensity(30);

// Synchronize the left and right y-axes
c.syncYAxis();

// Set the y axes titles with 10pts Arial Bold font
c.yAxis().setTitle("USD (Millions)", "Arial Bold", 10);
c.yAxis2().setTitle("USD (Millions)", "Arial Bold", 10);

// Set all axes to transparent
c.xAxis().setColors(cd.Transparent);
c.yAxis().setColors(cd.Transparent);
c.yAxis2().setColors(cd.Transparent);

// Set the label styles of all axes to 8pt Arial Bold font
c.xAxis().setLabelStyle("Arial Bold", 8);
c.yAxis().setLabelStyle("Arial Bold", 8);
c.yAxis2().setLabelStyle("Arial Bold", 8);

// Create the image and save it in a temporary location
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Create an image map for the chart
imageMap = c.getHTMLImageMap("xystub.cfm", "",
    "title='{dataSetName} @ {xLabel} = USD {value|0}M'");

</cfscript>

<html>
<cfoutput>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Database Clickable Charts
</div>
<hr style="border:solid 1px ##000080" />
<div style="font-size:10pt; font-family:verdana; width:600px; margin-bottom:20px">
    You have click the bar for the year #selectedYear#.
    Below is the "drill-down" chart showing the monthly details.
<br /><br />
<a href='viewsource.cfm?file=#CGI.SCRIPT_NAME#'>
    View source code
</a>
</div>

<img src="getchart.cfm?#chart1URL#" border="0" usemap="##map1">
<map name="map1">
#imageMap#
</map>

</body>
</cfoutput>
</html>

For demo purpose, "xystub.cfm" simply displays information on what is clicked. It's source code is as follows.

[File: cfdemo/xystub.cfm]
<html>
<cfoutput>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Simple Clickable XY Chart Handler
</div>
<hr style="border:solid 1px ##000080" />
<div style="font-size:10pt; font-family:verdana; margin-bottom:20">
    <a href="viewsource.cfm?file=#CGI.SCRIPT_NAME#">View Source Code</a>
</div>
<div style="font-size:10pt; font-family:verdana;">
<b>You have clicked on the following chart element :</b><br />
<ul>
    <li>Data Set : #URL.dataSetName#</li>
    <li>X Position : #URL.x#</li>
    <li>X Label : #URL.xLabel#</li>
    <li>Data Value : #URL.value#</li>
</ul>
</div>
</body>
</cfoutput>
</html>


Using Multiple Click Handlers

Using Multiple Click Handlers

When creating image maps with BaseChart.getHTMLImageMap, all data points will use the same image map handler.

For example, in a pie chart, if the image map is generated using BaseChart.getHTMLImageMap with "piestub.cfm" as the handler, no matter which sector is clicked, "piestub.cfm" will be invoked. The different sectors are distinguished by different HTTP query parameters.

If for some reasons, it is desirable that different sectors use different handlers, the followings are some of the methods:

  • Produce the image map using BaseChart.getHTMLImageMap, with the same handler for all sectors. In the handler, redirect the HTTP request to the "real handler" based on the sector clicked. This is the simplest and recommended method.

  • Use a client side Javascript function as the handler, where "{sector}" is used as the argument to indicate which sector is clicked. For example, "javascript:callMe({sector});" can be used as the handler. In the "callMe" function, the client side Javascript can instruct the browser to load the "real handler".

  • Do not use BaseChart.getHTMLImageMap. Instead, use Sector.getImageCoor and Sector.getLabelCoor to obtain the image map coordinates of individual sectors and sector labels. With these coordinates, one can create custom <AREA> tags for the individual sectors and can put any attributes in them. One can therefore use different "href" attributes for different sectors.

Although we use pie chart as an example above, the principles apply to other chart types as well.


Making Other Objects Clickable

Making Other Objects Clickable

Note that ChartDirector image map support is "open-ended". You can always insert additional <AREA> tags inside the image map.

In general, if an object contains multiple hot spots (e.g. the bars in a bar chart), the "getHTMLImageMap" method of that object may be used to generate <AREA> tags for all hot spots at once. These <AREA> tags will use the same handler and the hot spots will be distinguished by query parameters.

On the other hand, if an object only has one hot spot (e.g. a single sector or a text box), it is more convenient to enter the handler and tool tip attributes directly into the <AREA> tag. In this case, the "getImageCoor" method of that object may be used for getting the image map coordinates of the hot spot.

In case an object has no "getHTMLImageMap" or "getImageCoor" method, it may be necessary to compute or estimate its coordinates to create the <AREA> tag.

For example, suppose you want the vertical y-axis of an XYChart to be clickable. The end points of the y-axis are known. They are just the corners of the plot area. The "width" of the y-axis may be unknown, but for clickable purposes, it may be acceptable to assume a reasonable width. In this way, the coordinates of the bounding rectangle of the y-axis can be determined.

If the (x, y) coordinates of an object is only known by their data values, you can convert them to pixel coordinates using Layer.getXCoor and Layer.getYCoor (or PolarChart.getXCoor and PolarChart.getYCoor for polar charts).


Zoomable and Scrollable Charts

Zoomable and Scrollable Charts

This section describes the ChartDirector Zooming and Scroll Framework for creating charts system extremely wide range of zoom ratios and rich user controls.

In this section

Zooming and Scrolling Framework
Description of the ChartDirector Zooming and Scroll Framework.

Zooming and Scrolling Demonstration
This sample program demonstrates a zoomable and scrollable chart for time based data series, with drag to scroll, drag to zoom, click to zoom, as well as allowing the start and end dates to selected directly using drop down list boxes. The chart supports both partial updates (AJAX updates) and full page updates.

Zooming and Scrolling Demonstration (2)
This sample program demonstrates a general zoomable and scrollable chart, with drag to scroll, drag to zoom and click to zoom. The view port can also be moved by dragging on the rectangle on the navigation pad. The chart supports both partial updates (AJAX updates) and full page updates.


Zooming and Scrolling Framework

Zooming and Scrolling Framework

Introduction

When talking about "zooming", it is common to think about zooming like a digital photograph, in which everything is magnified, but is otherwise exactly the same. The zoom ratio is usually a few times and the same data (the photograph) are used at all zoom levels.

There is a much more powerful type of zooming, like zooming in a map. For example, one may start with a world map, and zoom all the way down to seeing the streets and buildings within a city. The zoom ratio can be in the order of 500000 - 1000000 times. Different presentation method may be used at different scales. For example, the world map may show only terrain information, while at highest zoom ratio the map may show the names of individual streets.

The ChartDirector Zooming and Scrolling Framework is designed based on the second model of zooming. The key features are:

  • Virtually unlimited zoom ratio.

    For example, one can zoom from 10 years down to 1 second (a zoom ratio of 315 million times).

  • Allows different chart types and data grouping methods at different scales.

    For example, to plot temperature for 1 day, one may be interested hourly temperature. On the other hand, to plot the temperature for 1 year, one may be interested in the daily high-low range (eg. using two lines for high and low daily temperatures and fill the region in between) rather than the hourly temperatures.

  • Click and drag to control zooming and scrolling.

    The browser side Javascript chart viewer control (JsChartViewer) implements zoom/scroll controls via mouse actions. One may use the mouse to drag to scroll, drag to select a region to zoom into, click to zoom in, and click to zoom out depending on the mouse usage mode (set using JsChartViewer.setMouseUsage).

  • Allows external controls for zooming and scrolling.

    In many applications, it may be desirable to have several controls to control zooming and scrolling. For example, for a time based chart, in addition to use "drag to scroll" and "drag to zoom", one may want to allow users to select the start and end dates on the axis using drop down list boxes or other controls.

The View Port

The ChartDirector Zooming and Scrolling framework is based on the concept of a view port.

A view port can be imagined as a rectangular window of an underlying rectangular surface. For example, a chart that has 10 years of data can be imagined as a very long chart. If one only displays one of the year, we can say the view port covers only 10% of the underlying chart.

With the view port concept, scrolling can be handled as moving the view port, while zooming in and out can be handled as changing the view port size.

WebChartViewer and JsChartViewer

The ChartDirector Zooming and Scrolling Framework for web applications is based on two controls:

  • JsChartViewer : This is a browser side Javascript control that manages the view port. It allows the view port coordinates to be modified by mouse actions, such as drag to scroll, drag to select a region to zoom into, click to zoom in, and click to zoom out.

  • WebChartViewer : This is the server side counterpart of JsChartViewer. It acts as a "proxy" to JsChartViewer. Properties of the browser side JsChartViewer will be accessible as properties of the WebChartViewer, and vice versa.

In a typical web page with a zoomable and scrollable chart, the operation is like:

  • The browser sends a request to the server for the web page.

  • On the server side, the chart is created and set into the WebChartViewer. The WebChartViewer may also be configured with the initial state of the JsChartViewer. The WebChartViewer may then generated the HTML tags for the chart image and the JsChartViewer state. These tags may be inserted into the web page to be sent to the browser.

  • On the browser side, the user can then see the chart, and can use the mouse actions to zoom or scroll the chart.

  • When a zooming or scrolling action occurs, the JsChartViewer will update its view port coordinates and send the updated state to the server.

  • On the server side, the WebChartViewer can be used to retrieve the updated view port coordinates. An updated chart can then be created and set into the WebChartViewer, which will then be sent back to the browser side JsChartViewer for display.

The last three steps may then repeat many times.

Partial Chart Update and Full Page Update

ChartDirector supports using AJAX (Asynchronous Javascript And XML) methods for the communication between the JsChartViewer and WebChartViewer. So the chart can be updated without refreshing the web page. In ChartDirector terminology, this is called a partial chart update.

The vast majority of the browsers nowadays support AJAX. However, it is still possible a user may be using a non-AJAX supporting browser. To handle these cases, ChartDirector also supports using traditional full page update method. In this method, the JsChartViewer updates the WebChartViewer by using HTTP POST or GET, and the WebChartViewer updates the browser display by updating the entire page.

JsChartViewer.canSupportPartialUpdate can be used to dynamically detect if a browser supports AJAX or not, so the JsChartViewer can determine which method to use to communicate with the WebChartViewer.

Integration with External Controls

It is not uncommon for a web page to be designed with multiple ways to control the axis range of the chart. For example, in a time based chart, in addition to using "drag to scroll" and "drag to select region" to select the time range of the chart, there may be text fields or drop down list boxes to allow the user to select the start time and end time directly.

Although the text fields or drop down list boxes are not part of the JsChartViewer, it would be ideal if these external controls can also use partial chart updates (AJAX requests), so the chart can be updated without the web page refreshing.

Also, if a user drags to scroll the chart using JsChartViewer, in addition to updating the chart, the text fields or drop down list boxes may also need to be updated to show the new time range.

To support external controls, JsChartViewer and WebChartViewer support custom attributes. Like other properties of JsChartViewer and WebChartViewer, custom attributes set on the browser side JsChartViewer will be accessible from the server side WebChartViewer, and vice versa.

For example, in the above case with external text fields for entering the start and end dates, the operation may be like:

  • Suppose the user enters the start and end dates directly using text fields and then press the "OK button". In the onClick event handler of the button, JsChartViewer.setCustomAttr may be used to copy the text fields into the JsChartViewer as custom attributes. Then JsChartViewer.partialUpdate may be used to sent a partial chart update request to the server.

  • On the server side, WebChartViewer.getCustomAttr may be used to get back the text field data. The server side script may then validate the user input, create an updated chart, and set it into the WebChartViewer. If the text fields are updated (eg., after user input validation, the text fields may have changed), they may be modified using WebChartViewer.setCustomAttr. The updated chart and text field data will then be sent back to the browser.

  • On the browser side, upon receiving the response, JsChartViewer will display the updated chart. To update the text fields, a JsChartViewer.PostUpdate event handler may be used to copy the custom attributes (get using JsChartViewer.getCustomAttr) to the text fields.

Persistent State Storage

Apart from supporting external controls, another usage of custom attributes is to provide a persistent state storage across multiple chart update requests.

In a zoomable and scrollable, whenever the view port is updated, there will be a request sent to the server for an updated chart. It is often useful to have a storage that is persistent across multiple chart update requests. In other words, data set in a chart update request can be retrieved in subsequent chart update requests.

Custom attributes can serve this role because attributes set on the server side WebChartViewer will be transported to the browser side JsChartViewer. During chart update requests, these attributes will be transported back to the server side. So these custom attributes are preserved across chart update requests from both the server side and browser side point of view.

Typical Server Side Code Structure

The server side code may need to handle the following types of requests from the browser:

  • Initial page request: This occurs when the page is accessed for the first time by a browser. The server side script should set the initial state of the JsChartViewer (through the WebChartViewer), and generate the entire web page including the chart.

  • Partial chart update (AJAX chart update): This occurs when the JsChartViewer sends a partial chart update requests to the server. The WebChartViewer may be used to process the request and to send an updated chart and as response.

    WebChartViewer.isPartialUpdateRequest may be used to detect if the current HTTP request is a partial update request.

  • Full page update: This occurs when the browser sends a traditional HTTP POST or GET request to the server. The request may be due to zoom or scroll mouse actions, or it can be submitted by external controls.

    WebChartViewer.isFullUpdateRequest may be used to detect if the current HTTP request is a full update request.

Note that one may always design a web page that only uses partial chart update or full page update, in which case only the corresponding request type needs to be implemented.

If a page only supports partial chart update, then very old browsers that do not support AJAX may be unable to zoom or scroll the chart, but they can still see the initial chart.

If a page only supports full page update, then it will work with all browsers, but each zooming or scrolling requests will result in updating the entire web page.

The typical code structure will be like:

  • For the initial page request, initialize the overall range and visible range of the chart. For example, for a time based chart, one may set the overall range to be 5 years, and the initial visible range to be 1 year.

    If the initial chart is designed to display all available data, one may use the auto-scaled axis range (obtain using Axis.getMaxValue and Axis.getMinValue after creating the chart) as the overall range.

    The overall range and visible range may then be used to compute the initial view port position and size.

    The overall range is needed in subsequent chart update requests. It may be stored as custom attributes using WebChartViewer.setCustomAttr, so it can be retrieved in subsequent chart update requests.

  • In subsequent chart update requests, use the view port settings and the overall range to determine the visible range.

  • Retrieve the necessary data based on the visible range.

    If the number of data points are small, you may also retrieve all data without regarding the visible range. ChartDirector will automatically clip the data to the view port. On the other hand, if there are many data points (which is typical of charts that need to zoom and scroll), it is recommended you retrieve only the necessary data to improve charting performance.

    For charts that need to zoom or scroll, it is not uncommon to have data series with thousands or even millions of points. However, considering a typical plot area is less than a thousand pixels in width, for most chart types, it is not necessary to plot that many points.

    Plotting too many data points will reduce the effective resolution of the chart rather than increasing it. It is like drawing a world map on the screen by drawing each street in each city in detail. Instead of getting a very detail map, one probably get a not too useful map.

    In general, for most chart types, the best chart is obtained when the number of data points is about the same as the number of pixels in width. As a rule of thumb, one may try to aggregate the data points together so that the number of points is 50% to 100% of the number of pixels in width.

    Aggregation means to group multiple data points together into one point. Common aggregation methods include using averaging, resampling, peak value, summation, etc. The exact method to use depends on your chart type and the nature of the data. For example, in a line chart, one may use averaging as the aggregation method, while for an area chart, one may use the peak value as the aggregation method.

    Sometimes, it may be meaningful to aggregate one data series into multiple data series. For example, suppose we have a data series representing the hourly temperature, and we need to plot it for a year (365 x 24 = 8760 points). Instead of plotting the data directly, we may aggregate the data into 3 daily series, representing the maximum, minimum and average temperature of a day. We may even use a color to fill the region between the maximum and minimum lines. The resulting chart will be much for elegant and useful than using the raw data directly.

    If the data come from a SQL database, one can often aggregate the data by using the GROUP BY clause in SQL statements. This may make the database query much faster, as the query result set will have much less records.

    ChartDirector includes a utility method ArrayMath.aggregate that can be used to conveniently aggregate data. This is useful for non-SQL data sources that do not support aggregate statements.

  • Draw the chart with the given data.

    There are plenty of sample code elsewhere in this documentation on how to draw various charts with ChartDirector. A special point to note is that the charting code may need to configure the axis scale as according to the view port, except for the initial chart which may use auto-scaling.

    The created chart may be stored in a session variable using BaseChart.makeSession, or in a temporary file using BaseChart.makeTmpFile. The URL to retrieve the chart should be set to the WebChartViewer using WebChartViewer.setImageUrl. If an image map is available for the chart, it should be set to the WebChartViewer using WebChartViewer.setImageMap.

  • Return the output to the the browser.

    For partial chart update request, WebChartViewer.partialUpdateChart should be use to return the response to the browser.

    For the initial page request or full page updates, WebChartViewer.renderHTML should be used to create the HTML tags that represent the chart. These tags may then be inserted in the HTML web page to be sent to the browser.

Typical Browser Side Code Structure

On the browser side, the typical code structure will be like:

  • Include the JsChartViewer script file "cdjcv.js" in the HTML. This is typically achieved by using the following code in the <HEAD> block of the HTML web page.

    <SCRIPT SRC='cdjcv.js'></SCRIPT>

    Note that the above assumes the "cdjcv.js" is in the same directory as the web page. Please modify the path if the "cdjcv.js" is in other directory.

  • Include code to initialize the JsChartViewer after the web page has loaded. This is typically done by call the initialization function in the onload event handler of the <BODY> tag, like:

    <BODY onload="initJsChartViewer()">

    Typically things that need to be done in the initialization function includes:

    • Add an event handler for the JsChartViewer.ViewPortChanged event to either perform a partial chart update, or to perform a full page update using traditional FORM submit. This may depend on whether the browser can support AJAX or not (can be detected using JsChartViewer.canSupportPartialUpdate).

    • Connect the JsChartViewer to HTML controls that may be used to configure its properties on the browser side, such as HTML buttons for configuring its mouse usage mode (see JsChartViewer.setMouseUsage).

    • Set up JsChartViewer.PreUpdate and JsChartViewer.PostUpdate event handlers if necessary to copy HTML control states to and from custom attributes. These allow external controls to send their states to the server and receive updates from the server during partial chart updates (AJAX requests).

    A template of the typical initialization function is as shown below.

    // Initialize browser side Javascript controls
function initJsChartViewer()
{
    // Check if the Javascript ChartViewer library is loaded
    if (!window.JsChartViewer)
        return;

    // Get the Javascript ChartViewer object (please replace idOfChartViewer below with
    // the real id used in your code)
    var viewer = JsChartViewer.get('idOfChartViewer');

    // TODO: Put code to connect the JsChartViewer to HTML controls that may be used to
    // configure its properties.
    //
    // ........................................
    //

    // Detect if browser is capable of support partial update (AJAX request)
    if (JsChartViewer.canSupportPartialUpdate())
    {
        // Browser can support partial update, so connect the view port change event to
        // trigger a partial update
        viewer.attachHandler("ViewPortChanged", viewer.partialUpdate);

        // TODO: Attach PreUpdate and/or PostUpdate event handlers if there are HTML
        // controls that need to send their states or receive updates from the server
        // during partial chart updates (AJAX requests)
        //
        // ........................................
        //
    }

    else
        // Browser cannot support partial update - so use full page update (in this
        // example, we assume this can be by submitting a form in the web page)
        viewer.attachHandler("ViewPortChanged", function() { document.forms[0].submit(); });

}

Library Files Required for Zoomable/Scrollable Charts

A zoomable/scrollable chart requires the following files. Please ensure you copy the necessary files to the proper directories (typically the same directory as the script) and reference them using the proper paths.

File | Description
getchart.cfm | The standard utility script used in the image url for retrieving the chart image from a session variable (see BaseChart.makeSession).
cdjcv.js zoomin.cur zoomout.cur nozoom.cur wait.gif | The script file for JsChartViewer, and the supporting cursor and image files. These files must be in the same directory.


Zooming and Scrolling Demonstration

Zooming and Scrolling Demonstration

This sample program demonstrates a zoomable and scrollable chart for time based data series. The followings are the key elements of this sample program:

  • The date/time range of the chart can be controlled by mouse actions, such as drag to scroll, drag to zoom, click to zoom, as well as by selecting the start and end dates directly using drop down list boxes.

  • Charts are updated using partial chart update (AJAX requests) by default. If the browser does not support AJAX, it will fall back to full page update. The full page update works even if the browser does not support Javascript, in which case the user can use the drop down list boxes to control the date range.

  • Zoom and scroll directions can be horizontal only (with vertical axis auto-scaled) or both horizontal and vertical.

  • Data points are with tool tips.

  • The time range of the axes can be from 5 years down to 10 days. The date/time format is configured differently depending on the time range.

  • Data are aggregated to avoid overlapping data points for long duration charts. This makes the chart sharp and clear at any zoom ratio.

The source code listing of this sample program is included at the end of this section. The code consists of the following main parts:

  • createFirstChart: This function is for handing the initial chart request. It initializes the total date/time range and the visible range, the initial view port positions as well as other chart parameters. It then calls drawChart to draw the chart.

  • processPartialUpdate: This function is for handling partial chart updates (AJAX chart updates). If the request is caused by mouse zoom/scroll actions, it computes the start and end dates based on the view port. On the other hand, if the request is caused by the user selecting the start and end dates directly from the drop down list boxes, the selected start and end dates will be used. It then calls drawChart to draw the chart, and updates the custom attributes representing the drop down list boxes to reflect the actual start and end dates used chosen.

  • processFullUpdate: This is the function for handling full page updates. It simply copies the HTTP POST or GET fields representing the drop down list boxes to the custom attributes to emulate a partial chart update, and then calls processPartialUpdate to perform the chart update.

  • drawChart: This is the main charting code. It draws the chart according to the selected date range.

  • HTML: The HTML part of the code represents the web page. Helper functions are used to generate the <OPTION> tags of the drop down list boxes. WebChartViewer.renderHTML are for generating the tags for the chart image. Some Javascript code are used to implement the push buttons used in this example.

  • initJsChartViewer: This Javascript function performs browser side initialization. It is invoked by the onload event handler of the <BODY> tag. It connects the browser side JsChartViewer with buttons for setting the mouse usage modes and for setting the zoom and scroll directions. It detects if the browser supports partial chart updates and sets up the ViewPortChanged event handler accordingly. It also sets up PreUpdate and PostUpdate event handlers to transfer the drop down list box states to and from the custom attributes, so that these list boxes can be accessible and updatable from the server side during partial chart updates.

Files in this Demonstration

This sample script requires the following files. When developing your own script using this sample script as a template, please ensure you copy the necessary files to the proper directories (typically the same directory as the script) and reference them using proper paths.

File | Description
zoomscrolldemo.cfm | Main source code for this demo.
pointer.gif zoomInIcon.gif zoomOutIcon.gif xrange.gif xyrange.gif | The images used in the push buttons in this demo.
getchart.cfm | The standard utility script used in the image url for retrieving the chart image from a session variable (see BaseChart.makeSession).
cdjcv.js zoomin.cur zoomout.cur nozoom.cur wait.gif | The script file for JsChartViewer, and the supporting cursor and image files. These files must be in the same directory.

Source Code Listing

[File: cfdemo/zoomscrolldemo.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

//
// We need to handle 3 types of request: - initial request for the full web page - partial update
// (AJAX chart update) to update the chart without reloading the page - full page update for old
// browsers that does not support partial updates
//

// The total date range of all data.
startDate = DateAdd("yyyy", -1, Now());
endDate = Now();

// The date range of the data that we zoomed into (visible on the chart).
viewPortStartDate = startDate;
viewPortEndDate = endDate;

//
// Handles the initial request
//
function createFirstChart(viewer)
{
    // Initialize the Javascript ChartViewer
    viewer.setMouseUsage(cd.MouseUsageScroll);

    // In this demo, we allow scrolling the chart for the last 5 years
    endDate = Now();
    endDate = CreateDate(Year(endDate), Month(endDate), Day(endDate));
    startDate = DateAdd("yyyy", -5, endDate);

    // The initial selected date range is last 1 year
    viewPortEndDate = endDate;
    viewPortStartDate = DateAdd("yyyy", -1, viewPortEndDate);

    // We store the scroll range as custom Javascript ChartViewer attributes, so the range can be
    // retrieved later in partial or full update requests. To avoid date format inconsistency, we
    // serialize the date to a number for storage.
    viewer.setCustomAttr("startDate", CreateODBCDateTime(startDate));
    viewer.setCustomAttr("endDate", CreateODBCDateTime(endDate));

    // In this demo, we set the maximum zoom-in to 10 days
    viewer.setZoomInWidthLimit(10.0 / DateDiff("d", startDate, endDate));

    // Draw the chart
    drawChart(viewer);
}

//
// Handles partial update (AJAX chart update)
//
function processPartialUpdate(viewer)
{
    // Declare local variables
    var duration = 0;
    var startYear = 0;
    var startMonth = 0;
    var startDay = 0;
    var endYear = 0;
    var endMonth = 0;
    var endDay = 0;

    // Retrieve the overall date range from custom Javascript ChartViewer attributes.
    startDate = ParseDateTime(viewer.getCustomAttr("startDate"));
    endDate = ParseDateTime(viewer.getCustomAttr("endDate"));

    // Now we need to determine the visible date range selected by the user. There are two
    // possibilities. The user may use the zoom/scroll features of the Javascript ChartViewer to
    // select the range, or s/he may use the start date / end date select boxes to select the date
    // range.

    if (viewer.isViewPortChangedEvent()) {
        // Is a view port change event from the Javascript ChartViewer, so we should get the
        // selected date range from the ChartViewer view port settings.
        duration = DateDiff("s", startDate, endDate);
        viewPortStartDate = DateAdd("s", viewer.getViewPortLeft() * duration, startDate);
        viewPortEndDate = DateAdd("s", viewer.getViewPortWidth() * duration, viewPortStartDate);
    } else {
        // The user has changed the selected range by using the start date / end date select boxes.
        // We need to retrieve the selected dates from those boxes. For partial updates, the select
        // box values are sent in as Javascript ChartViewer custom attributes.
        startYear = Int(viewer.getCustomAttr("StartYear"));
        startMonth = Int(viewer.getCustomAttr("StartMonth"));
        startDay = Int(viewer.getCustomAttr("StartDay"));
        endYear = Int(viewer.getCustomAttr("EndYear"));
        endMonth = Int(viewer.getCustomAttr("EndMonth"));
        endDay = Int(viewer.getCustomAttr("EndDay"));

        // Note that for browsers that do not support Javascript, there is no validation on the
        // client side. So it is possible for the day to exceed the valid range for a month (eg. Nov
        // 31, but Nov only has 30 days). So we set the date by adding the days difference to the 1
        // day of a month. For example, Nov 31 will be treated as Nov 1 + 30 days = Dec 1.
        viewPortStartDate = DateAdd("d", startDay - 1, CreateDate(startYear, startMonth, 1));
        viewPortEndDate = DateAdd("d", endDay - 1, CreateDate(endYear, endMonth, 1));
    }

    // Draw the chart
    drawChart(viewer);

    //
    // We need to communicate the new start date / end date back to the select boxes on the browser
    // side.
    //

    // Send year, month, day components to the start date / end date select boxes through Javascript
    // ChartViewer custom attributes.
    viewer.setCustomAttr("StartYear", Year(viewPortStartDate));
    viewer.setCustomAttr("StartMonth", Month(viewPortStartDate));
    viewer.setCustomAttr("StartDay", Day(viewPortStartDate));
    viewer.setCustomAttr("EndYear", Year(viewPortEndDate));
    viewer.setCustomAttr("EndMonth", Month(viewPortEndDate));
    viewer.setCustomAttr("EndDay", Day(viewPortEndDate));
}

//
// Handles full update
//
function processFullUpdate(viewer)
{
    // Declare local variables
    var ctrls = 0;
    var i = 0;

    // A full chart update is essentially the same as a partial chart update. The main difference is
    // that in a full chart update, the start date / end date select boxes are in Form Post
    // variables, while in partial chart update, they are in Javascript ChartViewer custom
    // attributes.
    //
    // So a simple implementation of the full chart update is to copy the Form Post values to the
    // Javascript ChartViewer custom attributes, and then call the partial chart update.

    // Controls to copy
    ctrls = Array("StartYear", "StartMonth", "StartDay", "EndYear", "EndMonth", "EndDay");

    // Copy control values to Javascript ChartViewer custom attributes
    for (i = 0; i LT ArrayLen(ctrls); i = i + 1) {
        viewer.setCustomAttr(ctrls[i + 1], Form[ctrls[i + 1]]);
    }

    // Now can use partial chart update
    processPartialUpdate(viewer);
}

//
// Draw the chart
//
function drawChart(viewer)
{
    // Declare local variables
    var totalDuration = 0;
    var minDuration = 0;
    var r = 0;
    var timeStamps = 0;
    var dataSeriesA = 0;
    var dataSeriesB = 0;
    var dataSeriesC = 0;
    var m = 0;
    var c = 0;
    var layer = 0;
    var minValue = 0;
    var maxValue = 0;
    var axisLowerLimit = 0;
    var axisUpperLimit = 0;
    var chartQuery = 0;
    var imageMap = 0;

    //
    // Validate and adjust the view port dates.
    //

    // Verify if the view port dates are within limits
    totalDuration = DateDiff("s", startDate, endDate);
    minDuration = viewer.getZoomInWidthLimit() * totalDuration;
    if (viewPortStartDate LT startDate) {
        viewPortStartDate = startDate;
    }
    if (DateDiff("s", viewPortStartDate, endDate) LT minDuration) {
        viewPortStartDate = DateAdd("s", -minDuration, endDate);
    }
    if (viewPortEndDate GT endDate) {
        viewPortEndDate = endDate;
    }
    if (DateDiff("s", viewPortStartDate, viewPortEndDate) LT minDuration) {
        viewPortEndDate = DateAdd("s", minDuration, viewPortStartDate);
    }

    // Adjust the view port to reflect the selected date range
    viewer.setViewPortWidth(DateDiff("s", viewPortStartDate, viewPortEndDate) / totalDuration);
    viewer.setViewPortLeft(DateDiff("s", startDate, viewPortStartDate) / totalDuration);

    //
    // Now we have the date range, we can get the necessary data. In this demo, we just use a random
    // number generator. In practice, you may get the data from a database or XML or by other means.
    // (See "Using Data Sources with ChartDirector" in the ChartDirector documentation if you need
    // some sample code on how to read data from database to array variables.)
    //

    // Just a random number generator to generate the data - emulates a table of numbers from
    // startDate to endDate
    r = cd.RanTable(127, 4, Int(0.5 + totalDuration / 86400) + 1);
    r.setDateCol(0, startDate, 86400);
    r.setCol(1, 150, -10, 10);
    r.setCol(2, 200, -10, 10);
    r.setCol(3, 250, -10, 10);

    // Emulate selecting the date range viewPortStartDate to viewPortEndDate. Note that we add one
    // day margin on both ends. It is because we are using daily data, but the view port can cover
    // partial days. For example, the view port end date can be at 3:00am Feb 1, 2006. In this case,
    // we need the data point at Feb 2, 2006.
    r.selectDate(0, DateAdd("d", -1, viewPortStartDate), DateAdd("d", 1, viewPortEndDate));

    // Emulate getting the random data from the table
    timeStamps = r.getCol(0);
    dataSeriesA = r.getCol(1);
    dataSeriesB = r.getCol(2);
    dataSeriesC = r.getCol(3);

    if (ArrayLen(timeStamps) GTE 520) {
        //
        // Zoomable chart with high zooming ratios often need to plot many thousands of points when
        // fully zoomed out. However, it is usually not needed to plot more data points than the
        // pixel resolution of the chart. Plotting too many points may cause the points and the
        // lines to overlap on the same pixel. So rather than increasing resolution, this reduces
        // the clarity of the chart. It is better to aggregate the data first if there are too many
        // points.
        //
        // In our current example, the chart plot area only has 520 pixels in width and is using a 2
        // pixel line width. So if there are more than 520 data points, we aggregate the data using
        // the ChartDirector aggregation utility method.
        //
        // If in your real application, you do not have too many data points, you may remove the
        // following code altogether.
        //

        // Set up an aggregator to aggregate the data based on regular sized slots
        m = cd.ArrayMath(timeStamps);
        m.selectRegularSpacing(ArrayLen(timeStamps) / 260);

        // For the timestamps, take the first timestamp on each slot
        timeStamps = m.aggregate(timeStamps, cd.AggregateFirst);

        // For the data values, take the averages
        dataSeriesA = m.aggregate(dataSeriesA, cd.AggregateAvg);
        dataSeriesB = m.aggregate(dataSeriesB, cd.AggregateAvg);
        dataSeriesC = m.aggregate(dataSeriesC, cd.AggregateAvg);
    }

    //
    // Now we have obtained the data, we can plot the chart.
    //

    //================================================================================
    // Step 1 - Configure overall chart appearance.
    //================================================================================

    // Create an XYChart object 600 x 300 pixels in size, with pale blue (0xf0f0ff) background,
    // black (000000) rounded border, 1 pixel raised effect.
    c = cd.XYChart(600, 300, "0xf0f0ff", "0x000000");
    c.setRoundedFrame();

    // Set the plotarea at (52, 60) and of size 520 x 192 pixels. Use white (ffffff) background.
    // Enable both horizontal and vertical grids by setting their colors to grey (cccccc). Set
    // clipping mode to clip the data lines to the plot area.
    c.setPlotArea(55, 60, 520, 192, "0xffffff", -1, -1, "0xcccccc", "0xcccccc");
    c.setClipping();

    // Add a top title to the chart using 15 pts Times New Roman Bold Italic font, with a light blue
    // (ccccff) background, black (000000) border, and a glass like raised effect.
    c.addTitle("Zooming and Scrolling Demonstration", "Times New Roman Bold Italic", 15
        ).setBackground("0xccccff", "0x000000", cd.glassEffect());

    // Add a bottom title to the chart to show the date range of the axis, with a light blue
    // (ccccff) background.
    c.addTitle2(cd.Bottom, "From <*font=Arial Bold Italic*>" & c.formatValue(viewPortStartDate,
        "{value|mmm dd, yyyy}") & "<*/font*> to <*font=Arial Bold Italic*>" & c.formatValue(
        viewPortEndDate, "{value|mmm dd, yyyy}") & "<*/font*> (Duration <*font=Arial Bold Italic*>"
         & Int(0.5 + (viewPortEndDate - viewPortStartDate)) & "<*/font*> days)", "Arial Italic", 10
        ).setBackground("0xccccff");

    // Add a legend box at the top of the plot area with 9pts Arial Bold font with flow layout.
    c.addLegend(50, 33, False, "Arial Bold", 9).setBackground(cd.Transparent, cd.Transparent);

    // Set axes width to 2 pixels
    c.xAxis().setWidth(2);
    c.yAxis().setWidth(2);

    // Add a title to the y-axis
    c.yAxis().setTitle("Price (USD)", "Arial Bold", 10);

    //================================================================================
    // Step 2 - Add data to chart
    //================================================================================

    //
    // In this example, we represent the data by lines. You may modify the code below if you want to
    // use other representations (areas, scatter plot, etc).
    //

    // Add a line layer for the lines, using a line width of 2 pixels
    layer = c.addLineLayer2();
    layer.setLineWidth(2);

    // Now we add the 3 data series to a line layer, using the color red (ff0000), green (00cc00)
    // and blue (0000ff)
    layer.setXData(timeStamps);
    layer.addDataSet(dataSeriesA, "0xff0000", "Product Alpha");
    layer.addDataSet(dataSeriesB, "0x00cc00", "Product Beta");
    layer.addDataSet(dataSeriesC, "0x0000ff", "Product Gamma");

    //================================================================================
    // Step 3 - Set up x-axis scale
    //================================================================================

    // Set x-axis date scale to the view port date range. ChartDirector auto-scaling will
    // automatically determine the ticks on the axis.
    c.xAxis().setDateScale(viewPortStartDate, viewPortEndDate);

    //
    // In the current demo, the x-axis range can be from a few years to a few days. We can let
    // ChartDirector auto-determine the date/time format. However, for more beautiful formatting, we
    // set up several label formats to be applied at different conditions.
    //

    // If all ticks are yearly aligned, then we use "yyyy" as the label format.
    c.xAxis().setFormatCondition("align", 31104000);
    c.xAxis().setLabelFormat("{value|yyyy}");

    // If all ticks are monthly aligned, then we use "mmm yyyy" in bold font as the first label of a
    // year, and "mmm" for other labels.
    c.xAxis().setFormatCondition("align", 2592000);
    c.xAxis().setMultiFormat(cd.StartOfYearFilter(), "<*font=bold*>{value|mmm yyyy}",
        cd.AllPassFilter(), "{value|mmm}");

    // If all ticks are daily algined, then we use "mmm dd<*br*>yyyy" in bold font as the first
    // label of a year, and "mmm dd" in bold font as the first label of a month, and "dd" for other
    // labels.
    c.xAxis().setFormatCondition("align", 86400);
    c.xAxis().setMultiFormat(cd.StartOfYearFilter(),
        "<*block,halign=left*><*font=bold*>{value|mmm dd<*br*>yyyy}", cd.StartOfMonthFilter(),
        "<*font=bold*>{value|mmm dd}");
    c.xAxis().setMultiFormat2(cd.AllPassFilter(), "{value|dd}");

    // For all other cases (sub-daily ticks), use "hh:nn<*br*>mmm dd" for the first label of a day,
    // and "hh:nn" for other labels.
    c.xAxis().setFormatCondition("else");
    c.xAxis().setMultiFormat(cd.StartOfDayFilter(), "<*font=bold*>{value|hh:nn<*br*>mmm dd}",
        cd.AllPassFilter(), "{value|hh:nn}");

    //================================================================================
    // Step 4 - Set up y-axis scale
    //================================================================================

    if (viewer.getZoomDirection() EQ cd.DirectionHorizontal) {
        // y-axis is auto-scaled - so vertically, the view port always cover the entire y data
        // range. We save the y-axis scale for supporting xy-zoom mode if needed in the future.
        c.layout();
        viewer.setCustomAttr("minValue", c.yAxis().getMinValue());
        viewer.setCustomAttr("maxValue", c.yAxis().getMaxValue());
        viewer.setViewPortTop(0);
        viewer.setViewPortHeight(1);
    } else {
        // xy-zoom mode - retrieve the auto-scaled axis range, which contains the entire y data
        // range.
        minValue = Val(viewer.getCustomAttr("minValue"));
        maxValue = Val(viewer.getCustomAttr("maxValue"));

        // Compute the view port axis range
        axisLowerLimit = maxValue - (maxValue - minValue) * (viewer.getViewPortTop() +
            viewer.getViewPortHeight());
        axisUpperLimit = maxValue - (maxValue - minValue) * viewer.getViewPortTop();

        // Set the axis scale to the view port axis range
        c.yAxis().setLinearScale(axisLowerLimit, axisUpperLimit);

        // By default, ChartDirector will round the axis scale to the tick position. For zooming, we
        // want to use the exact computed axis scale and so we disable rounding.
        c.yAxis().setRounding(False, False);
    }

    //================================================================================
    // Step 5 - Output the chart
    //================================================================================

    // Create the image and save it in a temporary location
    chartQuery = c.makeSession(GetPageContext(), viewer.getId());

    // Include tool tip for the chart
    imageMap = c.getHTMLImageMap("", "", "title='[{dataSetName}] {x|mmm dd, yyyy}: USD {value|2}'");

    // Set the chart URL, image map, and chart metrics to the viewer. For the image map, we use
    // delayed delivery and with compression, so the chart image will show up quicker.
    viewer.setImageUrl("getchart.cfm?" & chartQuery);
    viewer.setImageMap("getchart.cfm?" & viewer.makeDelayedMap(imageMap, True));
    viewer.setChartMetrics(c.getChartMetrics());
}

//
// A utility to create the <option> tags for the date range <select> boxes
//
// Parameters: startValue: The minimum selectable value. endValue: The maximum selectable value.
// selectedValue: The currently selected value.
//
function createSelectOptions(startValue, endValue, selectedValue)
{
    // Declare local variables
    var ret = 0;
    var i = 0;

    ret = ArrayNew(1);
    for (i = startValue; i LT endValue + 1; i = i + 1) {
        if (i EQ selectedValue) {
            // Use a "selected" <option> tag if it is the selected value
            ret[i - startValue + 1] = "<option value='" & i & "' selected>" & i & "</option>";
        } else {
            // Use a normal <option> tag
            ret[i - startValue + 1] = "<option value='" & i & "'>" & i & "</option>";
        }
    }
    return ArrayToList(ret, "");
}

// Create the WebChartViewer object
viewer = cd.WebChartViewer(GetPageContext(), "chart1");
if (viewer.isPartialUpdateRequest()) {
    // Is a partial update request (AJAX chart update)
    processPartialUpdate(viewer);
    // Since it is a partial update, there is no need to output the entire web page. We stream the
    // chart and then terminate the script immediately.
    viewer.partialUpdateChart(GetPageContext());
    return;
} else if (viewer.isFullUpdateRequest()) {
    // Is a full update request
    processFullUpdate(viewer);
} else {
    // Is a initial request
    createFirstChart(viewer);
}

// Create the <option> tags for the start date / end date select boxes to reflect the currently
// selected data range
startYearSelectOptions = createSelectOptions(Year(startDate), Year(endDate), Year(viewPortStartDate)
    );
startMonthSelectOptions = createSelectOptions(1, 12, Month(viewPortStartDate));
startDaySelectOptions = createSelectOptions(1, 31, Day(viewPortStartDate));
endYearSelectOptions = createSelectOptions(Year(startDate), Year(endDate), Year(viewPortEndDate));
endMonthSelectOptions = createSelectOptions(1, 12, Month(viewPortEndDate));
endDaySelectOptions = createSelectOptions(1, 31, Day(viewPortEndDate));

</cfscript>
<html>
<cfoutput>
<head>
    <title>ChartDirector Zoom and Scroll Demonstration</title>
    <script type="text/javascript" src="cdjcv.js"></script>
    <style type="text/css">
        div.chartPushButtonSelected { padding:5px; background:##ccffcc; cursor:hand; }
        div.chartPushButton { padding:5px; cursor:hand; }
        td.chartPushButton { font-family:Verdana; font-size:9pt; cursor:pointer; border-bottom:##000000 1px solid; }
    </style>
</head>
<body style="margin:0px" onload="initJsChartViewer()">
<script type="text/javascript">
// Initialize browser side Javascript controls
function initJsChartViewer()
{
    // Check if the Javascript ChartViewer library is loaded
    if (!window.JsChartViewer)
        return;

    // Get the Javascript ChartViewer object
    var viewer = JsChartViewer.get('#viewer.getId()#');

    // Connect the mouse usage buttons to the Javascript ChartViewer object
    connectViewerMouseUsage('ViewerMouseUsage1', viewer);
    // Connect the xy zoom mode buttons to the Javascript ChartViewer object
    connectViewerZoomControl('ViewerZoomControl1', viewer);

    // Detect if browser is capable of support partial update (AJAX chart update)
    if (JsChartViewer.canSupportPartialUpdate())
    {
        // Browser can support partial update, so connect the view port change event and
        // the submit button to trigger a partial update
        viewer.attachHandler("ViewPortChanged", viewer.partialUpdate);
        document.getElementById('SubmitButton').onclick = function() { viewer.partialUpdate(); return false; };

        // For partial updates, we need to pass the start date / end date select boxes values to/from
        // the server via Javascript ChartViewer custom attributes
        var controlsToSync = ['StartYear', 'StartMonth', 'StartDay', 'EndYear', 'EndMonth', 'EndDay'];
        viewer.attachHandler("PreUpdate", function() { copyToViewer(viewer, controlsToSync); });
        viewer.attachHandler("PostUpdate", function() { copyFromViewer(viewer, controlsToSync); });
    }
    else
        // Browser cannot support partial update - so use full page update
        viewer.attachHandler("ViewPortChanged", function() { document.forms[0].submit(); });
}
// A utility to copy HTML control values to Javascript ChartViewer custom attributes
function copyToViewer(viewer, controlsToSync)
{
    for (var i = 0; i < controlsToSync.length; ++i)
    {
        var obj = document.getElementById(controlsToSync[i]);
        if (obj && !{"button":1, "file":1, "image":1, "reset":1, "submit":1}[obj.type])
        {
            if ((obj.type == "checkbox") || (obj.type == "radio"))
                viewer.setCustomAttr(obj.id, obj.checked ? 1 : 0);
            else
                viewer.setCustomAttr(obj.id, obj.value);
        }
    }
}
// A utility to copy Javascipt ChartViewer custom attributes to HTML controls
function copyFromViewer(viewer, controlsToSync)
{
    for (var i = 0; i < controlsToSync.length; ++i)
    {
        var obj = document.getElementById(controlsToSync[i]);
        if (obj)
        {
            var value = viewer.getCustomAttr(obj.id);
            if (typeof value != "undefined")
            {
                if ((obj.type == "checkbox") || (obj.type == "radio"))
                    obj.checked = parseInt(value);
                else
                    obj.value = value;

                if (obj.validate)
                    obj.validate();
            }
        }
    }
}
</script>
<form method="post">
<table cellspacing="0" cellpadding="0" border="0">
    <tr>
        <td align="right" colspan="2" style="background:##000088">
            <div style="padding-bottom:2px; padding-right:3px; font-weight:bold; font-size:10pt; font-style:italic; font-family:Arial;">
                <a style="color:##FFFF00; text-decoration:none" href="http://www.advsofteng.com/">Advanced Software Engineering</a>
            </div>
        </td>
    </tr>
    <tr valign="top">
        <td style="width:150px; background:##c0c0ff; border-left:black 1px solid; border-right:black 1px solid; border-bottom:black 1px solid;">
            <!-- The following table is to create 3 cells for 3 buttons. The buttons are used to control
                 the mouse usage mode of the Javascript ChartViewer. -->
            <table id="ViewerMouseUsage1" cellspacing="0" cellpadding="0" width="100%" border="0">
                <tr>
                    <td class="chartPushButton">
                        <div class="chartPushButton" id="ViewerMouseUsage1_Scroll" title="Pointer">
                            <img src="pointer.gif" style="vertical-align:middle" width="16" height="16" alt="Pointer" />  Pointer
                        </div>
                    </td>
                </tr>
                <tr>
                    <td class="chartPushButton">
                        <div class="chartPushButton" id="ViewerMouseUsage1_ZoomIn" title="Zoom In">
                            <img src="zoomInIcon.gif" style="vertical-align:middle" width="16" height="16" alt="Zoom In" />  Zoom In
                        </div>
                    </td>
                </tr>
                <tr>
                    <td class="chartPushButton">
                        <div class="chartPushButton" id="ViewerMouseUsage1_ZoomOut" title="Zoom Out">
                            <img src="zoomOutIcon.gif" style="vertical-align:middle" width="16" height="16" alt="Zoom Out" />  Zoom Out
                        </div>
                    </td>
                </tr>
            </table>
            <script type="text/javascript">
            // Connect the mouse usage buttons to the Javascript ChartViewer
            function connectViewerMouseUsage(controlId, viewer)
            {
                // A cross browser utility to get the object by id.
                function getObj(id) { return document.getElementById ? document.getElementById(id) : document.all[id]; }

                // Set the button styles (colors) based on the current mouse usage mode of the Javascript ChartViewer
                function syncButtons()
                {
                    getObj(controlId + "_Scroll").className = (viewer.getMouseUsage() == JsChartViewer.Scroll) ?
                        "chartPushButtonSelected" : "chartPushButton";
                    getObj(controlId + "_ZoomIn").className = (viewer.getMouseUsage() == JsChartViewer.ZoomIn) ?
                        "chartPushButtonSelected" : "chartPushButton";
                    getObj(controlId + "_ZoomOut").className = (viewer.getMouseUsage() == JsChartViewer.ZoomOut) ?
                        "chartPushButtonSelected" : "chartPushButton";
                }
                syncButtons();

                // Run syncButtons whenever the Javascript ChartViewer is updated
                viewer.attachHandler("PostUpdate", syncButtons);

                // Set the Javascript ChartViewer mouse usage mode if a button is clicked.
                getObj(controlId + "_Scroll").onclick = function() { viewer.setMouseUsage(JsChartViewer.Scroll); syncButtons(); }
                getObj(controlId + "_ZoomIn").onclick = function() { viewer.setMouseUsage(JsChartViewer.ZoomIn); syncButtons(); }
                getObj(controlId + "_ZoomOut").onclick = function() { viewer.setMouseUsage(JsChartViewer.ZoomOut); syncButtons(); }
            }
            </script>
            <div style="font-size:9pt; margin:15px 5px 0px; font-family:verdana"><b>Zoom Mode</b></div>
            <!-- The following table is to create 2 cells for 2 buttons. The buttons are used to control
                 the zoom/scroll directions of the Javascript ChartViewer. -->
            <table id="ViewerZoomControl1" cellspacing="0" cellpadding="0" width="100%" border="0">
                <tr>
                    <td class="chartPushButton" style="border-bottom: ##000000 1px solid; border-top: ##000000 1px solid;">
                        <div class="chartPushButton" id="ViewerZoomControl1_Xmode" title="X-Axis zoomable / Y-Axis auto-scaled">
                            <img src="xrange.gif" style="vertical-align:middle" width="16" height="16" alt="X Zoom/Y Auto" />  X Zoom / Y Auto
                        </div>
                    </td>
                </tr>
                <tr>
                    <td class="chartPushButton" style="border-bottom: ##000000 1px solid;">
                        <div class="chartPushButton" id="ViewerZoomControl1_XYmode" title="X-Axis and Y-Axis zoomable">
                            <img src="xyrange.gif" style="vertical-align:middle" width="16" height="16" alt="XY Zoom" />  XY Zoom
                        </div>
                    </td>
                </tr>
            </table>
            <script type="text/javascript">
            // Connect the zoom/scroll direction buttons to the Javascript ChartViewer
            function connectViewerZoomControl(controlId, viewer)
            {
                // A cross browser utility to get the object by id.
                function getObj(id) { return document.getElementById ? document.getElementById(id) : document.all[id]; }

                // Set the button styles (colors) based on current zoom/scroll direction settings of the Javascript ChartViewer
                function syncButtons()
                {
                    getObj(controlId + "_Xmode").className = (viewer.getZoomDirection() == JsChartViewer.Horizontal) ?
                        "chartPushButtonSelected" : "chartPushButton";
                    getObj(controlId + "_XYmode").className = (viewer.getZoomDirection() == JsChartViewer.HorizontalVertical) ?
                        "chartPushButtonSelected" : "chartPushButton";
                }
                syncButtons();

                // Run syncButtons whenever the Javascript ChartViewer is updated
                viewer.attachHandler("PostUpdate", syncButtons);

                // Set the Javascript ChartViewer zoom/scroll direction if a button is clicked.
                function setViewerDirection(d)
                {
                    viewer.setScrollDirection(d);
                    viewer.setZoomDirection(d);
                    syncButtons();
                }
                getObj(controlId + "_Xmode").onclick = function() { setViewerDirection(JsChartViewer.Horizontal); }
                getObj(controlId + "_XYmode").onclick = function() { setViewerDirection(JsChartViewer.HorizontalVertical); }
            }
            </script>
            <div style="font-size:9pt; margin:15px 5px 0px; font-family:Verdana">
                <b>Start Time</b><br />
                <table cellspacing="0" cellpadding="0" border="0">
                    <tr>
                        <td style="font-size:8pt; font-family:Arial">Year</td>
                        <td style="font-size:8pt; font-family:Arial">Mon</td>
                        <td style="font-size:8pt; font-family:Arial">Day</td>
                    </tr>
                    <tr>
                        <td><select id="StartYear" name="StartYear" style="width:60">
                            #startYearSelectOptions#
                        </select></td>
                        <td><select id="StartMonth" name="StartMonth" style="width:40">
                            #startMonthSelectOptions#
                        </select></td>
                        <td><select id="StartDay" name="StartDay" style="width:40">
                            #startDaySelectOptions#
                        </select></td>
                    </tr>
                </table>
            </div>
            <div style="font-size:9pt; margin:15px 5px 0px; font-family:Verdana">
                <b>End Time</b><br />
                <table cellspacing="0" cellpadding="0" border="0">
                    <tr>
                        <td style="font-size:8pt; font-family:Arial">Year</td>
                        <td style="font-size:8pt; font-family:Arial">Mon</td>
                        <td style="font-size:8pt; font-family:Arial">Day</td>
                    </tr>
                    <tr>
                        <td><select id="EndYear" name="EndYear" style="width:60">
                            #endYearSelectOptions#
                        </select></td>
                        <td><select id="EndMonth" name="EndMonth" style="width:40">
                            #endMonthSelectOptions#
                        </select></td>
                        <td><select id="EndDay" name="EndDay" style="width:40">
                            #endDaySelectOptions#
                        </select></td>
                    </tr>
                </table>
            </div>
            <script type="text/javascript">
            // A utility to validate the day of month for the start date / end date HTML controls.
            // It sets the day of month select so that it only shows the legal range.
            function validateYMDControls(yearObj, monthObj, dayObj)
            {
                // Get the number of days in a month
                var noOfDays = [31, (parseInt(yearObj.value) % 4 == 0) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
                    [monthObj.selectedIndex];

                // Ensure the selected day of month is not bigger than the days in month
                dayObj.selectedIndex = Math.min(noOfDays - 1, dayObj.selectedIndex);

                // Extend/Shrink the day of month select box to ensure it covers the legal day range
                for (var i = dayObj.options.length; i < noOfDays; ++i)
                    dayObj.options[i] = new Option(i + 1, i + 1);
                for (var j = dayObj.options.length; j > noOfDays; --j)
                    dayObj.remove(j - 1);
            }
            // Initialize the HTML select controls for selecting dates
            function initYMDControls(yearId, monthId, dayId)
            {
                // A cross browser utility to get the object by id.
                var getObj = function(id) { return document.getElementById ? document.getElementById(id) : document.all[id]; }

                // Connect the onchange event to validateYMDControls
                getObj(yearId).onchange = getObj(yearId).validate = getObj(monthId).onchange = getObj(monthId).validate =
                    function() { validateYMDControls(getObj(yearId), getObj(monthId), getObj(dayId)); };

                // Validate once immediately
                getObj(yearId).validate();
            }
            // Connnect the start date / end date HTML select controls
            initYMDControls('StartYear', 'StartMonth', 'StartDay');
            initYMDControls('EndYear', 'EndMonth', 'EndDay');
            </script>
            <div style="margin-top:20px; font-family:Verdana; font-size:9pt; text-align:center">
                <input type="submit" id="SubmitButton" name="SubmitButton" value="Update Chart"></input>
            </div>
        </td>
        <td>
            <div style="font-weight:bold; font-size:20pt; margin:5px 0px 0px 5px; font-family:Arial">
                ChartDirector Zoom and Scroll Demonstration
            </div>
            <hr style="border:solid 1px ##000080" />
            <div style="padding:0px 5px 0px 10px">
                <!-- ****** Here is the chart image ****** -->
                #viewer.renderHTML(GetPageContext())#
            </div>
        </td>
    </tr>
</table>
</form>
</body>
</cfoutput>
</html>


Zooming and Scrolling Demonstration (2)

Zooming and Scrolling Demonstration (2)

This sample program demonstrates a general zoomable and scrollable chart. The followings are the key elements of this sample program:

  • The axis ranges of the chart can be controlled by mouse actions, such as drag to scroll, drag to zoom and click to zoom. The view port can also be moved by dragging on the rectangle on the navigation pad.

  • Charts are updated using partial chart update (AJAX requests) by default. If the browser does not support AJAX, it will fall back to full page update.

  • Data points are with tool tips.

The source code listing of this sample program is included at the end of this section. The code consists of the following main parts:

  • createFirstChart: This function is for handing the initial chart request. In this example, it simply initializes the initial state of the JsChartViewer. It then calls drawChart to draw the chart.

  • processPartialUpdate: This function is for handling partial chart updates (AJAX request). In this example, as there is no external controls that needs server side support, this function simply calls drawChart to update the chart.

  • processFullUpdate: This is the function for handling full page updates (postback). Similar to processPartialUpdate, it simply calls drawChart to update the chart.

  • drawChart: This is the main charting code. It draws the chart according to the selected axis range.

  • HTML: The HTML part of the code is for creating the web page. This include Javascript code for implementing the push buttons, and the navigation pad with the draggable rectangle.

  • initJsChartViewer: This Javascript function performs browser side initialization. It is invoked by the onload event handler of the <BODY> tag. It connects the browser side JsChartViewer with buttons for setting the mouse usage modes, and to the navigation pad for directly setting the view port. It detects if the browser supports partial chart updates and sets up the ViewPortChanged event handler accordingly.

Files in this Demonstration

This sample script requires the following files. When developing your own script using this sample script as a template, please ensure you copy the necessary files to the proper directories (typically the same directory as the script) and reference them using proper paths.

File | Description
zoomscrolldemo2.cfm | Main source code for this demo.
pointer.gif zoomInIcon.gif zoomOutIcon.gif | The images used in the push buttons in this demo.
getchart.cfm | A utility script used in the image url for retrieving the chart image from a session variable (see BaseChart.makeSession).
cdjcv.js zoomin.cur zoomout.cur nozoom.cur wait.gif | The script file for JsChartViewer, and the supporting cursor and image files. These files must be in the same directory.

Source Code Listing

[File: cfdemo/zoomscrolldemo2.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

//
// Copyright 2006 Advanced Software Engineering Limited
//
// You may use and modify the sample code in this file in your application, provided the Sample Code
// and its modifications are used only in conjunction with ChartDirector. Usage of this software is
// subjected to the terms and condition of the ChartDirector license.
//
//
// We need to handle 3 types of request: - initial request for the full web page - partial update
// (AJAX chart update) to update the chart without reloading the page - full page update for old
// browsers that does not support partial updates
//

//
// Handles the initial request
//
function createFirstChart(viewer)
{
    // Initialize the Javascript ChartViewer
    viewer.setScrollDirection(cd.DirectionHorizontalVertical);
    viewer.setZoomDirection(cd.DirectionHorizontalVertical);
    viewer.setMouseUsage(cd.MouseUsageScroll);

    // Draw the chart
    drawChart(viewer);
}

//
// Handles partial update (AJAX chart update)
//
function processPartialUpdate(viewer)
{
    // In this demo, we just need to redraw the chart
    drawChart(viewer);
}

//
// Handles full update
//
function processFullUpdate(viewer)
{
    // In this demo, we just need to redraw the chart
    drawChart(viewer);
}

//
// Draw the chart
//
function drawChart(viewer)
{
    // Declare local variables
    var dataX0 = 0;
    var dataY0 = 0;
    var dataX1 = 0;
    var dataY1 = 0;
    var dataX2 = 0;
    var dataY2 = 0;
    var c = 0;
    var legendBox = 0;
    var minX = 0;
    var maxX = 0;
    var minY = 0;
    var maxY = 0;
    var xScaleMin = 0;
    var xScaleMax = 0;
    var yScaleMax = 0;
    var yScaleMin = 0;
    var chartQuery = 0;
    var imageMap = 0;

    //
    // For simplicity, in this demo, we just use hard coded data. In a real application, the data
    // may come from a dynamic source such as a database. (See "Using Data Sources with
    // ChartDirector" in the ChartDirector documentation if you need some sample code on how to read
    // data from database to array variables.)
    //
    dataX0 = Array(10, 15, 6, -12, 14, -8, 13, -3, 16, 12, 10.5, -7, 3, -10, -5, 2, 5);
    dataY0 = Array(130, 150, 80, 110, -110, -105, -130, -15, -170, 125, 125, 60, 25, 150, 150, 15,
        120);
    dataX1 = Array(6, 7, -4, 3.5, 7, 8, -9, -10, -12, 11, 8, -3, -2, 8, 4, -15, 15);
    dataY1 = Array(65, -40, -40, 45, -70, -80, 80, 10, -100, 105, 60, 50, 20, 170, -25, 50, 75);
    dataX2 = Array(-10, -12, 11, 8, 6, 12, -4, 3.5, 7, 8, -9, 3, -13, 16, -7.5, -10, -15);
    dataY2 = Array(65, -80, -40, 45, -70, -80, 80, 90, -100, 105, 60, -75, -150, -40, 120, -50, -30)
        ;

    // Create an XYChart object 500 x 480 pixels in size, with light blue (c0c0ff) as background
    // color
    c = cd.XYChart(500, 480, "0xc0c0ff");

    // Set the plotarea at (50, 40) and of size 400 x 400 pixels. Use light grey (c0c0c0) horizontal
    // and vertical grid lines. Set 4 quadrant coloring, where the colors of the quadrants alternate
    // between lighter and deeper grey (dddddd/eeeeee).
    c.setPlotArea(50, 40, 400, 400, -1, -1, -1, "0xc0c0c0", "0xc0c0c0").set4QBgColor("0xdddddd",
        "0xeeeeee", "0xdddddd", "0xeeeeee", "0x000000");

    // Enable clipping mode to clip the part of the data that is outside the plot area.
    c.setClipping();

    // Set 4 quadrant mode, with both x and y axes symetrical around the origin
    c.setAxisAtOrigin(cd.XYAxisAtOrigin, cd.XAxisSymmetric + cd.YAxisSymmetric);

    // Add a legend box at (450, 40) (top right corner of the chart) with vertical layout and 8 pts
    // Arial Bold font. Set the background color to semi-transparent grey (40dddddd).
    legendBox = c.addLegend(450, 40, True, "Arial Bold", 8);
    legendBox.setAlignment(cd.TopRight);
    legendBox.setBackground("0x40dddddd");

    // Add titles to axes
    c.xAxis().setTitle("Alpha Index");
    c.yAxis().setTitle("Beta Index");

    // Set axes line width to 2 pixels
    c.xAxis().setWidth(2);
    c.yAxis().setWidth(2);

    // The default ChartDirector settings has a denser y-axis grid spacing and less-dense x-axis
    // grid spacing. In this demo, we want the tick spacing to be symmetrical. We use around 40
    // pixels between major ticks and 20 pixels between minor ticks.
    c.xAxis().setTickDensity(40, 20);
    c.yAxis().setTickDensity(40, 20);

    //
    // In this example, we represent the data by scatter points. If you want to represent the data
    // by somethings else (lines, bars, areas, floating boxes, etc), just modify the code below to
    // use the layer type of your choice.
    //

    // Add scatter layer, using 11 pixels red (ff33333) X shape symbols
    c.addScatterLayer(dataX0, dataY0, "Group A", cd.Cross2Shape(), 11, "0xff3333");

    // Add scatter layer, using 11 pixels green (33ff33) circle symbols
    c.addScatterLayer(dataX1, dataY1, "Group B", cd.CircleShape, 11, "0x33ff33");

    // Add scatter layer, using 11 pixels blue (3333ff) triangle symbols
    c.addScatterLayer(dataX2, dataY2, "Group C", cd.TriangleSymbol, 11, "0x3333ff");

    if (viewer.getCustomAttr("minY") EQ "") {
        // The axis scale has not yet been set up. This means this is the first time the chart is
        // drawn and it is drawn with no zooming. We can use auto-scaling to determine the
        // axis-scales, then remember them for future use.

        // explicitly auto-scale axes so we can get the axis scales
        c.layout();

        // save the axis scales for future use
        viewer.setCustomAttr("minX", c.xAxis().getMinValue());
        viewer.setCustomAttr("maxX", c.xAxis().getMaxValue());
        viewer.setCustomAttr("minY", c.yAxis().getMinValue());
        viewer.setCustomAttr("maxY", c.yAxis().getMaxValue());
    } else {
        // Retrieve the original full axes scale
        minX = Val(viewer.getCustomAttr("minX"));
        maxX = Val(viewer.getCustomAttr("maxX"));
        minY = Val(viewer.getCustomAttr("minY"));
        maxY = Val(viewer.getCustomAttr("maxY"));

        // Compute the zoomed-in axis scales by multiplying the full axes scale with the view port
        // ratio
        xScaleMin = minX + (maxX - minX) * viewer.getViewPortLeft();
        xScaleMax = minX + (maxX - minX) * (viewer.getViewPortLeft() + viewer.getViewPortWidth());
        yScaleMax = maxY - (maxY - minY) * viewer.getViewPortTop();
        yScaleMin = maxY - (maxY - minY) * (viewer.getViewPortTop() + viewer.getViewPortHeight());

        // Set the axis scales
        c.xAxis().setLinearScale(xScaleMin, xScaleMax);
        c.yAxis().setLinearScale(yScaleMin, yScaleMax);

        // By default, ChartDirector will round the axis scale to the tick position. For zooming, we
        // want to use the exact computed axis scale and so we disable rounding.
        c.xAxis().setRounding(False, False);
        c.yAxis().setRounding(False, False);
    }

    // Create the image
    chartQuery = c.makeSession(GetPageContext(), viewer.getId());

    // Include tool tip for the chart
    imageMap = c.getHTMLImageMap("", "", "title='[{dataSetName}] Alpha = {x|G}, Beta = {value|G}'");

    // Set the chart URL, image map, and chart metrics to the viewer
    viewer.setImageUrl("getchart.cfm?" & chartQuery);
    viewer.setImageMap(imageMap);
    viewer.setChartMetrics(c.getChartMetrics());
}

// Create the WebChartViewer object
viewer = cd.WebChartViewer(GetPageContext(), "chart1");

if (viewer.isPartialUpdateRequest()) {
    // Is a partial update request (AJAX chart update)
    processPartialUpdate(viewer);
    // Since it is a partial update, there is no need to output the entire web page. We stream the
    // chart and then terminate the script immediately.
    viewer.partialUpdateChart(GetPageContext());
    return;
} else if (viewer.isFullUpdateRequest()) {
    // Is a full update request
    processFullUpdate(viewer);
} else {
    // Is a initial request
    createFirstChart(viewer);
}

</cfscript>
<html>
<cfoutput>
<head>
    <title>ChartDirector Zoom and Scroll Demonstration (2)</title>
    <script type="text/javascript" src="cdjcv.js"></script>
    <style type="text/css">
        div.chartPushButtonSelected { padding:5px; background:##ccffcc; cursor:hand; }
        div.chartPushButton { padding:5px; cursor:hand; }
        td.chartPushButton { font-family:Verdana; font-size:9pt; cursor:pointer; border-bottom:##000000 1px solid; }
    </style>
</head>
<body style="margin:0px" onload="initJsChartViewer()">
<script type="text/javascript">
// Initialize browser side Javascript controls
function initJsChartViewer()
{
    // Check if the Javascript ChartViewer library is loaded
    if (!window.JsChartViewer)
        return;

    // Get the Javascript ChartViewer object
    var viewer = JsChartViewer.get('#viewer.getId()#');

    // Connect the mouse usage buttons to the Javascript ChartViewer object
    connectViewerMouseUsage('ViewerMouseUsage1', viewer);

    // Connect the view port window navigation pad to the Javascript ChartViewer object
    connectViewerViewPort('ViewerViewPort1', viewer);

    // Detect if browser is capable of support partial update (AJAX chart update)
    if (JsChartViewer.canSupportPartialUpdate())
        // Browser can support partial update, so connect the view port change event to
        // trigger a partial update
        viewer.attachHandler("ViewPortChanged", viewer.partialUpdate);
    else
        // Browser cannot support partial update - so use full page update
        viewer.attachHandler("ViewPortChanged", function() { document.forms[0].submit(); });
}
</script>
<form method="post">
<table cellspacing="0" cellpadding="0" border="0">
    <tr>
        <td align="right" colspan="2" style="background:##000088">
            <div style="padding-bottom:2px; padding-right:3px; font-weight:bold; font-size:10pt; font-style:italic; font-family:Arial;">
                <a style="color:##FFFF00; text-decoration:none" href="http://www.advsofteng.com/">Advanced Software Engineering</a>
            </div>
        </td>
    </tr>
    <tr valign="top">
        <td style="width:130px; background:##e0e0e0; border-left:black 1px solid; border-top:black 1px solid; border-bottom:black 1px solid;">
            <!-- The following table is to create 3 cells for 3 buttons. The buttons are used to control
                 the mouse usage mode of the Javascript ChartViewer. -->
            <table id="ViewerMouseUsage1" cellspacing="0" cellpadding="0" width="100%" border="0">
                <tr>
                    <td class="chartPushButton">
                        <div class="chartPushButton" id="ViewerMouseUsage1_Scroll" title="Pointer">
                            <img src="pointer.gif" style="vertical-align:middle" width="16" height="16" alt="Pointer" />  Pointer
                        </div>
                    </td>
                </tr>
                <tr>
                    <td class="chartPushButton">
                        <div class="chartPushButton" id="ViewerMouseUsage1_ZoomIn" title="Zoom In">
                            <img src="zoomInIcon.gif" style="vertical-align:middle" width="16" height="16" alt="Zoom In" />  Zoom In
                        </div>
                    </td>
                </tr>
                <tr>
                    <td class="chartPushButton">
                        <div class="chartPushButton" id="ViewerMouseUsage1_ZoomOut" title="Zoom Out">
                            <img src="zoomOutIcon.gif" style="vertical-align:middle" width="16" height="16" alt="Zoom Out" />  Zoom Out
                        </div>
                    </td>
                </tr>
            </table>
            <script type="text/javascript">
            // Connect the mouse usage buttons to the Javascript ChartViewer
            function connectViewerMouseUsage(controlId, viewer)
            {
                // A cross browser utility to get the object by id.
                function getObj(id) { return document.getElementById ? document.getElementById(id) : document.all[id]; }

                // Set the button styles (colors) based on mouse usage mode
                function syncButtons()
                {
                    getObj(controlId + "_Scroll").className = (viewer.getMouseUsage() == JsChartViewer.Scroll) ?
                        "chartPushButtonSelected" : "chartPushButton";
                    getObj(controlId + "_ZoomIn").className = (viewer.getMouseUsage() == JsChartViewer.ZoomIn) ?
                        "chartPushButtonSelected" : "chartPushButton";
                    getObj(controlId + "_ZoomOut").className = (viewer.getMouseUsage() == JsChartViewer.ZoomOut) ?
                        "chartPushButtonSelected" : "chartPushButton";
                }
                syncButtons();

                // Run syncButtons whenever the Javascript ChartViewer is updated
                viewer.attachHandler("PostUpdate", syncButtons);

                // Set the Javascript ChartViewer mouse usage mode if the buttons are clicked.
                getObj(controlId + "_Scroll").onclick = function() { viewer.setMouseUsage(JsChartViewer.Scroll); syncButtons(); }
                getObj(controlId + "_ZoomIn").onclick = function() { viewer.setMouseUsage(JsChartViewer.ZoomIn); syncButtons(); }
                getObj(controlId + "_ZoomOut").onclick = function() { viewer.setMouseUsage(JsChartViewer.ZoomOut); syncButtons(); }
            }
            </script>
            <br /><br /><br /><br />
            <!-- The following DIV blocks constitute the view port navigation pad. -->
            <div id="ViewerViewPort1" style="margin: 10px 5px; text-align: center">
                <div style="border:black 1px solid; padding:0px; margin:0px; width:120px; height:120px; background-color:##c0c0ff;
                    text-align:left">
                    <div id="ViewerViewPort1_ViewPort" style="border:black 1px solid; padding:0px; margin:0px; visibility:hidden;
                        width:60px; height:60px; position:relative; background-color:##c0c0c0">
                        <img src="" style="display:none" height="1" width="1" alt="" />
                    </div>
                </div>
            </div>
            <script type="text/javascript">
            // Connect the view port navigation pad to the Javascript ChartViewer
            function connectViewerViewPort(controlId, viewer)
            {
                // A cross browser utility to get the object by id.
                function getObj(id) { return document.getElementById ? document.getElementById(id) : document.all[id]; }

                // Get the inner rectangle representing the visible view port
                var p = getObj(controlId + "_ViewPort");

                // Set up the mouse down event handler
                p.onmousedown = ViewerViewPort_startDrag;
                p.viewer = viewer;

                // Remember the width and height of the outer container of the navigation pad. The exact definition of
                // width and height differs depending on browsers (some includes the borders and some exclude the borders).
                var parent = p.parentElement || p.parentNode;
                p.parentW = parent.offsetWidth - (document.all ? 2 : 4);
                p.parentH = parent.offsetHeight - (document.all ? 2 : 4);

                // Connect the view port to the viewer PostUpdate handler
                connectViewPortHandler(controlId, viewer);

                // The navigation pad has been set up, so can display it now.
                p.style.visibility = "visible";
            }
            // Connect the view port to the viewer PostUpdate handler
            function connectViewPortHandler(controlId, viewer)
            {
                // Set the navigation pad size and position depending on the Javascript ChartViewer view port state
                var syncViewPort = function()
                {
                    // A cross browser utility to get the object by id.
                    function getObj(id) { return document.getElementById ? document.getElementById(id) : document.all[id]; }

                    // Get the inner rectangle representing the visible view port
                    var p = getObj(controlId + "_ViewPort");

                    // Set the size and position based on Javascript ChartViewer view port state
                    p.currentWidth = p.style.width = Math.round(p.parentW * viewer.getViewPortWidth());
                    p.currentHeight = p.style.height = Math.round(p.parentH * viewer.getViewPortHeight());
                    p.currentX = p.style.left = Math.round(p.parentW * viewer.getViewPortLeft());
                    p.currentY = p.style.top = Math.round(p.parentH * viewer.getViewPortTop());
                }
                syncViewPort();

                // Run syncViewPort whenever the Javascript ChartViewer is updated
                viewer.attachHandler("PostUpdate", syncViewPort);
            }
            // Mouse down event handler
            function ViewerViewPort_startDrag(e)
            {
                if (document.onmousemove != ViewerViewPort_mouseMove)
                {
                    // Remember the current onmousemove and onmouseup event handler and replace them
                    // with our own handler
                    document.ViewerViewPort_onmousemovesave = document.onmousemove;
                    document.ViewerViewPort_onmouseupsave = document.onmouseup;
                    document.onmousemove = ViewerViewPort_mouseMove;
                    document.onmouseup = ViewerViewPort_endDrag;
                }

                // Remember the mouse down position
                document.ViewerViewPort_dragObj = this;
                this.refX = this.currentX - (window.event || e).clientX;
                this.refY = this.currentY - (window.event || e).clientY;
            }
            // Mouse move event handler
            function ViewerViewPort_mouseMove(e)
            {
                // Set the position of the navigation pad depending on how far the mouse has been dragged
                var obj = document.ViewerViewPort_dragObj;
                obj.currentX = obj.style.left =
                    Math.max(0, Math.min(obj.refX + (window.event || e).clientX, obj.parentW - obj.currentWidth));
                obj.currentY = obj.style.top =
                    Math.max(0, Math.min(obj.refY + (window.event || e).clientY, obj.parentH - obj.currentHeight));
                return false;
            }
            // Mouse up event handler
            function ViewerViewPort_endDrag(e)
            {
                // Restore the previous nmousemove and onmouseup event handler
                document.onmousemove = document.ViewerViewPort_onmousemovesave;
                document.onmouseup = document.ViewerViewPort_onmouseupsave;

                // Set the new view port position based on the mouse position
                var newVpLeft = 0;
                var newVpTop = 0;
                var obj = document.ViewerViewPort_dragObj;
                if (obj.viewer.getViewPortWidth() < 1)
                    newVpLeft = obj.currentX / (obj.parentW - obj.currentWidth) * (1 - obj.viewer.getViewPortWidth());
                if (obj.viewer.getViewPortHeight() < 1)
                    newVpTop = obj.currentY / (obj.parentH - obj.currentHeight) * (1 - obj.viewer.getViewPortHeight());

                // Change the view port only when the new view port position is really different from
                // existing position (to avoid unnecessary partial or full update)
                if ((Math.abs(obj.viewer.getViewPortLeft() - newVpLeft) > 0.0000001) ||
                    (Math.abs(obj.viewer.getViewPortTop() - newVpTop) > 0.0000001))
                {
                    obj.viewer.setViewPortLeft(newVpLeft);
                    obj.viewer.setViewPortTop(newVpTop);
                    obj.viewer.applyHandlers("ViewPortChanged");
                }
            }
            </script>
        </td>
        <td style="border: black 1px solid; background-color: ##c0c0ff">
            <div style="padding:5px">
                <!-- ****** Here is the chart image ****** -->
                #viewer.renderHTML(GetPageContext())#
            </div>
        </td>
    </tr>
</table>
</form>
</body>
</cfoutput>
</html>


Realtime Charts

Realtime Charts

This section describes how to use ChartDirector to create realtime charts.

In this section

Realtime Charts in ChartDirector
Description of the general approach of creating realtime charts in ChartDirector.

Realtime Chart Demonstration
This sample program demonstrates a realtime chart with configurable chart update rate.


Realtime Charts in ChartDirector

Realtime Charts in ChartDirector

For web applications, a realtime chart may be achieved by using browser side Javascript to periodic refreshes the <IMG> tag that displays the chart.

Typically, an HTML web page is created with an <IMG> tag for displaying the chart. The URL of the <IMG> tag points to a charting page that generates the most updated chart as an image. A browser side Javascript in the HTML web page periodically refreshes the <IMG> tag. This causes the chart to update periodically without refreshing the entire web page.

The code for refreshing the <IMG> tag can easily be implemented using standard browser side Javascript without any third party library at all. The ChartDirector Javascript ChartViewer also has a special method JsChartViewer.streamUpdate to support realtime charts, providing enhanced features such as double buffering, handling of overlapping updates, error handling and cache avoidance.


Realtime Chart Demonstration

Realtime Chart Demonstration

This sample program demonstrates a realtime chart with configurable chart update rate. The chart is being updated without the entire page refreshing.

The code consists of two parts - the containing web page and the charting page.

The containing web page is in HTML, with an <IMG> tag for displaying the chart. A browser side Javascript periodically refreshes the <IMG> tag. This causes new requests to the charting page, which will return updated charts. So the chart appears to update in periodically.

The container web page can easily be implemented using standard browser side Javascript without any third party library at all. However, in this example, we demonstrate using the JsChartViewer library for refreshing the <IMG>, as it offers several advantages like double buffering (to avoid flickering), handling of overlapping updates, better error handling and cache avoidance. See JsChartViewer.streamUpdate for more details.

NOTE: This sample script uses "cdjcv.js". When developing your own script using this sample code as a template, please ensure you copy "cdjcv.js" to the proper directory and reference it using the proper path.

Source Code Listing

[File: cfdemo/realtimedemo.cfm]
<html>
<cfoutput>
<head>
    <title>ChartDirector Realtime Chart Demonstration</title>
    <script type="text/javascript" src="cdjcv.js"></script>
</head>
<body style="margin:0px">
<table cellspacing="0" cellpadding="0" border="0">
    <tr>
        <td align="right" colspan="2" style="background:##000088">
            <div style="padding-bottom:2px; padding-right:3px; font-weight:bold; font-size:10pt; font-style:italic; font-family:Arial;">
                <a style="color:##FFFF00; text-decoration:none" href="http://www.advsofteng.com/">Advanced Software Engineering</a>
            </div>
        </td>
    </tr>
    <tr valign="top">
        <td style="width:150px; background:##c0c0ff; border-left:black 1px solid; border-right:black 1px solid; border-bottom:black 1px solid;">
            <br /><br />
            <div style="padding:10px; font-size:9pt; font-family:Verdana">
                <b>Update Period</b><br />
                <select id="UpdatePeriod" style="width:130px">
                    <option value="5">5 seconds</option>
                    <option value="10" selected="selected">10 seconds</option>
                    <option value="20">20 seconds</option>
                    <option value="30">30 seconds</option>
                    <option value="60">60 seconds</option>
                </select>
            </div>
            <div style="padding:10px; font-size:9pt; font-family:Verdana">
                <b>Time Remaining</b><br />
                <div style="width:130px; border:##888888 1px inset;">
                    <div style="margin:3px" id="TimeRemaining"> </div>
                </div>
            </div>
        </td>
        <td>
            <div style="font-weight:bold; font-size:20pt; margin:5px 0px 0px 5px; font-family:Arial">
                ChartDirector Realtime Chart Demonstration
            </div>
            <hr style="border:solid 1px ##000080" />
            <div style="padding:0px 5px 0px 10px">
                <!-- ****** Here is the image tag for the chart image ****** -->
                <img id="ChartImage1" src="realtimechart.cfm?chartId=demoChart1">
            </div>
        </td>
    </tr>
</table>
<script type="text/javascript">
// The followings is executed once every second
function updateDisplay()
{
    // Utility to get an object by id that works with most browsers
    var getObj = function(id) {    return document.getElementById ? document.getElementById(id) : document.all[id]; }

    // Get the configured update period
    var updatePeriodObj = getObj("UpdatePeriod");
    var updatePeriod = parseInt(updatePeriodObj.value);

    // Subtract 1 second for the remaining time - reload the counter if remaining time is 0
    if (!updatePeriodObj.timeLeft || (updatePeriodObj.timeLeft <= 0))
        updatePeriodObj.timeLeft = updatePeriod - 1;
    else
        updatePeriodObj.timeLeft = Math.min(updatePeriod, updatePeriodObj.timeLeft) - 1;

    // Update the chart if configured time has elasped
    if ((updatePeriodObj.timeLeft <= 0) && window.JsChartViewer)
        JsChartViewer.get('ChartImage1').streamUpdate();

    // Update the display to show remaining time
    getObj("TimeRemaining").innerHTML = updatePeriodObj.timeLeft + ((updatePeriodObj.timeLeft > 1) ? " seconds" : " second");
}
window.setInterval("updateDisplay()", 1000);
</script>
</body>
</cfoutput>
</html>

[File: cfdemo/realtimechart.cfm]
<cfscript>

// ChartDirector for ColdFusion API Access Point
cd = CreateObject("java", "ChartDirector.CFChart");

// A utility to allow us to create arrays with data in one line of code
function Array() {
    var result = ArrayNew(1);
    var i = 0;
    for (i = 1; i LTE ArrayLen(arguments); i = i + 1)
        result[i] = arguments[i];
    return result;
}

//
// Data to draw the chart. In this demo, the data buffer will be filled by a random
// data generator. In real life, the data is probably stored in a buffer (eg. a
// database table, a text file, or some global memory) and updated by other means.
//

// We use a data buffer to emulate the last 240 samples.
sampleSize = 240;
dataSeries1 = ArrayNew(1);
dataSeries2 = ArrayNew(1);
dataSeries3 = ArrayNew(1);
timeStamps = ArrayNew(1);

// Our pseudo random number generator
firstDate = DateAdd("s", -sampleSize, Now());
for (i = 0; i LT sampleSize; i = i + 1) {
    timeStamps[i + 1] = DateAdd("s", i, firstDate);
    p = Second(timeStamps[i + 1]) + Minute(timeStamps[i + 1]) * 60 + Hour(timeStamps[
        i + 1]) * 3600;
    dataSeries1[i + 1] = Cos(p * 7 * 18463) * 10 + 1 / (Cos(p) * Cos(p) + 0.01) + 20;
    dataSeries2[i + 1] = 100 * Sin(p / 27.7) * Sin(p / 10.1) + 150;
    dataSeries3[i + 1] = 100 * Cos(p / 6.7) * Cos(p / 11.9) + 150;
}

// Create an XYChart object 600 x 270 pixels in size, with light grey (f4f4f4)
// background, black (000000) border, 1 pixel raised effect, and with a rounded
// frame.
c = cd.XYChart(600, 270, "0xf4f4f4", "0x000000", 0);
c.setRoundedFrame();

// Set the plotarea at (55, 62) and of size 520 x 175 pixels. Use white (ffffff)
// background. Enable both horizontal and vertical grids by setting their colors to
// grey (cccccc). Set clipping mode to clip the data lines to the plot area.
c.setPlotArea(55, 62, 520, 175, "0xffffff", -1, -1, "0xcccccc", "0xcccccc");
c.setClipping();

// Add a title to the chart using 15 pts Times New Roman Bold Italic font, with a
// light grey (dddddd) background, black (000000) border, and a glass like raised
// effect.
c.addTitle("Zooming and Scrolling Demonstration", "Times New Roman Bold Italic", 15
    ).setBackground("0xdddddd", "0x000000", cd.glassEffect());

// Add a legend box at the top of the plot area with 9pts Arial Bold font. We set the
// legend box to the same width as the plot area and use grid layout (as opposed to
// flow or top/down layout). This distributes the 3 legend icons evenly on top of the
// plot area.
b = c.addLegend2(55, 33, 3, "Arial Bold", 9);
b.setBackground(cd.Transparent, cd.Transparent);
b.setWidth(520);

// Configure the y-axis with a 10pts Arial Bold axis title
c.yAxis().setTitle("Price (USD)", "Arial Bold", 10);

// Configure the x-axis to auto-scale with at least 75 pixels between major tick and
// 15 pixels between minor ticks. This shows more minor grid lines on the chart.
c.xAxis().setTickDensity(75, 15);

// Set the axes width to 2 pixels
c.xAxis().setWidth(2);
c.yAxis().setWidth(2);

// Set the x-axis label format
c.xAxis().setLabelFormat("{value|hh:nn:ss}");

// Create a line layer to plot the lines
layer = c.addLineLayer2();

// The x-coordinates are the timeStamps.
layer.setXData(timeStamps);

// The 3 data series are used to draw 3 lines. Here we put the latest data values as
// part of the data set name, so you can see them updated in the legend box.
layer.addDataSet(dataSeries1, "0xff0000", c.formatValue(dataSeries1[ArrayLen(
    dataSeries1)], "Software: <*bgColor=FFCCCC*> {value|2} "));
layer.addDataSet(dataSeries2, "0x00cc00", c.formatValue(dataSeries2[ArrayLen(
    dataSeries2)], "Hardware: <*bgColor=CCFFCC*> {value|2} "));
layer.addDataSet(dataSeries3, "0x0000ff", c.formatValue(dataSeries3[ArrayLen(
    dataSeries3)], "Services: <*bgColor=CCCCFF*> {value|2} "));

// Output the chart
chart1URL = c.makeSession(GetPageContext(), "chart1");

// Stream chart directly to browser
GetPageContext().forward("getchart.cfm?" & chart1URL);

</cfscript>


ChartDirector Reference

ChartDirector Reference

This sector contains reference documentation for all ChartDirector classes and methods, as well as the data types and other conventions used in ChartDirector.

In this section

Class Library
Describes all ChartDirector classes and methods

Controls
Describes controls and libraries for displaying charts and handling user interactions.

Data Types
Describes how ChartDirector represents colors, font attributes, date/time, alignments, NoValue and re-sampling filters.

ChartDirector Mark Up Language
CDML is a language for including formatting information in text strings by marking up the text with tags. CDML allows a single text string to be rendered using multiple fonts, with different colors, and even embed images in the text.

Parameter Substitution and Formatting
ChartDirector's template driven approach to precisely control the content of labels, as well as the number and date/time formats used.

Internationalization
Describes international characters support in ChartDirector


Class Library

Class Library

This section describes the core ChartDirector classes.

ChartDirector.CFChart

ChartDirector.CFChart is the Java class representing the access point of the ChartDirector API. You may use the ColdFusion "CreateObject" function to set up a variable to represent ChartDirector.CFChart.

Fundamental Classes

Class | Description
Box | The Box class represents boxes. It is used as the base class for more complex classes (such as the TextBox class).
TextBox | The TextBox class represents text boxes. It is a subclass of Box.
Line | The Line class represents straight lines.

General Charts

Class | Description
BaseChart | The BaseChart class is an abstract class containing methods that are common to all chart types.
MultiChart | The MultiChart class represents multi-charts. A multi-chart is a container to contain multiple charts. MultiChart is a subclass of BaseChart.
LegendBox | The class LegendBox represents legend boxes. It is a subclass of TextBox.

Pie Charts Related

Class | Description
PieChart | The PieChart class represents pie charts. It is a subclass of BaseChart.
Sector | The Sector class represents sectors.

XY Charts Related

Class | Description
XYChart | The XYChart class represents XY charts. The XYChart class is a subclass of BaseChart.
PlotArea | The PlotArea class represents plot areas in XY charts.
Axis | The Axis class represents x and y axes in XY charts.
Mark | The Mark class represents mark lines. It is a subclass of TextBox.
Layer | The Layer class is the base class for all XYChart layer classes.
BarLayer | The BarLayer class represents bar layers. BarLayer is a subclass of Layer.
LineLayer | The LineLayer class represents line layers. LineLayer is a subclass of Layer.
SplineLayer | The SplineLayer class represents spline layers. SplineLayer is a subclass of LineLayer.
StepLineLayer | The StepLineLayer class represents step line layers. StepLineLayer is a subclass of LineLayer.
TrendLayer | The TrendLayer class represents trend layers. TrendLayer is a subclass Layer.
InterLineLayer | The InterLineLayer class represents interline layers. InterLineLayer is a subclass of Layer.
ScatterLayer | The ScatterLayer class represents scatter layers. ScatterLayer is a subclass of Layer.
AreaLayer | The AreaLayer class represents area layers. AreaLayer is a subclass of Layer.
BaseBoxLayer | The BaseBoxLayer class is the base class for layers that uses isolated symbols to represent multiple data sets. These include BoxWhiskerLayer, HLOCLayer and CandleStickLayer. BaseBoxLayer is a subclass of Layer.
HLOCLayer | The HLOCLayer class represents high-low-open-close layers. HLOCLayer is a subclass of BaseBoxLayer.
CandleStickLayer | The CandleStickLayer class represents candlestick layers. CandleStickLayer is a subclass of BaseBoxLayer.
BoxWhiskerLayer | The BoxWhiskerLayer class represents box-whisker layers. BoxWhiskerLayer is a subclass of BaseBoxLayer.
VectorLayer | The VectorLayer class represents vector layers. VectorLayer is a subclass of Layer.
DataSet | The DataSet class represents data sets.

Polar Charts Related

Class | Description
PolarChart | The PolarChart class represents polar charts (including radar charts). The PolarChart class is a subclass of BaseChart.
RadialAxis | The RadialAxis class represents radial axes in polar charts. The radial axis is the axis representing the radius component of a polar coordinate.
AngularAxis | The AngularAxis class represents angular axes in polar charts. The angular axis is the axis representing the angular component of a polar coordinate.
PolarLayer | The PolarLayer class is the base class for all PolarChart layer classes.
PolarLineLayer | The PolarLineLayer class represents polar area layers. PolarLineLayer is a subclass of PolarLayer.
PolarAreaLayer | The PolarAreaLayer class represents polar area layers. PolarAreaLayer is a subclass of PolarLayer.
PolarSplineLineLayer | The PolarSplineLineLayer class represents polar spline line layers. PolarSplineLineLayer is a subclass of PolarLineLayer.
PolarSplineAreaLayer | The PolarSplineAreaLayer class represents polar spline area layers. PolarSplineAreaLayer is a subclass of PolarAreaLayer.
PolarVectorLayer | The PolarVectorLayer class represents polar vector layers. PolarVectorLayer is a subclass of PolarLayer.

Meters and Gauges

Class | Description
BaseMeter | The BaseMeter class is the base class of all meters in ChartDirector.
AngularMeter | The AngularMeter class represents angular meters. AngularMeter is a subclass of BaseMeter.
LinearMeter | The LinearMeter class represents linear meters. LinearMeter is a subclass of BaseMeter.
MeterPointer | The MeterPointer class represent meter pointers in both angular and linear meters.

Finance Charts Related

Class | Description
FinanceChart | FinanceChart is a powerful financial charting library built on top of the main ChartDirector library. It extends MultiChart by implementing many financial indicators, and allowing complex financial charts to be composed easily.

Graphics Primitives

Class | Description
DrawArea | The DrawArea class represents drawing surfaces, with methods for performing graphics primitives (such as drawing lines, shapes and texts) and the surfaces.
TTFText | The TTFText class represents text blocks.

Utility Classes

Class | Description
ArrayMath | The ArrayMath class is a utility class used to perform array computations.
RanTable | RanTable is a utility class to produce tables with random numbers.
FinanceSimulator | FinanceSimulator is a utility class to produce random data that looks like financial data series.


ChartDirector.CFChart

ChartDirector.CFChart

ChartDirector.CFChart is the Java class representing the access point of the ChartDirector API. You may use the ColdFusion "CreateObject" function to set up a variable to represent ChartDirector.CFChart.

For example :

cd = CreateObject("java", "ChartDirector.CFChart");

In the ColdFusion edition of ChartDirector, constructors for the main chart objects are implemented as static methods of ChartDirector.CFChart. Predefined constants are implemented as static properties of ChartDirector.CFChart.

For example, to create an XYChart object, one has to call the cd.XYChart method, where cd is the variable representing ChartDirector.CFChart. Similarly, to access the NoValue constant, one has to use cd.NoValue.

Properties
Name | Description
NoValue | A constant equals to 1.7E+308 to represent missing values in ChartDirector.
BottomLeft | A constant equals to 1 to represent the bottom left position.
BottomLeft2 | A constant equals to 12 to represent the alternative exterior bottom left position.
BottomCenter | A constant equals to 2 to represent the bottom center position.
BottomRight | A constant equals to 3 to represent the bottom right position.
BottomRight2 | A constant equals to 13 to represent the alternative exterior bottom right position.
Left | A constant equals to 4 to represent the left position.
Center | A constant equals to 5 to represent the center position.
Right | A constant equals to 6 to represent the right position.
TopLeft | A constant equals to 7 to represent the top left position.
TopLeft2 | A constant equals to 10 to represent the alternative exterior top left position.
TopCenter | A constant equals to 8 to represent the top center position.
TopRight | A constant equals to 9 to represent the top right position.
TopRight2 | A constant equals to 11 to represent the alternative exterior top right position.
Bottom | A constant equals to 2 to represent the bottom position.
Top | A constant equals to 8 to represent the top position.
Transparent | A constant equals to FF000000 (in hex) to represent the transparent color.
BackgroundColor | A constant equals to FFFF0000 (in hex) to represent the background color.
LineColor | A constant equals to FFFF0001 (in hex) to represent the default line color.
TextColor | A constant equals to FFFF0002 (in hex) to represent the default text color.
SameAsMainColor | A constant equals to FFFF0007 (in hex) to represent the current main color.
Palette | A constant equals to FFFF0000 (in hex) to represent the starting index of the color palette.
DataColor | A constant equals to FFFF0008 (in hex) to represent the starting index of automatic data color.
defaultPalette | A constant array of integers to represent the default palette.
whiteOnBlackPalette | A constant array of integers to represent the white on black palette.
transparentPalette | A constant array of integers to represent the semi-transparent palette.
NormalGlare | A constant equals to 3 to represent using normal glare strength in ChartDirector.CFChart.glassEffect shading style.
ReducedGlare | A constant equals to 2 to represent using reduced glare strength in ChartDirector.CFChart.glassEffect shading style.
NoGlare | A constant equals to 1 to represent disabling the glare in ChartDirector.CFChart.glassEffect shading style.
DashLine | A constant equals to 0505 (in hex) to represent a dash line pattern for use in dash colors.
DotLine | A constant equals to 0202 (in hex) to represent a dotted line pattern for use in dash colors.
DotDashLine | A constant equals to 05050205 (in hex) to represent a dot-dash line pattern for use in dash colors.
AltDashLine | A constant equals to 0A050505 (in hex) to represent a alternating long/short dash line pattern for use in dash colors.
goldGradient | A constant array of integers to represent a gradient that looks like a golden color.
silverGradient | A constant array of integers to represent a gradient that looks like a silver color.
redMetalGradient | A constant array of integers to represent a gradient that looks like a red metallic color.
blueMetalGradient | A constant array of integers to represent a gradient that looks like a blue metallic color.
greenMetalGradient | A constant array of integers to represent a gradient that looks like a green metallic color.
SquareShape | A constant equals to 1 to represent a square.
DiamondShape | A constant equals to 2 to represent a diamond shape.
TriangleShape | A constant equals to 3 to represent a triangle pointing upwards.
RightTriangleShape | A constant equals to 4 to represent a triangle pointing rightwards.
LeftTriangleShape | A constant equals to 5 to represent a triangle pointing leftwards.
InvertedTriangleShape | A constant equals to 6 to represent a triangle pointing downwards.
CircleShape | A constant equals to 7 to represent a circle.
DiamondPointer | A constant equals to 0 to represent the diamond style meter pointer.
TriangularPointer | A constant equals to 1 to represent the triangular style meter pointer.
ArrowPointer | A constant equals to 2 to represent the arrow style meter pointer.
ArrowPointer2 | A constant equals to 3 to represent the alternative arrow style meter pointer.
LinePointer | A constant equals to 4 to represent the line style meter pointer.
PencilPointer | A constant equals to 5 to represent the pencil style meter pointer.
PNG | A constant equals to 0 to represent the PNG image format.
GIF | A constant equals to 1 to represent the GIF image format.
JPG | A constant equals to 2 to represent the JPG image format.
BMP | A constant equals to 4 to represent the BMP image format.
WMP | A constant equals to 3 to represent the WAP bitmap image format.
NoAntiAlias | A constant equals to 0 to represent that text should be drawn without using anti-alias.
AntiAlias | A constant equals to 1 to represent that text should be drawn with anti-alias.
AutoAntiAlias | A constant equals to 2 to represent that text should be drawn with anti-alias if necessary based on font attributes.
TryPalette | A constant equals to 0 to represent that palette based image format should be used if the image contains 256 colors or less.
ForcePalette | A constant equals to 1 to represent that palette based image format should always be used (dither the image if necessary).
NoPalette | A constant equals to 2 to represent that true color image format should always be used.
Quantize | A constant equals to 0 to represent that the quantize dithering method should be used if dithering is required.
OrderedDither | A constant equals to 1 to represent that the ordered dithering method should be used if dithering is required.
ErrorDiffusion | A constant equals to 2 to represent that the error diffusion dithering method should be used if dithering is required.
SideLayout | A constant equals to 0 to represent the side label layout method for pie/donut charts.
CircleLayout | A constant equals to 1 to represent the circular label layout method for pie/donut charts.
Side | A constant equals to 3 to represent the "Side" data representation method for multiple data sets.
Stack | A constant equals to 1 to represent the "Stack" data representation method for multiple data sets.
Overlay | A constant equals to 0 to represent the "Overlay" data representation method for multiple data sets.
Percentage | A constant equals to 4 to represent the "Percentage" data representation method for multiple data sets.
LogTick | A constant equals to +1.6e308 to represent that the ticks in a log scale axis should be 1 - 2 - 5 - 10 style increments.
MinorTickOnly | A constant equals to -1.7e308 to represent that the label position should contain a minor tick only.
MicroTickOnly | A constant equals to -1.6e308 to represent that the label position should contain a micro tick only.
PixelScale | A constant equals to 0 to represent that the size is measured in pixels.
XAxisScale | A constant equals to 1 to represent that the size is measured using the x-axis scale.
YAxisScale | A constant equals to 2 to represent that the size is measured using y-axis scale.
AngularAxisScale | A constant equals to 1 to represent that the size is measured using the angular-axis scale.
RadialAxisScale | A constant equals to 2 to represent that the size is measured using the radial-axis scale.
XAxisAtOrigin | A constant equals to 1 to represent that the x-axis should intersect with the zero point of the y-axis if it exists on the chart.
YAxisAtOrigin | A constant equals to 2 to represent that the y-axis should intersect with the zero point of the x-axis if it exists on the chart.
XYAxisAtOrigin | A constant equals to 3 to represent that the x-axis and y-axis should intersect at the origin if it exists on the chart.
XAxisSymmetric | A constant equals to 1 to represent that the x-axis should be symmetrical about the origin.
XAxisSymmetricIfNeeded | A constant equals to 2 to represent that the x-axis should be symmetrical about the origin if the data contain both positive and negative values.
YAxisSymmetric | A constant equals to 4 to represent that the y-axis should be symmetrical about the origin.
YAxisSymmetricIfNeeded | A constant equals to 8 to represent that the y-axis should be symmetrical about the origin if the data contain both positive and negative values.
XYAxisSymmetric | A constant equals to 16 to represent that the the x-axis and y-axis should be symmetrical about the origin.
XYAxisSymmetricIfNeeded | A constant equals to 32 to represent that the x-axis and y-axis should be symmetrical about the origin if the data contain both positive and negative values.
NormalLegend | A constant equals to 0 to represent that the legend keys order should follow the creation order of the data sets.
ReverseLegend | A constant equals to 1 to represent that the legend keys order is the reverse of the creation order of the data sets.
NoLegend | A constant equals to 2 to represent that no legend keys should be added to the legend box.
AutoGrid | A constant equals to -2 to represent that the number of columns in the legend box with grid layout is automatically determine.
ChartBackZ | A constant equals to 100 (in hex) to represent the z-order of the back surface of the chart.
ChartFrontZ | A constant equals to ffff (in hex) to represent the z-order of the front surface of the chart.
PlotAreaZ | A constant equals to 1000 (in hex) to represent the z-order of the plot area back surface of the chart.
GridLinesZ | A constant equals to 2000 (in hex) to represent the z-order of the grid lines of the chart.
TouchBar | A constant equals to -1.7e-100 to represent that the bars in a bar layer should touch each others with no gap in between.
HLOCDefault | A constant equals to 0 to represent that the HLOC symbols should be drawn using the same color.
HLOCOpenClose | A constant equals to 1 to represent that the HLOC symbols should be drawn using two alternative colors based on whether the closing price is higher than the opening price.
HLOCUpDown | A constant equals to 2 to represent that the HLOC symbols should be drawn using two alternative colors based on whether the closing price is higher than the previous closing price.
AggregateSum | A constant equals to 0 to represent using the sum as the aggregated value in ArrayMath.aggregate.
AggregateAvg | A constant equals to 1 to represent using the average as the aggregated value in ArrayMath.aggregate.
AggregateStdDev | A constant equals to 2 to represent using the standard deviation as the aggregated value in ArrayMath.aggregate.
AggregateMin | A constant equals to 3 to represent using the minimum value as the aggregated value in ArrayMath.aggregate.
AggregateMed | A constant equals to 4 to represent using the median value as the aggregated value in ArrayMath.aggregate.
AggregateMax | A constant equals to 5 to represent using the maximum value as the aggregated value in ArrayMath.aggregate.
AggregatePercentile | A constant equals to 6 to represent using the percentile value as the aggregated value in ArrayMath.aggregate.
AggregateFirst | A constant equals to 7 to represent using the first value as the aggregated value in ArrayMath.aggregate.
AggregateLast | A constant equals to 8 to represent using the last value as the aggregated value in ArrayMath.aggregate.
AggregateCount | A constant equals to 9 to represent using the item count as the aggregated value in ArrayMath.aggregate.
BoxFilter | A constant equals to 0 to represent a Box graphical re-sampling filter.
LinearFilter | A constant equals to 1 to represent a Linear graphical re-sampling filter.
QuadraticFilter | A constant equals to 2 to represent a Quadratic graphical re-sampling filter.
BSplineFilter | A constant equals to 3 to represent a B-spline graphical re-sampling filter.
HermiteFilter | A constant equals to 4 to represent a Hermite graphical re-sampling filter.
CatromFilter | A constant equals to 5 to represent a Catrom graphical re-sampling filter.
MitchellFilter | A constant equals to 6 to represent a Mitchell graphical re-sampling filter.
SincFilter | A constant equals to 7 to represent a Sinc graphical re-sampling filter.
LanczosFilter | A constant equals to 8 to represent a Lanczos graphical re-sampling filter.
GaussianFilter | A constant equals to 9 to represent a Gaussian graphical re-sampling filter.
HanningFilter | A constant equals to 10 to represent a Hanning graphical re-sampling filter.
HammingFilter | A constant equals to 11 to represent a Hamming graphical re-sampling filter.
BlackmanFilter | A constant equals to 12 to represent a Blackman graphical re-sampling filter.
BesselFilter | A constant equals to 13 to represent a Bessel graphical re-sampling filter.
MouseUsageDefault | A constant equals to 0 to represent using the default mouse behaviour.
MouseUsageScroll | A constant equals to 2 to represent using the mouse for drag scrolling.
MouseUsageZoomIn | A constant equals to 3 to represent using the mouse for zoom in actions.
MouseUsageZoomOut | A constant equals to 4 to represent using the mouse for zoom out actions.
DirectionHorizontal | A constant equals to 0 to represent that the zoom and/or scroll orientation is horizontal.
DirectionVertical | A constant equals to 1 to represent that the zoom and/or scroll orientation is vertical.
DirectionHorizontalVertical | A constant equals to 2 to represent that the zoom and/or scroll orientation can be both horizontal and vertical.

Methods
Name | Description
PieChart | Creates a new PieChart object.
XYChart | Creates a new XYChart object.
PolarChart | Creates a new PolarChart object.
AngularMeter | Creates a new AngularMeter object.
LinearMeter | Creates a new LinearMeter object.
MultiChart | Creates a new MultiChart object.
FinanceChart | Creates a new FinanceChart object.
DrawArea | Creates a DrawArea object.
ArrayMath | Creates an ArrayMath object and initialize it with the given array.
RanTable | Creates a RanTable object.
FinanceSimulator | Creates a FinanceSimulator object.
WebChartViewer | Creates a new WebChartViewer object.
setLicenseCode | Sets the license code into ChartDirector.
getVersion | Gets ChartDirector version information.
getBootLog | A diagnostic function to obtain the ChartDirector boot log.
testFont | A diagnostic function to perform a font loading test.
chartTime | Obtain the second elapsed since 01-01-0001 00:00:00 to the given time, which is the date/time format used by ChartDirector.
chartTime2 | Converts a UNIX time (seconds elapsed since 01-01-1970 00:00:00 GMT) to the date/time format used by ChartDirector.
getChartYMD | Gets the year, month and day represented by a ChartDirector date/time.
getChartWeekDay | Gets the weekday represented by a ChartDirector date/time.
CTime | Converts a ColdFusion date to ChartDirector's date/time format.
CTime2 | Converts an array of ColdFusion date objects to ChartDirector's date/time format.
NTime | Converts a date/time in ChartDirector's date/time format to a ColdFusion date object.
NTime2 | Converts an array of dates/times in ChartDirector's date/time format to ColdFusion date objects.
goldColor | Creates a golden color, most commonly used as a background color.
silverColor | Creates a silver color, most commonly used as a background color.
metalColor | Creates a color by modulates the brightness of another color to create metallic shiny effects.
glassEffect | A complex shading effect that emulates tinted glass or semi-transparent plastic material.
softLighting | A special shading effect that looks like gradient coloring.
PolygonShape | Gets the shape id that represents a polygon.
Polygon2Shape | Gets the shape id that represents a polygon in an alternative orientation.
StarShape | Gets the shape id that represents a star shape.
CrossShape | Gets the shape id that represents a '+' shape.
Cross2Shape | Gets the shape id that represents a 'X' shape.
StartOfHourFilter | Creates a data filter that matches date/times that represent the start of a new hour in a date/time series.
StartOfDayFilter | Creates a data filter that matches date/times that represent the start of a new day in a date/time series.
StartOfWeekFilter | Creates a data filter that matches date/times that represent the start of a new week in a date/time series.
StartOfMonthFilter | Creates a data filter that matches date/times that represent the start of a new month in a date/time series.
StartOfYearFilter | Creates a data filter that matches date/times that represent the start of a new year in a date/time series.
RegularSpacingFilter | Creates a data filter that matches 1 out of every N elements.
AllPassFilter | Creates a data filter that matches every element.
NonePassFilter | Creates a data filter that matches no element.
SelectItemFilter | Creates a data filter that matches the specified item.


ChartDirector.CFChart.NoValue

ChartDirector.CFChart.NoValue

Description

A constant equals to 1.7E+308 to represent missing values in ChartDirector.

Please refer to No Value Specification for more details.


ChartDirector.CFChart.BottomLeft

ChartDirector.CFChart.BottomLeft

Description

A constant equals to 1 to represent the bottom left position.

See Alignment Specification for supported alignment types.


ChartDirector.CFChart.BottomLeft2

ChartDirector.CFChart.BottomLeft2

Description

A constant equals to 12 to represent the alternative exterior bottom left position.

See Alignment Specification for supported alignment types.


ChartDirector.CFChart.BottomCenter

ChartDirector.CFChart.BottomCenter

Description

A constant equals to 2 to represent the bottom center position.

See Alignment Specification for supported alignment types.


ChartDirector.CFChart.BottomRight

ChartDirector.CFChart.BottomRight

Description

A constant equals to 3 to represent the bottom right position.

See Alignment Specification for supported alignment types.


ChartDirector.CFChart.BottomRight2

ChartDirector.CFChart.BottomRight2

Description

A constant equals to 13 to represent the alternative exterior bottom right position.

See Alignment Specification for supported alignment types.


ChartDirector.CFChart.Left

ChartDirector.CFChart.Left

Description

A constant equals to 4 to represent the left position.

See Alignment Specification for supported alignment types.


ChartDirector.CFChart.Center

ChartDirector.CFChart.Center

Description

A constant equals to 5 to represent the center position.

See Alignment Specification for supported alignment types.


ChartDirector.CFChart.Right

ChartDirector.CFChart.Right

Description

A constant equals to 6 to represent the right position.

See Alignment Specification for supported alignment types.


ChartDirector.CFChart.TopLeft

ChartDirector.CFChart.TopLeft

Description

A constant equals to 7 to represent the top left position.

See Alignment Specification for supported alignment types.


ChartDirector.CFChart.TopLeft2

ChartDirector.CFChart.TopLeft2

Description

A constant equals to 10 to represent the alternative exterior top left position.

See Alignment Specification for supported alignment types.


ChartDirector.CFChart.TopCenter

ChartDirector.CFChart.TopCenter

Description

A constant equals to 8 to represent the top center position.

See Alignment Specification for supported alignment types.


ChartDirector.CFChart.TopRight

ChartDirector.CFChart.TopRight

Description

A constant equals to 9 to represent the top right position.

See Alignment Specification for supported alignment types.


ChartDirector.CFChart.TopRight2

ChartDirector.CFChart.TopRight2

Description

A constant equals to 11 to represent the alternative exterior top right position.

See Alignment Specification for supported alignment types.


ChartDirector.CFChart.Bottom

ChartDirector.CFChart.Bottom

Description

A constant equals to 2 to represent the bottom position.

See Alignment Specification for supported alignment types.


ChartDirector.CFChart.Top

ChartDirector.CFChart.Top

Description

A constant equals to 8 to represent the top position.

See Alignment Specification for supported alignment types.


ChartDirector.CFChart.Transparent

ChartDirector.CFChart.Transparent

Description

A constant equals to FF000000 (in hex) to represent the transparent color.

See Color Specification on how colors are represented in ChartDirector.


ChartDirector.CFChart.BackgroundColor

ChartDirector.CFChart.BackgroundColor

Description

A constant equals to FFFF0000 (in hex) to represent the background color.

See Color Specification on how colors are represented in ChartDirector.


ChartDirector.CFChart.LineColor

ChartDirector.CFChart.LineColor

Description

A constant equals to FFFF0001 (in hex) to represent the default line color.

See Color Specification on how colors are represented in ChartDirector.


ChartDirector.CFChart.TextColor

ChartDirector.CFChart.TextColor

Description

A constant equals to FFFF0002 (in hex) to represent the default text color.

See Color Specification on how colors are represented in ChartDirector.


ChartDirector.CFChart.SameAsMainColor

ChartDirector.CFChart.SameAsMainColor

Description

A constant equals to FFFF0007 (in hex) to represent the current main color.

See Color Specification on how colors are represented in ChartDirector.


ChartDirector.CFChart.Palette

ChartDirector.CFChart.Palette

Description

A constant equals to FFFF0000 (in hex) to represent the starting index of the color palette.

See Color Specification on how colors are represented in ChartDirector.


ChartDirector.CFChart.DataColor

ChartDirector.CFChart.DataColor

Description

A constant equals to FFFF0008 (in hex) to represent the starting index of automatic data color.

See Color Specification on how colors are represented in ChartDirector.


ChartDirector.CFChart.defaultPalette

ChartDirector.CFChart.defaultPalette

Description

A constant array of integers to represent the default palette.

The array is in a format that can be directly used in BaseChart.setColors and DrawArea.setColorTable.

See Color Specification on how colors are represented in ChartDirector.


ChartDirector.CFChart.whiteOnBlackPalette

ChartDirector.CFChart.whiteOnBlackPalette

Description

A constant array of integers to represent the white on black palette.

The array is in a format that can be directly used in BaseChart.setColors and DrawArea.setColorTable.

See Color Specification on how colors are represented in ChartDirector.


ChartDirector.CFChart.transparentPalette

ChartDirector.CFChart.transparentPalette

Description

A constant array of integers to represent the semi-transparent palette.

The array is in a format that can be directly used in BaseChart.setColors and DrawArea.setColorTable.

See Color Specification on how colors are represented in ChartDirector.


ChartDirector.CFChart.NormalGlare

ChartDirector.CFChart.NormalGlare

Description

A constant equals to 3 to represent using normal glare strength in ChartDirector.CFChart.glassEffect shading style.


ChartDirector.CFChart.ReducedGlare

ChartDirector.CFChart.ReducedGlare

Description

A constant equals to 2 to represent using reduced glare strength in ChartDirector.CFChart.glassEffect shading style.


ChartDirector.CFChart.NoGlare

ChartDirector.CFChart.NoGlare

Description

A constant equals to 1 to represent disabling the glare in ChartDirector.CFChart.glassEffect shading style.


ChartDirector.CFChart.DashLine

ChartDirector.CFChart.DashLine

Description

A constant equals to 0505 (in hex) to represent a dash line pattern for use in dash colors.

See Color Specification on how colors are represented in ChartDirector.


ChartDirector.CFChart.DotLine

ChartDirector.CFChart.DotLine

Description

A constant equals to 0202 (in hex) to represent a dotted line pattern for use in dash colors.

See Color Specification on how colors are represented in ChartDirector.


ChartDirector.CFChart.DotDashLine

ChartDirector.CFChart.DotDashLine

Description

A constant equals to 05050205 (in hex) to represent a dot-dash line pattern for use in dash colors.

See Color Specification on how colors are represented in ChartDirector.


ChartDirector.CFChart.AltDashLine

ChartDirector.CFChart.AltDashLine

Description

A constant equals to 0A050505 (in hex) to represent a alternating long/short dash line pattern for use in dash colors.

See Color Specification on how colors are represented in ChartDirector.


ChartDirector.CFChart.goldGradient

ChartDirector.CFChart.goldGradient

Description

A constant array of integers to represent a gradient that looks like a golden color.

The array is in a format that can be directly used in BaseChart.gradientColor2 and DrawArea.gradientColor2. Its contents (in hex) is:

00 FFE743 60 FFFFE0 B0 FFF0B0 100 FFE743

See Color Specification on how colors are represented in ChartDirector.


ChartDirector.CFChart.silverGradient

ChartDirector.CFChart.silverGradient

Description

A constant array of integers to represent a gradient that looks like a silver color.

The array is in a format that can be directly used in BaseChart.gradientColor2 and DrawArea.gradientColor2. Its contents (in hex) is:

00 C8C8C8 60 F8F8F8 B0 E0E0E0 100 C8C8C8

See Color Specification on how colors are represented in ChartDirector.


ChartDirector.CFChart.redMetalGradient

ChartDirector.CFChart.redMetalGradient

Description

A constant array of integers to represent a gradient that looks like a red metallic color.

The array is in a format that can be directly used in BaseChart.gradientColor2 and DrawArea.gradientColor2. Its contents (in hex) is:

00 E09898 60 FFF0F0 B0 F0D8D8 100 E09898

See Color Specification on how colors are represented in ChartDirector.


ChartDirector.CFChart.blueMetalGradient

ChartDirector.CFChart.blueMetalGradient

Description

A constant array of integers to represent a gradient that looks like a blue metallic color.

The array is in a format that can be directly used in BaseChart.gradientColor2 and DrawArea.gradientColor2. Its contents (in hex) is:

00 9898E0 60 F0F0FF B0 D8D8F0 100 9898E0

See Color Specification on how colors are represented in ChartDirector.


ChartDirector.CFChart.greenMetalGradient

ChartDirector.CFChart.greenMetalGradient

Description

A constant array of integers to represent a gradient that looks like a green metallic color.

The array is in a format that can be directly used in BaseChart.gradientColor2 and DrawArea.gradientColor2. Its contents (in hex) is:

00 98E098 60 F0FFF0 B0 D8F0D8 100 98E098

See Color Specification on how colors are represented in ChartDirector.


ChartDirector.CFChart.SquareShape

ChartDirector.CFChart.SquareShape

Description

A constant equals to 1 to represent a square.

Please refer to Shape Specification for samples and more information on using shapes in ChartDirector.


ChartDirector.CFChart.DiamondShape

ChartDirector.CFChart.DiamondShape

Description

A constant equals to 2 to represent a diamond shape.

Please refer to Shape Specification for samples and more information on using shapes in ChartDirector.


ChartDirector.CFChart.TriangleShape

ChartDirector.CFChart.TriangleShape

Description

A constant equals to 3 to represent a triangle pointing upwards.

Please refer to Shape Specification for samples and more information on using shapes in ChartDirector.


ChartDirector.CFChart.RightTriangleShape

ChartDirector.CFChart.RightTriangleShape

Description

A constant equals to 4 to represent a triangle pointing rightwards.

Please refer to Shape Specification for samples and more information on using shapes in ChartDirector.


ChartDirector.CFChart.LeftTriangleShape

ChartDirector.CFChart.LeftTriangleShape

Description

A constant equals to 5 to represent a triangle pointing leftwards.

Please refer to Shape Specification for samples and more information on using shapes in ChartDirector.


ChartDirector.CFChart.InvertedTriangleShape

ChartDirector.CFChart.InvertedTriangleShape

Description

A constant equals to 6 to represent a triangle pointing downwards.

Please refer to Shape Specification for samples and more information on using shapes in ChartDirector.


ChartDirector.CFChart.CircleShape

ChartDirector.CFChart.CircleShape

Description

A constant equals to 7 to represent a circle.

Please refer to Shape Specification for samples and more information on using shapes in ChartDirector.


ChartDirector.CFChart.DiamondPointer

ChartDirector.CFChart.DiamondPointer

Description

A constant equals to 0 to represent the diamond style meter pointer.

This constant is used in MeterPointer.setShape.


ChartDirector.CFChart.TriangularPointer

ChartDirector.CFChart.TriangularPointer

Description

A constant equals to 1 to represent the triangular style meter pointer.

This constant is used in MeterPointer.setShape.


ChartDirector.CFChart.ArrowPointer

ChartDirector.CFChart.ArrowPointer

Description

A constant equals to 2 to represent the arrow style meter pointer.

This constant is used in MeterPointer.setShape.


ChartDirector.CFChart.ArrowPointer2

ChartDirector.CFChart.ArrowPointer2

Description

A constant equals to 3 to represent the alternative arrow style meter pointer.

This constant is used in MeterPointer.setShape.


ChartDirector.CFChart.LinePointer

ChartDirector.CFChart.LinePointer

Description

A constant equals to 4 to represent the line style meter pointer.

This constant is used in MeterPointer.setShape.


ChartDirector.CFChart.PencilPointer

ChartDirector.CFChart.PencilPointer

Description

A constant equals to 5 to represent the pencil style meter pointer.

This constant is used in MeterPointer.setShape.


ChartDirector.CFChart.PNG

ChartDirector.CFChart.PNG

Description

A constant equals to 0 to represent the PNG image format.


ChartDirector.CFChart.GIF

ChartDirector.CFChart.GIF

Description

A constant equals to 1 to represent the GIF image format.


ChartDirector.CFChart.JPG

ChartDirector.CFChart.JPG

Description

A constant equals to 2 to represent the JPG image format.


ChartDirector.CFChart.BMP

ChartDirector.CFChart.BMP

Description

A constant equals to 4 to represent the BMP image format.


ChartDirector.CFChart.WMP

ChartDirector.CFChart.WMP

Description

A constant equals to 3 to represent the WAP bitmap image format.


ChartDirector.CFChart.NoAntiAlias

ChartDirector.CFChart.NoAntiAlias

Description

A constant equals to 0 to represent that text should be drawn without using anti-alias.

This constant is used in BaseChart.setAntiAlias and DrawArea.setAntiAlias.


ChartDirector.CFChart.AntiAlias

ChartDirector.CFChart.AntiAlias

Description

A constant equals to 1 to represent that text should be drawn with anti-alias.

This constant is used in BaseChart.setAntiAlias and DrawArea.setAntiAlias.


ChartDirector.CFChart.AutoAntiAlias

ChartDirector.CFChart.AutoAntiAlias

Description

A constant equals to 2 to represent that text should be drawn with anti-alias if necessary based on font attributes.

This constant is used in BaseChart.setAntiAlias and DrawArea.setAntiAlias.


ChartDirector.CFChart.TryPalette

ChartDirector.CFChart.TryPalette

Description

A constant equals to 0 to represent that palette based image format should be used if the image contains 256 colors or less.

This constant is used in DrawArea.setPaletteMode.


ChartDirector.CFChart.ForcePalette

ChartDirector.CFChart.ForcePalette

Description

A constant equals to 1 to represent that palette based image format should always be used (dither the image if necessary).

This constant is used in DrawArea.setPaletteMode.


ChartDirector.CFChart.NoPalette

ChartDirector.CFChart.NoPalette

Description

A constant equals to 2 to represent that true color image format should always be used.

This constant is used in DrawArea.setPaletteMode.


ChartDirector.CFChart.Quantize

ChartDirector.CFChart.Quantize

Description

A constant equals to 0 to represent that the quantize dithering method should be used if dithering is required.

This constant is used in DrawArea.setDitherMethod.


ChartDirector.CFChart.OrderedDither

ChartDirector.CFChart.OrderedDither

Description

A constant equals to 1 to represent that the ordered dithering method should be used if dithering is required.

This constant is used in DrawArea.setDitherMethod.


ChartDirector.CFChart.ErrorDiffusion

ChartDirector.CFChart.ErrorDiffusion

Description

A constant equals to 2 to represent that the error diffusion dithering method should be used if dithering is required.

This constant is used in DrawArea.setDitherMethod.


ChartDirector.CFChart.SideLayout

ChartDirector.CFChart.SideLayout

Description

A constant equals to 0 to represent the side label layout method for pie/donut charts.

This constant is used in PieChart.setLabelLayout.


ChartDirector.CFChart.CircleLayout

ChartDirector.CFChart.CircleLayout

Description

A constant equals to 1 to represent the circular label layout method for pie/donut charts.

This constant is used in PieChart.setLabelLayout.


ChartDirector.CFChart.Side

ChartDirector.CFChart.Side

Description

A constant equals to 3 to represent the "Side" data representation method for multiple data sets.

This constant is used in XYChart.addBarLayer2, XYChart.addAreaLayer2 and Layer.setDataCombineMethod.


ChartDirector.CFChart.Stack

ChartDirector.CFChart.Stack

Description

A constant equals to 1 to represent the "Stack" data representation method for multiple data sets.

This constant is used in XYChart.addBarLayer2, XYChart.addAreaLayer2 and Layer.setDataCombineMethod.


ChartDirector.CFChart.Overlay

ChartDirector.CFChart.Overlay

Description

A constant equals to 0 to represent the "Overlay" data representation method for multiple data sets.

This constant is used in XYChart.addBarLayer2, XYChart.addAreaLayer2 and Layer.setDataCombineMethod.


ChartDirector.CFChart.Percentage

ChartDirector.CFChart.Percentage

Description

A constant equals to 4 to represent the "Percentage" data representation method for multiple data sets.

This constant is used in XYChart.addBarLayer2, XYChart.addAreaLayer2 and Layer.setDataCombineMethod.


ChartDirector.CFChart.LogTick

ChartDirector.CFChart.LogTick

Description

A constant equals to +1.6e308 to represent that the ticks in a log scale axis should be 1 - 2 - 5 - 10 style increments.

This constant is used in Axis.setLogScale.


ChartDirector.CFChart.MinorTickOnly

ChartDirector.CFChart.MinorTickOnly

Description

A constant equals to -1.7e308 to represent that the label position should contain a minor tick only.

This constant is used in Axis.setLabels2 .


ChartDirector.CFChart.MicroTickOnly

ChartDirector.CFChart.MicroTickOnly

Description

A constant equals to -1.6e308 to represent that the label position should contain a micro tick only.

This constant is used in Axis.setLabels2 and BaseMeter.setScale3.


ChartDirector.CFChart.PixelScale

ChartDirector.CFChart.PixelScale

Description

A constant equals to 0 to represent that the size is measured in pixels.

This constant is used in LineLayer.setSymbolScale, PolarLayer.setSymbolScale, XYChart.addVectorLayer, PolarChart.addVectorLayer, VectorLayer.setVector and PolarVectorLayer.setVector.


ChartDirector.CFChart.XAxisScale

ChartDirector.CFChart.XAxisScale

Description

A constant equals to 1 to represent that the size is measured using the x-axis scale.

This constant is used in LineLayer.setSymbolScale, XYChart.addVectorLayer and VectorLayer.setVector.


ChartDirector.CFChart.YAxisScale

ChartDirector.CFChart.YAxisScale

Description

A constant equals to 2 to represent that the size is measured using y-axis scale.

This constant is used in LineLayer.setSymbolScale, XYChart.addVectorLayer and VectorLayer.setVector.


ChartDirector.CFChart.AngularAxisScale

ChartDirector.CFChart.AngularAxisScale

Description

A constant equals to 1 to represent that the size is measured using the angular-axis scale.

This constant is used in PolarLayer.setSymbolScale.


ChartDirector.CFChart.RadialAxisScale

ChartDirector.CFChart.RadialAxisScale

Description

A constant equals to 2 to represent that the size is measured using the radial-axis scale.

This constant is used in PolarLayer.setSymbolScale, PolarChart.addVectorLayer and PolarVectorLayer.setVector.


ChartDirector.CFChart.XAxisAtOrigin

ChartDirector.CFChart.XAxisAtOrigin

Description

A constant equals to 1 to represent that the x-axis should intersect with the zero point of the y-axis if it exists on the chart.

This constant is used in XYChart.setAxisAtOrigin.


ChartDirector.CFChart.YAxisAtOrigin

ChartDirector.CFChart.YAxisAtOrigin

Description

A constant equals to 2 to represent that the y-axis should intersect with the zero point of the x-axis if it exists on the chart.

This constant is used in XYChart.setAxisAtOrigin.


ChartDirector.CFChart.XYAxisAtOrigin

ChartDirector.CFChart.XYAxisAtOrigin

Description

A constant equals to 3 to represent that the x-axis and y-axis should intersect at the origin if it exists on the chart.

This constant is used in XYChart.setAxisAtOrigin.


ChartDirector.CFChart.XAxisSymmetric

ChartDirector.CFChart.XAxisSymmetric

Description

A constant equals to 1 to represent that the x-axis should be symmetrical about the origin.

This constant is used in XYChart.setAxisAtOrigin.


ChartDirector.CFChart.XAxisSymmetricIfNeeded

ChartDirector.CFChart.XAxisSymmetricIfNeeded

Description

A constant equals to 2 to represent that the x-axis should be symmetrical about the origin if the data contain both positive and negative values.

This constant is used in XYChart.setAxisAtOrigin.


ChartDirector.CFChart.YAxisSymmetric

ChartDirector.CFChart.YAxisSymmetric

Description

A constant equals to 4 to represent that the y-axis should be symmetrical about the origin.

This constant is used in XYChart.setAxisAtOrigin.


ChartDirector.CFChart.YAxisSymmetricIfNeeded

ChartDirector.CFChart.YAxisSymmetricIfNeeded

Description

A constant equals to 8 to represent that the y-axis should be symmetrical about the origin if the data contain both positive and negative values.

This constant is used in XYChart.setAxisAtOrigin.


ChartDirector.CFChart.XYAxisSymmetric

ChartDirector.CFChart.XYAxisSymmetric

Description

A constant equals to 16 to represent that the the x-axis and y-axis should be symmetrical about the origin.

This constant is used in XYChart.setAxisAtOrigin.


ChartDirector.CFChart.XYAxisSymmetricIfNeeded

ChartDirector.CFChart.XYAxisSymmetricIfNeeded

Description

A constant equals to 32 to represent that the x-axis and y-axis should be symmetrical about the origin if the data contain both positive and negative values.

This constant is used in XYChart.setAxisAtOrigin.


ChartDirector.CFChart.NormalLegend

ChartDirector.CFChart.NormalLegend

Description

A constant equals to 0 to represent that the legend keys order should follow the creation order of the data sets.

This constant is used in Layer.setLegendOrder.


ChartDirector.CFChart.ReverseLegend

ChartDirector.CFChart.ReverseLegend

Description

A constant equals to 1 to represent that the legend keys order is the reverse of the creation order of the data sets.

This constant is used in Layer.setLegendOrder.


ChartDirector.CFChart.NoLegend

ChartDirector.CFChart.NoLegend

Description

A constant equals to 2 to represent that no legend keys should be added to the legend box.

This constant is used in Layer.setLegendOrder.


ChartDirector.CFChart.AutoGrid

ChartDirector.CFChart.AutoGrid

Description

A constant equals to -2 to represent that the number of columns in the legend box with grid layout is automatically determine.

This constant is used in BaseChart.addLegend2 and LegendBox.setCols.


ChartDirector.CFChart.ChartBackZ

ChartDirector.CFChart.ChartBackZ

Description

A constant equals to 100 (in hex) to represent the z-order of the back surface of the chart.

This constant is used in Box.setZOrder, Line.setZOrder and MeterPointer.setZOrder.


ChartDirector.CFChart.ChartFrontZ

ChartDirector.CFChart.ChartFrontZ

Description

A constant equals to ffff (in hex) to represent the z-order of the front surface of the chart.

This constant is used in Box.setZOrder, Line.setZOrder and MeterPointer.setZOrder.


ChartDirector.CFChart.PlotAreaZ

ChartDirector.CFChart.PlotAreaZ

Description

A constant equals to 1000 (in hex) to represent the z-order of the plot area back surface of the chart.

This constant is used in Box.setZOrder, Line.setZOrder and MeterPointer.setZOrder.


ChartDirector.CFChart.GridLinesZ

ChartDirector.CFChart.GridLinesZ

Description

A constant equals to 2000 (in hex) to represent the z-order of the grid lines of the chart.

This constant is used in Box.setZOrder, Line.setZOrder and MeterPointer.setZOrder.


ChartDirector.CFChart.TouchBar

ChartDirector.CFChart.TouchBar

Description

A constant equals to -1.7e-100 to represent that the bars in a bar layer should touch each others with no gap in between.

This constant is used in BarLayer.setBarGap.


ChartDirector.CFChart.HLOCDefault

ChartDirector.CFChart.HLOCDefault

Description

A constant equals to 0 to represent that the HLOC symbols should be drawn using the same color.

This constant is used in XYChart.addHLOCLayer3 and HLOCLayer.setColorMethod.


ChartDirector.CFChart.HLOCOpenClose

ChartDirector.CFChart.HLOCOpenClose

Description

A constant equals to 1 to represent that the HLOC symbols should be drawn using two alternative colors based on whether the closing price is higher than the opening price.

This constant is used in XYChart.addHLOCLayer3 and HLOCLayer.setColorMethod.


ChartDirector.CFChart.HLOCUpDown

ChartDirector.CFChart.HLOCUpDown

Description

A constant equals to 2 to represent that the HLOC symbols should be drawn using two alternative colors based on whether the closing price is higher than the previous closing price.

This constant is used in XYChart.addHLOCLayer3 and HLOCLayer.setColorMethod.


ChartDirector.CFChart.AggregateSum

ChartDirector.CFChart.AggregateSum

Description

A constant equals to 0 to represent using the sum as the aggregated value in ArrayMath.aggregate.


ChartDirector.CFChart.AggregateAvg

ChartDirector.CFChart.AggregateAvg

Description

A constant equals to 1 to represent using the average as the aggregated value in ArrayMath.aggregate.


ChartDirector.CFChart.AggregateStdDev

ChartDirector.CFChart.AggregateStdDev

Description

A constant equals to 2 to represent using the standard deviation as the aggregated value in ArrayMath.aggregate.


ChartDirector.CFChart.AggregateMin

ChartDirector.CFChart.AggregateMin

Description

A constant equals to 3 to represent using the minimum value as the aggregated value in ArrayMath.aggregate.


ChartDirector.CFChart.AggregateMed

ChartDirector.CFChart.AggregateMed

Description

A constant equals to 4 to represent using the median value as the aggregated value in ArrayMath.aggregate.


ChartDirector.CFChart.AggregateMax

ChartDirector.CFChart.AggregateMax

Description

A constant equals to 5 to represent using the maximum value as the aggregated value in ArrayMath.aggregate.


ChartDirector.CFChart.AggregatePercentile

ChartDirector.CFChart.AggregatePercentile

Description

A constant equals to 6 to represent using the percentile value as the aggregated value in ArrayMath.aggregate.


ChartDirector.CFChart.AggregateFirst

ChartDirector.CFChart.AggregateFirst

Description

A constant equals to 7 to represent using the first value as the aggregated value in ArrayMath.aggregate.


ChartDirector.CFChart.AggregateLast

ChartDirector.CFChart.AggregateLast

Description

A constant equals to 8 to represent using the last value as the aggregated value in ArrayMath.aggregate.


ChartDirector.CFChart.AggregateCount

ChartDirector.CFChart.AggregateCount

Description

A constant equals to 9 to represent using the item count as the aggregated value in ArrayMath.aggregate.


ChartDirector.CFChart.BoxFilter

ChartDirector.CFChart.BoxFilter

Description

A constant equals to 0 to represent a Box graphical re-sampling filter.

Please refer to Re-Sampling Filters for more information graphical filters in ChartDirector.


ChartDirector.CFChart.LinearFilter

ChartDirector.CFChart.LinearFilter

Description

A constant equals to 1 to represent a Linear graphical re-sampling filter.

Please refer to Re-Sampling Filters for more information graphical filters in ChartDirector.


ChartDirector.CFChart.QuadraticFilter

ChartDirector.CFChart.QuadraticFilter

Description

A constant equals to 2 to represent a Quadratic graphical re-sampling filter.

Please refer to Re-Sampling Filters for more information graphical filters in ChartDirector.


ChartDirector.CFChart.BSplineFilter

ChartDirector.CFChart.BSplineFilter

Description

A constant equals to 3 to represent a B-spline graphical re-sampling filter.

Please refer to Re-Sampling Filters for more information graphical filters in ChartDirector.


ChartDirector.CFChart.HermiteFilter

ChartDirector.CFChart.HermiteFilter

Description

A constant equals to 4 to represent a Hermite graphical re-sampling filter.

Please refer to Re-Sampling Filters for more information graphical filters in ChartDirector.


ChartDirector.CFChart.CatromFilter

ChartDirector.CFChart.CatromFilter

Description

A constant equals to 5 to represent a Catrom graphical re-sampling filter.

Please refer to Re-Sampling Filters for more information graphical filters in ChartDirector.


ChartDirector.CFChart.MitchellFilter

ChartDirector.CFChart.MitchellFilter

Description

A constant equals to 6 to represent a Mitchell graphical re-sampling filter.

Please refer to Re-Sampling Filters for more information graphical filters in ChartDirector.


ChartDirector.CFChart.SincFilter

ChartDirector.CFChart.SincFilter

Description

A constant equals to 7 to represent a Sinc graphical re-sampling filter.

Please refer to Re-Sampling Filters for more information graphical filters in ChartDirector.


ChartDirector.CFChart.LanczosFilter

ChartDirector.CFChart.LanczosFilter

Description

A constant equals to 8 to represent a Lanczos graphical re-sampling filter.

Please refer to Re-Sampling Filters for more information graphical filters in ChartDirector.


ChartDirector.CFChart.GaussianFilter

ChartDirector.CFChart.GaussianFilter

Description

A constant equals to 9 to represent a Gaussian graphical re-sampling filter.

Please refer to Re-Sampling Filters for more information graphical filters in ChartDirector.


ChartDirector.CFChart.HanningFilter

ChartDirector.CFChart.HanningFilter

Description

A constant equals to 10 to represent a Hanning graphical re-sampling filter.

Please refer to Re-Sampling Filters for more information graphical filters in ChartDirector.


ChartDirector.CFChart.HammingFilter

ChartDirector.CFChart.HammingFilter

Description

A constant equals to 11 to represent a Hamming graphical re-sampling filter.

Please refer to Re-Sampling Filters for more information graphical filters in ChartDirector.


ChartDirector.CFChart.BlackmanFilter

ChartDirector.CFChart.BlackmanFilter

Description

A constant equals to 12 to represent a Blackman graphical re-sampling filter.

Please refer to Re-Sampling Filters for more information graphical filters in ChartDirector.


ChartDirector.CFChart.BesselFilter

ChartDirector.CFChart.BesselFilter

Description

A constant equals to 13 to represent a Bessel graphical re-sampling filter.

Please refer to Re-Sampling Filters for more information graphical filters in ChartDirector.


ChartDirector.CFChart.MouseUsageDefault

ChartDirector.CFChart.MouseUsageDefault

Description

A constant equals to 0 to represent using the default mouse behaviour.

This constant is used in .


ChartDirector.CFChart.MouseUsageScroll

ChartDirector.CFChart.MouseUsageScroll

Description

A constant equals to 2 to represent using the mouse for drag scrolling.

This constant is used in .


ChartDirector.CFChart.MouseUsageZoomIn

ChartDirector.CFChart.MouseUsageZoomIn

Description

A constant equals to 3 to represent using the mouse for zoom in actions.

This constant is used in .


ChartDirector.CFChart.MouseUsageZoomOut

ChartDirector.CFChart.MouseUsageZoomOut

Description

A constant equals to 4 to represent using the mouse for zoom out actions.

This constant is used in .


ChartDirector.CFChart.DirectionHorizontal

ChartDirector.CFChart.DirectionHorizontal

Description

A constant equals to 0 to represent that the zoom and/or scroll orientation is horizontal.

This constant is used in .


ChartDirector.CFChart.DirectionVertical

ChartDirector.CFChart.DirectionVertical

Description

A constant equals to 1 to represent that the zoom and/or scroll orientation is vertical.

This constant is used in .


ChartDirector.CFChart.DirectionHorizontalVertical

ChartDirector.CFChart.DirectionHorizontalVertical

Description

A constant equals to 2 to represent that the zoom and/or scroll orientation can be both horizontal and vertical.

This constant is used in .


ChartDirector.CFChart.PieChart

ChartDirector.CFChart.PieChart

Usage

PieChart(width, height [, bgColor [, edgeColor [, raisedEffect ]]])

Description

Creates a new PieChart object.

Arguments

Argument | Default | Description
width | (Mandatory) | The width of the chart in pixels.
height | (Mandatory) | The height of the chart in pixels.
bgColor | BackgroundColor | The background color of the chart.
edgeColor | Transparent | The edge color of the chart.
raisedEffect | 0 | The 3D border width. For positive values, the border will appear raised. For negative values, the border will appear depressed. A zero value means the border will appear flat.

Return Value

The PieChart object created.


ChartDirector.CFChart.XYChart

ChartDirector.CFChart.XYChart

Usage

XYChart(width, height [, bgColor [, edgeColor [, raisedEffect ]]])

Description

Creates a new XYChart object.

Arguments

Argument | Default | Description
width | (Mandatory) | The width of the chart in pixels.
height | (Mandatory) | The height of the chart in pixels.
bgColor | BackgroundColor | The background color of the chart.
edgeColor | Transparent | The edge color of the chart.
raisedEffect | 0 | The 3D border width. For positive values, the border will appear raised. For negative values, the border will appear depressed. A zero value means the border will appear flat.

Return Value

The XYChart object created.


ChartDirector.CFChart.PolarChart

ChartDirector.CFChart.PolarChart

Usage

PolarChart(width, height [, bgColor [, edgeColor [, raisedEffect ]]])

Description

Creates a new PolarChart object.

Arguments

Argument | Default | Description
width | (Mandatory) | The width of the chart in pixels.
height | (Mandatory) | The height of the chart in pixels.
bgColor | BackgroundColor | The background color of the chart.
edgeColor | Transparent | The edge color of the chart.
raisedEffect | 0 | The 3D border width. For positive values, the border will appear raised. For negative values, the border will appear depressed. A zero value means the border will appear flat.

Return Value

The PolarChart object created.


ChartDirector.CFChart.AngularMeter

ChartDirector.CFChart.AngularMeter

Usage

AngularMeter(width, height [, bgColor [, edgeColor [, raisedEffect ]]])

Description

Creates a new AngularMeter object.

Arguments

Argument | Default | Description
width | (Mandatory) | The width of the chart in pixels.
height | (Mandatory) | The height of the chart in pixels.
bgColor | BackgroundColor | The background color of the chart.
edgeColor | Transparent | The edge color of the chart.
raisedEffect | 0 | The 3D border width. For positive values, the border will appear raised. For negative values, the border will appear depressed. A zero value means the border will appear flat.

Return Value

The AngularMeter object created.


ChartDirector.CFChart.LinearMeter

ChartDirector.CFChart.LinearMeter

Usage

LinearMeter(width, height [, bgColor [, edgeColor [, raisedEffect ]]])

Description

Creates a new LinearMeter object.

Arguments

Argument | Default | Description
width | (Mandatory) | The width of the chart in pixels.
height | (Mandatory) | The height of the chart in pixels.
bgColor | BackgroundColor | The background color of the chart.
edgeColor | Transparent | The edge color of the chart.
raisedEffect | 0 | The 3D border width. For positive values, the border will appear raised. For negative values, the border will appear depressed. A zero value means the border will appear flat.

Return Value

The LinearMeter object created.


ChartDirector.CFChart.MultiChart

ChartDirector.CFChart.MultiChart

Usage

MultiChart(width, height [, bgColor [, edgeColor [, raisedEffect ]]])

Description

Creates a new MultiChart object.

Arguments

Argument | Default | Description
width | (Mandatory) | The width of the chart in pixels.
height | (Mandatory) | The height of the chart in pixels.
bgColor | BackgroundColor | The background color of the chart.
edgeColor | Transparent | The edge color of the chart.
raisedEffect | 0 | The 3D border width. For positive values, the border will appear raised. For negative values, the border will appear depressed. A zero value means the border will appear flat.

Return Value

The MultiChart object created.


ChartDirector.CFChart.FinanceChart

ChartDirector.CFChart.FinanceChart

Usage

FinanceChart(width)

Description

Creates a new FinanceChart object.

Arguments

Argument | Default | Description
width | (Mandatory) | The width of the chart in pixels. The height will be automatically determined as the chart is built.

Return Value

The FinanceChart object created.


ChartDirector.CFChart.DrawArea

ChartDirector.CFChart.DrawArea

Usage

DrawArea()

Description

Creates a DrawArea object.

Arguments

None

Return Value

The DrawArea object created.


ChartDirector.CFChart.ArrayMath

ChartDirector.CFChart.ArrayMath

Usage

ArrayMath(a)

Description

Creates an ArrayMath object and initialize it with the given array.

Arguments

Argument | Default | Description
a | (Mandatory) | An array of numbers used to initialize the ArrayMath object.

Return Value

The ArrayMath object created.


ChartDirector.CFChart.RanTable

ChartDirector.CFChart.RanTable

Usage

RanTable(seed, noOfCols, noOfRows)

Description

Creates a RanTable object.

Arguments

Argument | Default | Description
seed | (Mandatory) | The seed to be used in the random number generator.
noOfCols | (Mandatory) | The number of columns in the random number table.
noOfRows | (Mandatory) | The number of rows in the random number table.

Return Value

The RanTable object created.


ChartDirector.CFChart.FinanceSimulator

ChartDirector.CFChart.FinanceSimulator

Usage

FinanceSimulator(seed, startTime, endTime, resolution)

Description

Creates a FinanceSimulator object.

Arguments

Argument | Default | Description
seed | (Mandatory) | The seed to be used in the random number generator.
startTime | (Mandatory) | The start date/time of the financial date series.
endTime | (Mandatory) | The end date/time of the financial date series.
resolution | (Mandatory) | The resolution of the financial data series in seconds. For example, a value of 86400 means daily data (1 day = 86400 seconds). A value of 7 * 86400 means weekly data. A value of 30 * 86400 means monthly data.

Return Value

The FinanceSimulator object created.


ChartDirector.CFChart.WebChartViewer

ChartDirector.CFChart.WebChartViewer

Usage

WebChartViewer(pageContext, id)

Description

Creates a new WebChartViewer object.

Arguments

Argument | Default | Description
pageContext | (Mandatory) | The PageContext object representing the current web page. This is typically obtained by using the ColdFusion "GetPageContext" function.
id | (Mandatory) | The id of the WebChartViewer, which is also be used as the id attribute of the <IMG> tag for displaying the chart. It should start with A-Z, a-z or underscore, and consists entirely of alphanumeric characters with no spaces

Return Value

The WebChartViewer object created.


ChartDirector.CFChart.setLicenseCode

ChartDirector.CFChart.setLicenseCode

Usage

setLicenseCode(licCode)

Description

Sets the license code into ChartDirector.

ChartDirector will automatically get it's license code from the file "chartdir.lic".

If for some reason, you do not want to use the "chartdir.lic" file (eg. you want to embed ChartDirector with your application, but you do not want people to see the "chartdir.lic" file), you may use the setLicenseCode method to hard code the license code into your source code.

If ChartDirector is run without any license code, it will run in evaluation mode.

Arguments

Argument | Default | Description
licCode | (Mandatory) | A text string containing the license code.

Return Value

The error message, or an empty string if no error.


ChartDirector.CFChart.getVersion

ChartDirector.CFChart.getVersion

Usage

getVersion()

Description

Gets ChartDirector version information.

The version number is encoded as a 32-bit integer. The most significant 8 bits is the major version number. The next 8 bits are the minor version number. The least significant 16 bits are the build number.

Arguments

None

Return Value

The version information encoded in a 32-bit integer.


ChartDirector.CFChart.getBootLog

ChartDirector.CFChart.getBootLog

Usage

getBootLog()

Description

A diagnostic function to obtain the ChartDirector boot log.

Currently, ChartDirector does not need to do anything particular during start up, except scanning for the license file. Thus this information is mainly used to diagnose license file loading issues.

Arguments

None

Return Value

A text string containing the boot log.


ChartDirector.CFChart.testFont

ChartDirector.CFChart.testFont

Usage

testFont(font, fontIndex, fontHeight, fontWidth, angle)

Description

A diagnostic function to perform a font loading test.

From experience, the most common issue for font loading is unable to access server side fonts using anonymous user account for a web application, probably due to security restrictions. This diagnostic function can return the cause of problem to aid trouble-shooting.

Other uses of this function is to trace out where does ChartDirector search for the fonts, and the substitution font in case the request font is not available.

Arguments

Argument | Default | Description
font | (Mandatory) | The font name. See Font Specification for details on various font attributes.
fontIndex | (Mandatory) | The font index if the font name refers to a font collection. An index of 0 means the first font.
fontHeight | (Mandatory) | The font height in points. This parameter will not affect font loading if the exact font exists, but will affect which substitution font to use if the font does not exist.
fontWidth | (Mandatory) | The font width in points. This parameter will not affect font loading if the exact font exists, but will affect which substitution font to use if the font does not exist.
angle | (Mandatory) | The rotation angle of the text. The angle is measured in degrees in clockwise direction. This parameter will not affect font loading if the exact font exists, but will affect which substitution font to use if the font does not exist.

Return Value

A text string showing the result of the font loading test.


ChartDirector.CFChart.chartTime

ChartDirector.CFChart.chartTime

Usage

chartTime(y, m, d [, h, n, s ])

Description

Obtain the second elapsed since 01-01-0001 00:00:00 to the given time, which is the date/time format used by ChartDirector.

Arguments

Argument | Default | Description
y | (Mandatory) | The year component of the given time.
m | (Mandatory) | The month component of the given time
d | (Mandatory) | The day of month component of the given time.
h | 0 | The hour component of the given time.
n | 0 | The minute component of the given time.
s | 0 | The second component of the given time.

Return Value

The second elapsed since 01-01-0001 00:00:00 to the given time.


ChartDirector.CFChart.chartTime2

ChartDirector.CFChart.chartTime2

Usage

chartTime2(t)

Description

Converts a UNIX time (seconds elapsed since 01-01-1970 00:00:00 GMT) to the date/time format used by ChartDirector.

The UNIX time will be converted assuming based on local time zone (the time zone settings of the operating system).

Arguments

Argument | Default | Description
t | (Mandatory) | A time represented as seconds elapsed since 01-01-1970 00:00:00 GMT.

Return Value

The second elapsed since 01-01-0001 00:00:00 to the given time.


ChartDirector.CFChart.getChartYMD

ChartDirector.CFChart.getChartYMD

Usage

getChartYMD(t)

Description

Gets the year, month and day represented by a ChartDirector date/time.

Arguments

Argument | Default | Description
t | (Mandatory) | A ChartDirector date/time, that is, a number representing seconds elapsed since 01-01-0001 00:00:00.

Return Value

An integer which when represented in decimal notation is yyyymmdd, where yyyy is the year, mm is the month (1 - 12), and dd is the day (1 - 31).


ChartDirector.CFChart.getChartWeekDay

ChartDirector.CFChart.getChartWeekDay

Usage

getChartWeekDay(t)

Description

Gets the weekday represented by a ChartDirector date/time.

Arguments

Argument | Default | Description
t | (Mandatory) | A ChartDirector date/time, that is, a number representing seconds elapsed since 01-01-0001 00:00:00.

Return Value

An integer from 0 - 6 representing Sun - Sat.


ChartDirector.CFChart.CTime

ChartDirector.CFChart.CTime

Usage

CTime(time)

Description

Converts a ColdFusion date to ChartDirector's date/time format.

For the ColdFusion edition of ChartDirector, there should be no need to call CTime explicitly, as ChartDirector will automatically convert ColdFusion date to ChartDirector's internal format. This method is provided just for consistency with other editions of ChartDirector.

Arguments

Argument | Default | Description
time | (Mandatory) | A ColdFusion date object.

Return Value

A number representing dates/times in ChartDirector's date/time format.


ChartDirector.CFChart.CTime2

ChartDirector.CFChart.CTime2

Usage

CTime2(times)

Description

Converts an array of ColdFusion date objects to ChartDirector's date/time format.

This function is similar to ChartDirector.CFChart.CTime, but operate on an array of ColdFusion date objects instead of a single ColdFusion date object.

Arguments

Argument | Default | Description
times | (Mandatory) | An array of ColdFusion date objects.

Return Value

An array of numbers representing dates/times in ChartDirector's date/time format.


ChartDirector.CFChart.NTime

ChartDirector.CFChart.NTime

Usage

NTime(time)

Description

Converts a date/time in ChartDirector's date/time format to a ColdFusion date object.

This method is the reverse of ChartDirector.CFChart.CTime.

Arguments

Argument | Default | Description
time | (Mandatory) | A number representing date/time using ChartDirector's date/time format.

Return Value

A ColdFusion date object.


ChartDirector.CFChart.NTime2

ChartDirector.CFChart.NTime2

Usage

NTime2(times)

Description

Converts an array of dates/times in ChartDirector's date/time format to ColdFusion date objects.

This method is the reverse of ChartDirector.CFChart.CTime2.

Arguments

Argument | Default | Description
times | (Mandatory) | An array of numbers representing dates/times using ChartDirector's date/time format.

Return Value

An array of ColdFusion date objects.


ChartDirector.CFChart.goldColor

ChartDirector.CFChart.goldColor

Usage

goldColor([ angle ])

Description

Creates a golden color, most commonly used as a background color.

This method is a short cut to the ChartDirector.CFChart.metalColor method, using yellow (FFEE44 in hex) as the base color.

Arguments

Argument | Default | Description
angle | 90 | The direction for brightness modulation, specified as a clockwise angle in degrees, with 0 being the upward pointing direction.

Return Value

A 32-bit integer representing the golden color.


ChartDirector.CFChart.silverColor

ChartDirector.CFChart.silverColor

Usage

silverColor([ angle ])

Description

Creates a silver color, most commonly used as a background color.

This method is a short cut to the ChartDirector.CFChart.metalColor method, using grey (CCCCCC in hex) as the base color.

Arguments

Argument | Default | Description
angle | 90 | The direction for brightness modulation, specified as a clockwise angle in degrees, with 0 being the upward pointing direction.

Return Value

A 32-bit integer representing the silver color.


ChartDirector.CFChart.metalColor

ChartDirector.CFChart.metalColor

Usage

metalColor(c [, angle ])

Description

Creates a color by modulates the brightness of another color to create metallic shiny effects.

The brightness of the color will vary smoothly across the image in a given a direction, so as to produce a shiny effect. The modulation period will be the same as the size of the image, so this method is best use to create background colors.

Arguments

Argument | Default | Description
c | (Mandatory) | The color to be modulated.
angle | 90 | The direction for brightness modulation, specified as a clockwise angle in degrees, with 0 being the upward pointing direction.

Return Value

A 32-bit integer representing the metallic color.


ChartDirector.CFChart.glassEffect

ChartDirector.CFChart.glassEffect

Usage

glassEffect([ glareSize [, glareDirection [, raisedEffect ]]])

Description

A complex shading effect that emulates tinted glass or semi-transparent plastic material.

This effect involves glare and variation of lighting caused by reflection and refraction inside the material. It is best explained by viewing the examples.

Example | Location of lighting effect
Error Line Chart | The title is shaded using glass effect, with NormalGlare, lighting from Top, and raised effect of 5 pixels.
Donut Chart | Both the title and the sector labels are shaded using glass effect with ReducedGlare, lighting from Top, and raised effect of 5 pixels.
Glass Multi-Bar Chart | The bars are shaded using glass effect, with NormalGlare, lighting from Left, and raised effect of 5 pixels.

Currently, this effect only works well for long, thin objects, such as title bars, text boxes and bars in bar charts.

The glassEffect method returns an integer representing this effect. The integer can be used as the third argument to Box.setBackground to apply the effect it objects derived from Box (such as labels and titles represented by TextBox). It may also be used as the second argument to Layer.setBorderColor for BarLayer objects to apply the effect to bars.

Arguments

Argument | Default | Description
glareSize | NormalGlare | The amount of glare. Must be one of the predefined constants NormalGlare, ReducedGlare or NoGlare. With NormalGlare and ReducedGlare, the glare will cover around 50% and 35% of the object. If NoGlare is used, there will be no glare and the effect will not look like glass at all, but is equivalent to the ChartDirector.CFChart.softLighting effect. Usually, NormalGlare is best for thin objects with lightly colored background, while ReducedGlare is best for dark background objects or not-so-thin objects (eg. text boxes using white text on a dark background, or with more than 1 line of text).
glareDirection | Top | The direction of the glare, which must be one of the predefined constants Top, Right, Bottom, Left.
raisedEffect | 5 | With glass shading effect, the object will appear to have some 3D depth. The raisedEffect argument controls the amount of 3D depth in pixels.

Return Value

An integer representing the glass effect.


ChartDirector.CFChart.softLighting

ChartDirector.CFChart.softLighting

Usage

softLighting([ direction [, raisedEffect ]])

Description

A special shading effect that looks like gradient coloring.

This effect is best explained by viewing the examples.

Example | Location of lighting effect
Soft Multi-Bar Chart | The bars are shaded using soft lighting effect, with light direction from Top, and raised effect of 4 pixels.
Soft Bar Shading | The bars are shaded using soft lighting effect, with light direction from Left, and raised effect of 4 pixels.
Spline Line Chart | The title is shaded using soft lighting effect, with light direction from Right, and raised effect of 4 pixels.

The softLighting method returns an integer representing this effect. The integer can be used as the third argument to Box.setBackground to apply the effect it objects derived from Box (such as labels and titles represented by TextBox). It may also be used as the second argument to Layer.setBorderColor for BarLayer objects to apply the effect to bars.

Arguments

Argument | Default | Description
direction | Top | The direction of the lighting, which must be one of the predefined constants Top, Bottom, Right or Left.
raisedEffect | 4 | With soft lighting effect, the object will appear to have some 3D depth. The raisedEffect argument controls the amount of 3D depth in pixels.

Return Value

An integer representing the soft lighting effect.


ChartDirector.CFChart.PolygonShape

ChartDirector.CFChart.PolygonShape

Usage

PolygonShape(side)

Description

Gets the shape id that represents a polygon.

Please refer to Shape Specification for samples and more information on using shapes in ChartDirector.

Arguments

Argument | Default | Description
side | (Mandatory) | The number of sides the polygon has.

Return Value

An integer shape id representing the polygon.


ChartDirector.CFChart.Polygon2Shape

ChartDirector.CFChart.Polygon2Shape

Usage

Polygon2Shape(side)

Description

Gets the shape id that represents a polygon in an alternative orientation.

Please refer to Shape Specification for samples and more information on using shapes in ChartDirector.

Arguments

Argument | Default | Description
side | (Mandatory) | The number of sides the polygon has.

Return Value

An integer shape id representing the polygon in an alternative orientation.


ChartDirector.CFChart.StarShape

ChartDirector.CFChart.StarShape

Usage

StarShape(side)

Description

Gets the shape id that represents a star shape.

Please refer to Shape Specification for samples and more information on using shapes in ChartDirector.

Arguments

Argument | Default | Description
side | (Mandatory) | The number of points the polygon has.

Return Value

An integer shape id representing the star shape.


ChartDirector.CFChart.CrossShape

ChartDirector.CFChart.CrossShape

Usage

CrossShape(width)

Description

Gets the shape id that represents a '+' shape.

Please refer to Shape Specification for samples and more information on using shapes in ChartDirector.

Arguments

Argument | Default | Description
width | (Mandatory) | The percentage width of the arms of the a '+' relative to the entire shape. Must be between 0 and 1.

Return Value

An integer shape id representing the a '+' shape.


ChartDirector.CFChart.Cross2Shape

ChartDirector.CFChart.Cross2Shape

Usage

Cross2Shape(width)

Description

Gets the shape id that represents a 'X' shape.

Please refer to Shape Specification for samples and more information on using shapes in ChartDirector.

Arguments

Argument | Default | Description
width | (Mandatory) | The percentage width of the arms of the a 'X' relative to the entire shape. Must be between 0 and 1.

Return Value

An integer shape id representing the a 'X' shape.


ChartDirector.CFChart.StartOfHourFilter

ChartDirector.CFChart.StartOfHourFilter

Usage

StartOfHourFilter([ labelStep [, initialMargin ]])

Description

Creates a data filter that matches date/times that represent the start of a new hour in a date/time series.

This method is typically used in Axis.setMultiFormat and Axis.setMultiFormat2 to select specific dates/times for formatting as axis labels.

In a date/time series, an element is considered that start of a new hour if it is of a different hour than the previous element. It does not need to be at exactly the starting instance of the hour.

For the first element of the date/time series, because there is no previous element to compare with, it will be considered as the start of a new hour if it is "near" the exact starting instance of the current hour, in which "near" is defined using the initialMargin argument, expressed as a ratio (0 to 1) of the hour duration.

Arguments

Argument | Default | Description
labelStep | 1 | For dates/times that matches the start of hour criteria, picks only 1 out of every "labelStep" number of elements. For example, if this argument is 3, only 1 of every 3 elements that at at the start of hour will be selected.
initialMargin | 0.05 | If the first label is "near" the exact starting instance of the current hour to within the ratio specified in the initial margin, it will be considered to have matched the start of hour criteria.

Return Value

An integer filter id representing the filter.


ChartDirector.CFChart.StartOfDayFilter

ChartDirector.CFChart.StartOfDayFilter

Usage

StartOfDayFilter([ labelStep [, initialMargin ]])

Description

Creates a data filter that matches date/times that represent the start of a new day in a date/time series.

This method is typically used in Axis.setMultiFormat and Axis.setMultiFormat2 to select specific dates/times for formatting as axis labels.

In a date/time series, an element is considered that start of a new day if it is of a different day than the previous element. It does not need to be at exactly the starting instance of the day.

For the first element of the date/time series, because there is no previous element to compare with, it will be considered as the start of a new day if it is "near" the exact starting instance of the current day, in which "near" is defined using the initialMargin argument, expressed as a ratio (0 to 1) of the day duration.

Arguments

Argument | Default | Description
labelStep | 1 | For dates/times that matches the start of day criteria, picks only 1 out of every "labelStep" number of elements. For example, if this argument is 3, only 1 of every 3 elements that at at the start of day will be selected.
initialMargin | 0.05 | If the first label is "near" the exact starting instance of the current day to within the ratio specified in the initial margin, it will be considered to have matched the start of day criteria.

Return Value

An integer filter id representing the filter.


ChartDirector.CFChart.StartOfWeekFilter

ChartDirector.CFChart.StartOfWeekFilter

Usage

StartOfWeekFilter([ labelStep [, initialMargin ]])

Description

Creates a data filter that matches date/times that represent the start of a new week in a date/time series.

This method is typically used in Axis.setMultiFormat and Axis.setMultiFormat2 to select specific dates/times for formatting as axis labels.

In a date/time series, an element is considered that start of a new week if it is of a different week than the previous element. It does not need to be at exactly the starting instance of the week.

For the first element of the date/time series, because there is no previous element to compare with, it will be considered as the start of a new week if it is "near" the exact starting instance of the current week, in which "near" is defined using the initialMargin argument, expressed as a ratio (0 to 1) of the week duration.

Arguments

Argument | Default | Description
labelStep | 1 | For dates/times that matches the start of week criteria, picks only 1 out of every "labelStep" number of elements. For example, if this argument is 3, only 1 of every 3 elements that at at the start of week will be selected.
initialMargin | 0.05 | If the first label is "near" the exact starting instance of the current week to within the ratio specified in the initial margin, it will be considered to have matched the start of week criteria.

Return Value

An integer filter id representing the filter.


ChartDirector.CFChart.StartOfMonthFilter

ChartDirector.CFChart.StartOfMonthFilter

Usage

StartOfMonthFilter([ labelStep [, initialMargin ]])

Description

Creates a data filter that matches date/times that represent the start of a new month in a date/time series.

This method is typically used in Axis.setMultiFormat and Axis.setMultiFormat2 to select specific dates/times for formatting as axis labels.

In a date/time series, an element is considered that start of a new month if it is of a different month than the previous element. It does not need to be at exactly the starting instance of the month.

For the first element of the date/time series, because there is no previous element to compare with, it will be considered as the start of a new month if it is "near" the exact starting instance of the current month, in which "near" is defined using the initialMargin argument, expressed as a ratio (0 to 1) of the month duration.

Arguments

Argument | Default | Description
labelStep | 1 | For dates/times that matches the start of month criteria, picks only 1 out of every "labelStep" number of elements. For example, if this argument is 3, only 1 of every 3 elements that at at the start of month will be selected.
initialMargin | 0.05 | If the first label is "near" the exact starting instance of the current month to within the ratio specified in the initial margin, it will be considered to have matched the start of month criteria.

Return Value

An integer filter id representing the filter.


ChartDirector.CFChart.StartOfYearFilter

ChartDirector.CFChart.StartOfYearFilter

Usage

StartOfYearFilter([ labelStep [, initialMargin ]])

Description

Creates a data filter that matches date/times that represent the start of a new year in a date/time series.

This method is typically used in Axis.setMultiFormat and Axis.setMultiFormat2 to select specific dates/times for formatting as axis labels.

In a date/time series, an element is considered that start of a new year if it is of a different year than the previous element. It does not need to be at exactly the starting instance of the year.

For the first element of the date/time series, because there is no previous element to compare with, it will be considered as the start of a new year if it is "near" the exact starting instance of the current year, in which "near" is defined using the initialMargin argument, expressed as a ratio (0 to 1) of the year duration.

Arguments

Argument | Default | Description
labelStep | 1 | For dates/times that matches the start of year criteria, picks only 1 out of every "labelStep" number of elements. For example, if this argument is 3, only 1 of every 3 elements that at at the start of year will be selected.
initialMargin | 0.05 | If the first label is "near" the exact starting instance of the current year to within the ratio specified in the initial margin, it will be considered to have matched the start of year criteria.

Return Value

An integer filter id representing the filter.


ChartDirector.CFChart.RegularSpacingFilter

ChartDirector.CFChart.RegularSpacingFilter

Usage

RegularSpacingFilter([ labelStep [, initialMargin ]])

Description

Creates a data filter that matches 1 out of every N elements.

This method is typically used in Axis.setMultiFormat and Axis.setMultiFormat2 to select specific elements for formatting as axis labels.

Arguments

Argument | Default | Description
labelStep | 1 | Picks 1 out of every "labelStep" number of elements. For example, if this argument is 3, only 1 of every 3 elements will be selected.
initialMargin | 0 | Adds an offset when determining the elements to be selected. For example, if the labelStep is 3, the selected indexes should be 0, 3, 6, 9, .... If initialMargin is set to 1, the indexes becomes 1, 4, 7, 10, ....

Return Value

An integer filter id representing the filter.


ChartDirector.CFChart.AllPassFilter

ChartDirector.CFChart.AllPassFilter

Usage

AllPassFilter()

Description

Creates a data filter that matches every element.

This method is typically used in Axis.setMultiFormat and Axis.setMultiFormat2 as a "catch all" filter.

Arguments

None

Return Value

An integer filter id representing the filter.


ChartDirector.CFChart.NonePassFilter

ChartDirector.CFChart.NonePassFilter

Usage

NonePassFilter()

Description

Creates a data filter that matches no element.

This method is typically used in Axis.setMultiFormat and Axis.setMultiFormat2 as a "deny all" filter.

Arguments

None

Return Value

An integer filter id representing the filter.


ChartDirector.CFChart.SelectItemFilter

ChartDirector.CFChart.SelectItemFilter

Usage

SelectItemFilter(item)

Description

Creates a data filter that matches the specified item.

This method is typically used in Axis.setMultiFormat and Axis.setMultiFormat2 to select a specific element for special formatting.

Arguments

Argument | Default | Description
item | (Mandatory) | The index of the specified item.

Return Value

An integer filter id representing the filter.


Box

Box

The Box class represents boxes. It is used as the base class for more complex classes (such as the TextBox class).

Method | Inherited | Description
setPos | (Self) | Sets the coordinates of the top-left corner of the box.
setSize | (Self) | Sets the width and height of the box.
setBackground | (Self) | Sets the background color, border color and 3D border effect of the box.
setRoundedCorners | (Self) | Sets the border style to use rounded corners.
getWidth | (Self) | Gets the width of the box.
getHeight | (Self) | Gets the height of the box.
getImageCoor | (Self) | Gets the image map coordinates of the box as HTML image map attributes.
setZOrder | (Self) | Sets the z-order (drawing order) for custom box objects.


Box.setPos

Box.setPos

Usage

setPos(x, y)

Description

Sets the coordinates of the top-left corner of the box.

Arguments

Argument | Default | Description
x | (Mandatory) | The x coordinate of the left of the box.
y | (Mandatory) | The y coordinate of the top of the box.

Return Value

None


Box.setSize

Box.setSize

Usage

setSize(w, h)

Description

Sets the width and height of the box.

Arguments

Argument | Default | Description
w | (Mandatory) | The width of the box in pixels.
h | (Mandatory) | The height of the box in pixels.

Return Value

None


Box.setBackground

Box.setBackground

Usage

setBackground(color [, edgeColor [, raisedEffect ]])

Description

Sets the background color, border color and 3D border effect of the box.

Arguments

Argument | Default | Description
color | (Mandatory) | The background color of the box.
edgeColor | -1 | The border color of the box.
raisedEffect | 0 | The 3D border width. For positive values, the border will appear raised. For negative values, the border will appear depressed. A zero value means the border will appear flat. This argument is also used to support ChartDirector.CFChart.glassEffect and ChartDirector.CFChart.softLighting effects.

Return Value

None


Box.setRoundedCorners

Box.setRoundedCorners

Usage

setRoundedCorners([ r1 [, r2 [, r3 [, r4 ]]]])

Description

Sets the border style to use rounded corners.

Arguments

Argument | Default | Description
r1 | 10 | The radius of the top-left rounded corner in pixels.
r2 | -1 | The radius of the top-right rounded corner in pixels. The default value of -1 means it is the same as the radius of the top-left corner.
r3 | -1 | The radius of the bottom-right rounded corner in pixels. The default value of -1 means it is the same as the radius of the top-left corner.
r4 | -1 | The radius of the bottom-left rounded corner in pixels. The default value of -1 means it is the same as the radius of the top-left corner.

Return Value

None


Box.getWidth

Box.getWidth

Usage

getWidth()

Description

Gets the width of the box.

In some usages, the width of a box may be dynamically determined. An example is the width of an LegendBox, which cannot be known until all data are available. In these cases, the width is undefined until the chart or at least the legend box has been laid out (using BaseChart.layout or BaseChart.layoutLegend), or the chart image has been drawn (eg. using BaseChart.makeSession, BaseChart.makeChart or BaseChart.makeChart2).

Arguments

None

Return Value

The width of the box in pixels.


Box.getHeight

Box.getHeight

Usage

getHeight()

Description

Gets the height of the box.

In some usages, the height of a box may be dynamically determined. An example is the height of an LegendBox, which cannot be known until all data are available. In these cases, the height is undefined until the chart or at least the legend box has been laid out (using BaseChart.layout or BaseChart.layoutLegend), or the chart image has been drawn (eg. using BaseChart.makeSession, BaseChart.makeChart or BaseChart.makeChart2).

Arguments

None

Return Value

The height of the box in pixels.


Box.getImageCoor

Box.getImageCoor

Usage

getImageCoor([ offsetX, offsetY ])

Description

Gets the image map coordinates of the box as HTML image map attributes.

The image map coordinates will be in the following format:

shape="rect" cords="[x1],[y1],[x2],[y2]"

where (x1, y1) and (x2, y2) are opposite corners of the box. The format is designed so that it can easily be incorporated into HTML image maps.

This method should be called only after creating the chart image (eg. using BaseChart.makeSession, BaseChart.makeChart or BaseChart.makeChart2). The image map cannot be determined without creating the chart image first.

Arguments

Argument | Default | Description
offsetX | 0 | An offset to be added to all x coordinates in the image map. This is useful if the current image will be shifted and inserted into another image. In this case, the image map will need to be shifted by the same offset.
offsetY | 0 | An offset to be added to all y coordinates in the image map. See offsetX above for description.

Return Value

A text string representing the coordinates of the box in HTML image map attribute format.


Box.setZOrder

Box.setZOrder

Usage

setZOrder(z)

Description

Sets the z-order (drawing order) for custom box objects.

The setZOrder method of the Box object only applies to custom objects created using BaseChart.addText. Box objects generated by ChartDirector, such as axes labels, data labels, etc., will have their z-order fixed by ChartDirector.

ChartDirector will draw objects in ascending z-order. That means objects with larger z-order will be drawn later, and hence will be on the top of the chart.

The following constants represents the z-order of various ChartDirector objects. You may use these constants to determine the ordering of the object relative to these ChartDirector objects.

Constant | Value | Description
ChartBackZ | 0x100 | The z-order of the chart background. Objects at this z-order will be painted on the chart background.
ChartFrontZ | 0xffff | The z-order of the front of the chart. Objects at this z-order will appear on top of all chart objects.
PlotAreaZ | 0x1000 | The z-order of the plot area background. Objects at this z-order will be painted on the plot area background but behind other plot area objects (such as grid lines).
GridLinesZ | 0x2000 | The z-order of the grid lines. Objects at this z-order will be painted after painting the grid lines.

Arguments

Argument | Default | Description
z | (Mandatory) | The z-order of the object.

Return Value

None


TextBox

TextBox

The TextBox class represents text boxes. It is a subclass of Box.

Method | Inherited | Description
setText | (Self) | Sets the text to be shown in the text box.
setFontStyle | (Self) | Sets the font of the text by specifying the file that contains the font.
setFontSize | (Self) | Sets the font height and width in points.
setFontAngle | (Self) | Sets the rotation angle and layout direction of the text.
setFontColor | (Self) | Sets the color of the text.
setAlignment | (Self) | Sets the alignment of the text relative to the container box.
setWidth | (Self) | Sets the width of the text box and wraps text if necessary.
setHeight | (Self) | Sets the height of the text box.
setMaxWidth | (Self) | Sets the maximum width of the text box and wraps text if necessary.
setTruncate | (Self) | Sets the maximum number of lines in the text box, and truncate the text if it exceeds the line count.
setMargin | (Self) | Sets all margins (left, right, top, and bottom) of the text box to the same value.
setMargin2 | (Self) | Sets the margins of the text box in pixels.
setPos | Box | Sets the coordinates of the top-left corner of the box.
setSize | Box | Sets the width and height of the box.
setBackground | Box | Sets the background color, border color and 3D border effect of the box.
setRoundedCorners | Box | Sets the border style to use rounded corners.
getWidth | Box | Gets the width of the box.
getHeight | Box | Gets the height of the box.
getImageCoor | Box | Gets the image map coordinates of the box as HTML image map attributes.
setZOrder | Box | Sets the z-order (drawing order) for custom box objects.


TextBox.setText

TextBox.setText

Usage

setText(text)

Description

Sets the text to be shown in the text box.

See ChartDirector Mark Up Language on how to embed special tags in the text for sophisticated formatting.

Arguments

Argument | Default | Description
text | (Mandatory) | The text to be displayed in the text box.

Return Value

None


TextBox.setFontStyle

TextBox.setFontStyle

Usage

setFontStyle(font [, fontIndex ])

Description

Sets the font of the text by specifying the file that contains the font.

See Font Specification for details on various font attributes.

Arguments

Argument | Default | Description
font | (Mandatory) | The font name.
fontIndex | 0 | The font index in case the font name refers to a font collection. An index of 0 means the first font.

Return Value

None


TextBox.setFontSize

TextBox.setFontSize

Usage

setFontSize(fontHeight [, fontWidth ])

Description

Sets the font height and width in points.

See Font Specification for details on various font attributes.

Arguments

Argument | Default | Description
fontHeight | (Mandatory) | The font height in points.
fontWidth | 0 | The font width in points. If the font width is zero, it is assumed to be the same as the font height.

Return Value

None


TextBox.setFontAngle

TextBox.setFontAngle

Usage

setFontAngle(angle [, vertical ])

Description

Sets the rotation angle and layout direction of the text.

See Font Specification for details on various font attributes.

Arguments

Argument | Default | Description
angle | (Mandatory) | The text rotation angle. Rotation is measured in counter-clockwise direction in degrees.
vertical | false (zero) | Determine if the font is layout horizontally (from left to right) or vertically (from top to down). Vertical layout is common for Oriental languages such as Chinese, Japanese and Korean. A true (non-zero) value means vertical layout. A false (zero) value means horizontal layout.

Return Value

None


TextBox.setFontColor

TextBox.setFontColor

Usage

setFontColor(color)

Description

Sets the color of the text.

If this method is not called, TextColor will be used to draw the text.

Arguments

Argument | Default | Description
color | (Mandatory) | The font color.

Return Value

None


TextBox.setAlignment

TextBox.setAlignment

Usage

setAlignment(a)

Description

Sets the alignment of the text relative to the container box.

Arguments

Argument | Default | Description
a | (Mandatory) | The alignment specification. See Alignment Specification for supported alignment types.

Return Value

None


TextBox.setWidth

TextBox.setWidth

Usage

setWidth(width)

Description

Sets the width of the text box and wraps text if necessary.

By default, the width of the text box is automatically determined to be the length of the text. The setWidth method can be used to specified a fix width. If the text requires a longer width for display, the text will be wrapped into multiple lines.

Arguments

Argument | Default | Description
width | (Mandatory) | The width of the text box in pixels.

Return Value

None


TextBox.setHeight

TextBox.setHeight

Usage

setHeight(height)

Description

Sets the height of the text box.

By default, the height of the text box is automatically determined to be just enough to hold the text. The setHeight method can be used to specified a fix height.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the text box in pixels.

Return Value

None


TextBox.setMaxWidth

TextBox.setMaxWidth

Usage

setMaxWidth(maxWidth)

Description

Sets the maximum width of the text box and wraps text if necessary.

By default, the width of the text box is automatically determined to be the length of the text. This method can be used to limit the width of the text box. If the text requires a longer width for display, it will be wrapped into multiple lines.

Arguments

Argument | Default | Description
maxWidth | (Mandatory) | The maximum width of the text box in pixels.

Return Value

None


TextBox.setTruncate

TextBox.setTruncate

Usage

void setTruncate(maxWidth [, maxLines ])

Description

Sets the maximum number of lines in the text box, and truncate the text if it exceeds the line count.

The maxWidth parameter of this method specifies the maximum width of the text box. If the text requires a longer width for display, it will be wrapped into multiple lines. However, if the number of lines exceed maxLines, the text will be truncated, with the last visible characters replaced with "...".

If maxLines is 1 (the default), the text will never be wrapped and will be truncated directly if it needs more than maxWidth for display.

Arguments

Argument | Default | Description
maxWidth | (Mandatory) | The maximum width of the text box in pixels.
maxLines | 1 | The maximum number of lines that the text box can have. The text will be truncated if it exceeds the maximum number of lines.

Return Value

None


TextBox.setMargin

TextBox.setMargin

Usage

setMargin(m)

Description

Sets all margins (left, right, top, and bottom) of the text box to the same value.

The margins of a text box are the distances between the borders of the text box to the text inside. By default, the left and right margins are approximately half the font width, and the top and bottom margins are approximately 1/4 of the font height.

Arguments

Argument | Default | Description
m | (Mandatory) | The left, right, top and bottom margins in pixels.

Return Value

None


TextBox.setMargin2

TextBox.setMargin2

Usage

setMargin2(leftMargin, rightMargin, topMargin, bottomMargin)

Description

Sets the margins of the text box in pixels.

The margins of a text box are the distances between the borders of the text box to the text inside. By default, the left and right margins are approximately half the font width, and the top and bottom margins are approximately 1/4 of the font height.

Arguments

Argument | Default | Description
leftMargin | (Mandatory) | The left margin in pixels.
rightMargin | (Mandatory) | The right margin in pixels.
topMargin | (Mandatory) | The top margin in pixels.
bottomMargin | (Mandatory) | The bottom margin in pixels.

Return Value

None


Line

Line

The Line class represents straight lines.

Method | Inherited | Description
setPos | (Self) | Sets the end-points of the line.
setColor | (Self) | Sets the color of the line.
setWidth | (Self) | Sets the width of the line in pixels.
setZOrder | (Self) | Sets the z-order (drawing order) of the line.


Line.setPos

Line.setPos

Usage

setPos(x1, y1, x2, y2)

Description

Sets the end-points of the line.

Arguments

Argument | Default | Description
x1 | (Mandatory) | The x coordinate of the first end-point of the line.
y1 | (Mandatory) | The y coordinate of the first end-point of the line.
x2 | (Mandatory) | The x coordinate of the second end-point of the line.
y2 | (Mandatory) | The y coordinate of the second end-point of the line.

Return Value

None


Line.setColor

Line.setColor

Usage

setColor(c)

Description

Sets the color of the line.

By default, the color of the line is LineColor. To draw a dash line, you can use a dash line color (created using BaseChart.dashLineColor or DrawArea.dashLineColor).

Arguments

Argument | Default | Description
c | (Mandatory) | The color of the line.

Return Value

None


Line.setWidth

Line.setWidth

Usage

setWidth(w)

Description

Sets the width of the line in pixels.

Arguments

Argument | Default | Description
w | (Mandatory) | The width (thickness) of the line in pixels.

Return Value

None


Line.setZOrder

Line.setZOrder

Usage

setZOrder(z)

Description

Sets the z-order (drawing order) of the line.

Please refer to Box.setZOrder on an explanation of z-order and the z-order of various standard ChartDirector objects.

Arguments

Argument | Default | Description
z | (Mandatory) | The z-order of the line.

Return Value

None


BaseChart

BaseChart

The BaseChart class is an abstract class containing methods that are common to all chart types.

Method | Inherited | Description
setSize | (Self) | Sets the size of the chart.
setBackground | (Self) | Sets the background color, border color and 3D border effect of the chart.
setRoundedFrame | (Self) | Sets the border style of the chart to rounded corners.
setBorder | (Self) | Sets the border color of the chart.
setWallpaper | (Self) | Uses the image from the specified file as the wallpaper to repetitively fill the background of the chart.
setBgImage | (Self) | Uses the image from the specified file as the background image of the chart.
setSearchPath | (Self) | Sets the search path for loading image files.
setTransparentColor | (Self) | Specifies a certain color to mean transparent when creating the image output, or to include alpha transparency channel in the output.
setAntiAlias | (Self) | Controls whether anti-alias is used when drawing lines, shapes and text.
addTitle | (Self) | Adds a title at the top center of the chart.
addTitle2 | (Self) | Adds a title to the chart.
addLegend | (Self) | Adds a legend box to the chart.
addLegend2 | (Self) | Adds a legend box to the chart with grid layout.
getLegend | (Self) | Gets the LegendBox object representing the legend box in the chart.
layoutLegend | (Self) | Lays out and gets the LegendBox object representing the legend box in the chart.
getDrawArea | (Self) | Retrieves the internal DrawArea object that is used to draw the chart.
addText | (Self) | Adds a text box to the chart.
addLine | (Self) | Adds a line to the chart.
addExtraField | (Self) | Adds an array of text to be used as an extra field in various places.
addExtraField2 | (Self) | Adds an array of numbers/dates to be used as an extra field in various places.
setColor | (Self) | Change the color at the specified position in the palette.
setColors | (Self) | Change the colors in the palette.
setColors2 | (Self) | Change the colors in the palette, starting from the specified position in the palette.
getColor | (Self) | Gets the color at the specified position of the palette.
halfColor | (Self) | Creates a color that is half the intensity of the given color.
dashLineColor | (Self) | Creates a dash line color.
patternColor | (Self) | Creates a pattern color using an array of colors as the bitmap pattern.
patternColor2 | (Self) | Creates a pattern color by loading the pattern from an image file.
linearGradientColor | (Self) | Creates a two-point linear gradient color.
linearGradientColor2 | (Self) | Creates a multi-point linear gradient color.
radialGradientColor | (Self) | Creates a two-point radial gradient color.
radialGradientColor2 | (Self) | Creates a multi-point radial gradient color.
gradientColor | (Self) | Creates a two-point linear gradient color.
gradientColor2 | (Self) | Creates a multi-point linear gradient color.
setDefaultFonts | (Self) | Sets the defaults for normal, bold, italic and bold-italic fonts.
setFontTable | (Self) | Sets an entry in the font table to the specified font name.
formatValue | (Self) | Formats a number/date using the ChartDirector formatting syntax as is in Parameter Substitution and Formatting.
setNumberFormat | (Self) | Sets the characters used for thousand separator, decimal point, and negative sign.
setMonthNames | (Self) | Sets the names of the months for date/time formatting purposes.
setWeekDayNames | (Self) | Sets the names of the week days for date/time formatting purposes.
setAMPM | (Self) | Sets the names to be used to denote morning and afternoon.
layout | (Self) | Perform auto-scaling of the axis and compute the positions of the various objects in the chart.
makeChart | (Self) | Generates the chart image and save it into a file.
makeChart2 | (Self) | Generates the chart as an image in memory.
makeChart3 | (Self) | Generates the chart in internal format and return a DrawArea object to allow adding custom drawings on top of the chart.
makeSession | (Self) | Generates the chart as an image and save it to a session variable.
makeTmpFile | (Self) | Generates the chart as an image and save it to a temporary file, and automatically remove old files.
getHTMLImageMap | (Self) | Generates an HTML image map for the chart.
getChartMetrics | (Self) | Gets the chart metrics for passing to WebChartViewer.setChartMetrics to support view ports.


BaseChart.setSize

BaseChart.setSize

Usage

setSize(width, height)

Description

Sets the size of the chart.

Arguments

Argument | Default | Description
width | (Mandatory) | The width of the chart in pixels.
height | (Mandatory) | The height of the chart in pixels.

Return Value

None


BaseChart.setBackground

BaseChart.setBackground

Usage

setBackground(color [, edgeColor [, raisedEffect ]])

Description

Sets the background color, border color and 3D border effect of the chart.

Arguments

Argument | Default | Description
color | (Mandatory) | The background color of the chart.
edgeColor | Transparent | The border color of the chart.
raisedEffect | 0 | The 3D border width. For positive values, the border will appear raised. For negative values, the border will appear depressed. A zero value means the border will appear flat.

Return Value

None


BaseChart.setRoundedFrame

BaseChart.setRoundedFrame

Usage

setRoundedFrame([ extColor [, r1 [, r2 [, r3 [, r4 ]]]]])

Description

Sets the border style of the chart to rounded corners.

The underlying drawing surface for a chart is always rectangular. When rounded corners are used, part of the drawing surface (the regions external to the rounded corners) will be outside the chart border. The extColor argument specifies the color to be used for the external regions. Typically, it is set to the same color as the background the container that will be hosting the chart.

For example, in a web page, the extColor may be set to the same color as the web page background.

Arguments

Argument | Default | Description
extColor | FFFFFF | The exterior background color.
r1 | 10 | The radius of the top-left rounded corner in pixels.
r2 | -1 | The radius of the top-right rounded corner in pixels. The default value of -1 means it is the same as the radius of the top-left corner.
r3 | -1 | The radius of the bottom-right rounded corner in pixels. The default value of -1 means it is the same as the radius of the top-left corner.
r4 | -1 | The radius of the bottom-left rounded corner in pixels. The default value of -1 means it is the same as the radius of the top-left corner.

Return Value

None


BaseChart.setBorder

BaseChart.setBorder

Usage

setBorder(color)

Description

Sets the border color of the chart.

Arguments

Argument | Default | Description
color | (Mandatory) | The border color of the chart.

Return Value

None


BaseChart.setWallpaper

BaseChart.setWallpaper

Usage

setWallpaper(img)

Description

Uses the image from the specified file as the wallpaper to repetitively fill the background of the chart.

ChartDirector will automatically detect the image file format using the file extension, which must either png, jpg, jpeg, gif, wbmp or wmp (case insensitive).

Please refer to BaseChart.setSearchPath on the directory that ChartDirector will search for the file.

Arguments

Argument | Default | Description
img | (Mandatory) | The image file that is used as the background wallpaper of the chart.

Return Value

None


BaseChart.setBgImage

BaseChart.setBgImage

Usage

setBgImage(img [, align ])

Description

Uses the image from the specified file as the background image of the chart.

ChartDirector will automatically detect the image file format using the file extension, which must either png, jpg, jpeg, gif, wbmp or wmp (case insensitive).

Please refer to BaseChart.setSearchPath on the directory that ChartDirector will search for the file.

Arguments

Argument | Default | Description
img | (Mandatory) | The image file that is used as the background image of the chart.
align | Center | The alignment of the background image relative to the chart. See Alignment Specification for supported alignment types.

Return Value

None


BaseChart.setSearchPath

BaseChart.setSearchPath

Usage

setSearchPath(pageContext [, path ])

Description

Sets the search path for loading image files.

Several ChartDirector operations involve loading image files. Examples are wallpapers (BaseChart.setWallpaper), background images (BaseChart.setBgImage and PlotArea.setBackground2), user-defined symbols (DataSet.setDataSymbol2) or for embedding images in text using ChartDirector Mark Up Language.

By default, ChartDirector will search for the image files by interpreting the path names as file system path names. For example, the root "/" is interpreted as the root of the file system, not the root of the web document directory or the root of the servlet context. Relative paths are interpreted as relative to the "current working directory" (note that the "current working directory" is determined by the operating system and is in general different from the current URL directory.) This allows you to use image files outside of the web document directory.

In addition, ChartDirector will search for the image files by interpreting the path names as Java resource paths and search them in the Java class paths. This allows one to use images embedded in JAR files as resources.

The setSearchPath method allows you to specify using the current page context for searching the images. In this case, the root "/" is interpreted as the root of the servlet context. If a relative path is used, it is interpreted as relative to the current URL directory.

The setSearchPath allows you to optionally specify one or more directories to search for the image files. Directories should be separated with the path separator of the operating system (";" for Windows and ":" for Linux/UNIX).

Arguments

Argument | Default | Description
pageContext | (Mandatory) | The PageContext object representing the current web page. This is typically obtained by using the ColdFusion "GetPageContext" function.
path | "" | A list of directories to search for the images, separated with the path separator of the operating system (";" for Windows and ":" for Linux/UNIX). If this argument is not provided, then the current URL directory is used.

Return Value

None


BaseChart.setTransparentColor

BaseChart.setTransparentColor

Usage

setTransparentColor(c)

Description

Specifies a certain color to mean transparent when creating the image output, or to include alpha transparency channel in the output.

There are two types of transparency:

  • Alpha transparency: In addition to red, green and blue levels, there is a transparency level associated with each pixel, which can range from completely transparent to completely opaque. The data associated with the transparency information is called the alpha channel.

  • Single color transparency: The image itself has no alpha channel, but a certain color is used to mean completely transparent.
For internal drawing, ChartDirector always use alpha transparency. However, when outputting the image as an image file, ChartDirector by default will remove the alpha channel to reduce image size. It is because many image displaying software do not support alpha transparency. For example, the IE browser only supports single color transparency but not alpha transparency.

If you want to use single color transparency in the output, you may specify the transparent color as the argument to the setTransparentColor method. Note that only GIF and PNG can support single color transparency. JPEG, BMP and WBMP cannot support transparency at all.

If you do want to keep the alpha channel in final output, you may pass -1 as the argument to setTransparentColor. Note that the only image format that can support alpha transparency is PNG.

One important thing to note is that the IE browser (and possibly many image displaying software) only supports single color transparency for palette based images with up to 256 colors, but not for true color images. For this reason, if single color transparency is used, ChartDirector will automatically reduce the image to 256 colors if it has more than 256 colors. This may result in lost of image quality, especially if the image contains gradient colors.

Therefore, due to the limitations of the current generations of image displaying software, for highest image quality, sometimes it may be beneficial to not using transparency in image output, but to set the image background color to the same color as the container background.

Arguments

Argument | Default | Description
c | (Mandatory) | The color that is designated as the transparent color. If -1 is used, the full alpha transparency channel will be included in the final output.

Return Value

None


BaseChart.setAntiAlias

BaseChart.setAntiAlias

Usage

setAntiAlias([ shapeAntiAlias [, textAntiAlias ]])

Description

Controls whether anti-alias is used when drawing lines, shapes and text.

For anti-aliasing text, ChartDirector supports the following modes.

Constant | Value | Description
NoAntiAlias | 0 | Disable anti-alias when drawing text
AntiAlias | 1 | Always use anti-alias when drawing text
AutoAntiAlias | 2 | Automatically determine if anti-alias should be used for the text. This is the default. Currently, ChartDirector will anti-alias only large or bold fonts. For small fonts, assuming it is of high quality, anti-alias is unnecessary. It is because high quality fonts are normally designed to be sharp and clear at low resolution. Anti-aliasing will blur the fonts and make them look worse. However, for complicated fonts (e.g. some fonts with oriental characters), or for lower quality fonts (e.g. some freeware fonts), anti-alias may be necessary. In this case, it may be needed to force anti-aliasing of all fonts using AntiAlias mode.

Arguments

Argument | Default | Description
shapeAntiAlias | true (non-zero) | A true (non-zero) value enables anti-alias when drawing lines and shapes. A false (zero) value disables anti-alias when drawing lines and shapes
textAntiAlias | AutoAntiAlias | The text anti-alias mode, which must be one of AutoAntiAlias, AntiAlias or NoAntiAlias.

Return Value

None


BaseChart.addTitle

BaseChart.addTitle

Usage

addTitle(text [, font [, fontSize [, fontColor [, bgColor [, edgeColor ]]]]])

Description

Adds a title at the top center of the chart.

The title is contained within a box, of which the width is the same as the width of the chart, and the height is automatically adjusted to fit the text. The box is initially invisible, but can be made visible by setting the bgColor and edgeColor.

Arguments

Argument | Default | Description
text | (Mandatory) | The text for the title. See ChartDirector Mark Up Language on how to embed special tags in the text for sophisticated formatting.
font | "" | The font used to draw the title text. The default is "bold". See Font Specification for details on various font attributes.
fontSize | 12 | The font size in points for the title text.
fontColor | TextColor | The color of the title text.
bgColor | Transparent | The background color of the title box.
edgeColor | Transparent | The border color of the title box.

Return Value

A TextBox object representing the title box. This may be used to fine-tune the appearance of the title box.


BaseChart.addTitle2

BaseChart.addTitle2

Usage

addTitle2(alignment, text [, font [, fontSize [, fontColor [, bgColor [, edgeColor ]]]]])

Description

Adds a title to the chart.

Arguments

Argument | Default | Description
alignment | (Mandatory) | The position on the title on the chart. See Alignment Specification for supported alignment types.
text | (Mandatory) | The text for the title. See ChartDirector Mark Up Language on how to embed special tags in the text for sophisticated formatting.
font | "" | The font used to draw the title text. The default is "bold". See Font Specification for details on various font attributes.
fontSize | 12 | The font size in points for the title text.
fontColor | TextColor | The color of the title text.
bgColor | Transparent | The background color of the title box.
edgeColor | Transparent | The border color of the title box.

Return Value

A TextBox object representing the title box. This may be used to fine-tune the appearance of the title box.


BaseChart.addLegend

BaseChart.addLegend

Usage

addLegend(x, y [, vertical [, font [, fontSize ]]])

Description

Adds a legend box to the chart.

The entries in the legend box will flow from top to bottom (one line per entry), or from left to right and then top to bottom (like flowing text), depending on the vertical argument. For grid layout, use BaseChart.addLegend2.

Arguments

Argument | Default | Description
x | (Mandatory) | The x coordinate of the reference point of the legend box. By default, the reference point is the top-left corner of the box, but can be configured by using TextBox.setAlignment.
y | (Mandatory) | The y coordinate of the reference point of the legend box. By default, the reference point is the top-left corner of the box, but can be configured by using TextBox.setAlignment.
vertical | true (non-zero) | A true (non-zero) value means the legend keys are laid out vertically (one line per entry). A false (zero) value means the legend keys are laid out horizontal and flow like text (from left to right, top to bottom).
font | "" | The font name of the font for drawing the legend text. The default is "normal". See Font Specification for details on various font attributes.
fontSize | 10 | The font size of the legend text.

Return Value

A LegendBox object representing the legend box. You may use this object to fine-tune the appearance of the legend box.


BaseChart.addLegend2

BaseChart.addLegend2

Usage

addLegend2(x, y, noOfCols [, font [, fontSize ]])

Description

Adds a legend box to the chart with grid layout.

In grid layout, the legend box will be divided into a table in which all cells are of of same width. The legend entries will fill the cells from left to right, top to bottom.

The number of columns can be specified using the noOfCols argument. If this argument is set to the special constant AutoGrid (= -2), the number of columns will be automatically determined based on the longest legend entry. If this argument is 0, the legend box will use a flow layout (from left to right and then top to bottom, in which the entries may not be vertically aligned).

In any case, the number of rows in the table is automatically determined so as to have enough cells for all legend entries.

Arguments

Argument | Default | Description
x | (Mandatory) | The x coordinate of the reference point of the legend box. By default, the reference point is the top-left corner of the box, but can be configured by using TextBox.setAlignment.
y | (Mandatory) | The y coordinate of the reference point of the legend box. By default, the reference point is the top-left corner of the box, but can be configured by using TextBox.setAlignment.
noOfCols | (Mandatory) | The number of columns in the legend box. The special value AutoGrid (= -2) means the number of columns is automatically determined. If this argument is 0, the legend box will use a flow layout (from left to right and then top to bottom, in which the entries may not be vertically aligned).
font | "" | The font name of the font for drawing the legend text. The default is "normal". See Font Specification for details on various font attributes.
fontSize | 10 | The font size of the legend text.

Return Value

A LegendBox object representing the legend box. You may use this object to fine-tune the appearance of the legend box.


BaseChart.getLegend

BaseChart.getLegend

Usage

getLegend()

Description

Gets the LegendBox object representing the legend box in the chart.

The LegendBox obtains using this method is not fixed. This allows you to add more keys to the legend box, and change the legend box fonts, etc. However, this also means that the legend box size (Box.getWidth and Box.getHeight) is undefined.

To obtain the width and height of the legend box, use BaseChart.layoutLegend.

Arguments

None

Return Value

The LegendBox object representing the legend box in the chart.


BaseChart.layoutLegend

BaseChart.layoutLegend

Usage

layoutLegend()

Description

Lays out and gets the LegendBox object representing the legend box in the chart.

Once the legend box has been laid out, the width and height is known and can be obtained using Box.getWidth and Box.getHeight. However, you may not perform actions that may affect the legend box sizes, such as changing the fonts or adding more data. You may still move the legend box around by using Box.setPos.

The most common use of this method is to position the legend box based on its actual size.

Arguments

None

Return Value

The LegendBox object representing the legend box in the chart.


BaseChart.getDrawArea

BaseChart.getDrawArea

Usage

getDrawArea()

Description

Retrieves the internal DrawArea object that is used to draw the chart.

The most common reason of accessing the internal DrawArea object is to add custom drawings (lines, texts, shapes, etc) to the chart.

If the custom drawings are drawn before drawing the chart image (eg. using BaseChart.makeSession, BaseChart.makeChart or BaseChart.makeChart2), the custom drawings will be at the background of the chart.

Arguments

None

Return Value

A DrawArea object that can be used to add custom text and shapes to the chart.


BaseChart.addText

BaseChart.addText

Usage

addText(x, y, text [, font [, fontSize [, fontColor [, alignment [, angle [, vertical ]]]]]])

Description

Adds a text box to the chart.

By default, only the text is visible, the box is transparent. This method returns a TextBox object that can be used to change the appearance of the text box.

Arguments

Argument | Default | Description
x | (Mandatory) | The x coordinate of the left of the text box.
y | (Mandatory) | The y coordinate of the top of the text box.
text | (Mandatory) | The text to shown in the text box. See ChartDirector Mark Up Language on how to embed special tags in the text for sophisticated formatting.
font | "" | The font used to draw the text. See Font Specification for details on various font attributes.
fontSize | 8 | The font size used to draw the text.
fontColor | TextColor | The color used to draw the text.
alignment | TopLeft | The alignment of the text within the text box. See Alignment Specification for supported alignment types.
angle | 0 | The rotation angle of the text within the text box.
vertical | false (zero) | Indicate whether the text should be laid out vertically (from top to bottom) or horizontally (from left to right).

Return Value

A TextBox object representing the text box. This may be used to fine-tune the appearance of the text box.


BaseChart.addLine

BaseChart.addLine

Usage

addLine(x1, y1, x2, y2 [, color [, lineWidth ]])

Description

Adds a line to the chart.

Arguments

Argument | Default | Description
x1 | (Mandatory) | The x coordinate of the first endpoint of the line.
y1 | (Mandatory) | The y coordinate of the first endpoint of the line.
x2 | (Mandatory) | The x coordinate of the second endpoint of the line.
y2 | (Mandatory) | The y coordinate of the second endpoint of the line.
color | LineColor | The color of the line.
lineWidth | 1 | The width of the line.

Return Value

A Line object representing the line added. You may use this object to fine- tune the appearance of the line.


BaseChart.addExtraField

BaseChart.addExtraField

Usage

addExtraField(texts)

Description

Adds an array of text to be used as an extra field in various places.

This method merely stores the data inside the chart object. The Parameter Substitution and Formatting mechanism will determine how the data are to be used.

A common use for extra fields is to specify extra information (such as a custom serial number for the data points) to be displayed on data labels or on tool tips, or to supply extra query parameters in clickable charts. All these are achieved by specifying the extra field on the data label template or image map templates during parameter substitution.

Arguments

Argument | Default | Description
texts | (Mandatory) | An array of text to be stored inside the chart object.

Return Value

None


BaseChart.addExtraField2

BaseChart.addExtraField2

Usage

addExtraField2(numbers)

Description

Adds an array of numbers/dates to be used as an extra field in various places.

This method merely stores the data inside the chart object. The Parameter Substitution and Formatting mechanism will determine how the data are to be used.

A common use for extra fields is to specify extra information (such as a custom serial number for the data points) to be displayed on data labels or on tool tips, or to supply extra query parameters in clickable charts. All these are achieved by specifying the extra field on the data label template or image map templates during parameter substitution.

Arguments

Argument | Default | Description
numbers | (Mandatory) | An array of numbers/dates to be stored inside the chart object.

Return Value

None


BaseChart.setColor

BaseChart.setColor

Usage

setColor(paletteEntry, color)

Description

Change the color at the specified position in the palette.

See Color Specification on how colors are represented in ChartDirector.

Arguments

Argument | Default | Description
paletteEntry | (Mandatory) | An index to the palette.
color | (Mandatory) | The color to change to.

Return Value

None


BaseChart.setColors

BaseChart.setColors

Usage

setColors(colors)

Description

Change the colors in the palette.

See Color Specification on how colors are represented in ChartDirector.

Arguments

Argument | Default | Description
colors | (Mandatory) | An array of colors to change to.

Return Value

None


BaseChart.setColors2

BaseChart.setColors2

Usage

setColors2(paletteEntry, colors)

Description

Change the colors in the palette, starting from the specified position in the palette.

See Color Specification on how colors are represented in ChartDirector.

Arguments

Argument | Default | Description
paletteEntry | (Mandatory) | An index to the palette to start changing the colors.
colors | (Mandatory) | An array of colors to change to.

Return Value

None


BaseChart.getColor

BaseChart.getColor

Usage

getColor(paletteEntry)

Description

Gets the color at the specified position of the palette.

See Color Specification on how colors are represented in ChartDirector.

Arguments

Argument | Default | Description
paletteEntry | (Mandatory) | An index to the palette.

Return Value

The requested color.


BaseChart.halfColor

BaseChart.halfColor

Usage

halfColor(c)

Description

Creates a color that is half the intensity of the given color.

Arguments

Argument | Default | Description
c | (Mandatory) | The given color.

Return Value

A 32-bit integer representing the half intensity color.


BaseChart.dashLineColor

BaseChart.dashLineColor

Usage

dashLineColor(color [, patternCode ])

Description

Creates a dash line color.

A dash line color is a dynamic color that switches on and off periodically. When it is used to draw a line, the line will appear as a dash line.

The style of the dash line is defined by a pattern code, which is a 4-byte integer. A value of PPQQRRSS (in hex) means the first PP pixels are turned on, followed by QQ pixels turned off, followed by RR pixels turned on, followed by SS pixels turned off, and then restart from PP again.

ChartDirector comes from several predefined constants for common dash line patterns.

Constant | Value (in Hex) | Dash Line Style
DashLine | 00000505 |
DotLine | 00000202 |
DotDashLine | 05050205 |
AltDashLine | 0A050505 |

Arguments

Argument | Default | Description
color | (Mandatory) | The color to draw the dash line.
patternCode | DashLine | A 4-byte integer representing the style of the dash line.

Return Value

A 32-bit integer representing the dash line color.


BaseChart.patternColor

BaseChart.patternColor

Usage

patternColor(colorArray, height [, startX, startY ])

Description

Creates a pattern color using an array of colors as the bitmap pattern.

A pattern color is a dynamic color that changes according to a 2D periodic pattern. When it is used to fill an area, the area will look like being tiled with a wallpaper pattern.

Arguments

Argument | Default | Description
colorArray | (Mandatory) | An array of colors representing the colors of the bitmap pixels. The color of the pixel at (x, y) should correspond to index (x + y * width - 1) of the array.
height | (Mandatory) | The height of the bitmap in pixels. (The width is automatically computed as the size of the color array divided by the height.)
startX | 0 | The x coordinate of a reference point to align with the top-left corner the pattern.
startY | 0 | The y coordinate of a reference point to align with the top-left corner the pattern.

Return Value

A 32-bit integer representing the pattern color.


BaseChart.patternColor2

BaseChart.patternColor2

Usage

patternColor2(filename [, startX, startY ])

Description

Creates a pattern color by loading the pattern from an image file.

A pattern color is a dynamic color that changes according to a 2D periodic pattern. When it is used to fill an area, the area will look like being tiled with a wallpaper pattern.

ChartDirector will automatically detect the image file format using the file extension, which must either png, jpg, jpeg, gif, wbmp or wmp (case insensitive).

Please refer to BaseChart.setSearchPath on the directory that ChartDirector will search for the file.

Arguments

Argument | Default | Description
filename | (Mandatory) | An image file providing the pattern.
startX | 0 | The x coordinate of a reference point to align with the top-left corner the pattern.
startY | 0 | The y coordinate of a reference point to align with the top-left corner the pattern.

Return Value

A 32-bit integer representing the pattern color.


BaseChart.linearGradientColor

BaseChart.linearGradientColor

Usage

linearGradientColor(startX, startY, endX, endY, startColor, endColor [, periodic ])

Description

Creates a two-point linear gradient color.

Arguments

Argument | Default | Description
startX | (Mandatory) | The x coordinate of the starting point of the reference gradient line segment.
startY | (Mandatory) | The y coordinate of the starting point of the reference gradient line segment.
endX | (Mandatory) | The x coordinate of the ending point of the reference gradient line segment.
endY | (Mandatory) | The y coordinate of the ending point of the reference gradient line segment.
startColor | (Mandatory) | The color at the starting point of the reference gradient line segment.
endColor | (Mandatory) | The color at the ending point of the reference gradient line segment.
periodic | false | Specifies whether the gradient will repeat itself periodically. If the gradient does not repeat itself, the points that lie beyond the end points of the gradient line segment will assume the colors of the end points.

Return Value

A 32-bit integer representing the linear gradient color.


BaseChart.linearGradientColor2

BaseChart.linearGradientColor2

Usage

linearGradientColor2(startX, startY, endX, endY, colorArray [, periodic ])

Description

Creates a multi-point linear gradient color.

In this method, the color points are defined as an array of positions and colors along a reference line segment, in the following format:

position0, color0, position1, color1, .... positionN, colorN

The positions are specified as a number from 0 - 256 (0 - 100 in hex), in which 0 represents the starting point of the reference line segment, and 256 (100 in hex) represents the ending point of the reference line segment.

For example, the array (in hex):

000000, FF0000, 000080, FFFF00, 000100, 00FF00

means the starting point (000000) is red (FF0000), the mid-point (000080 in hex) is yellow (FFFF00), and the ending point (000100 in hex) is green (00FF00).

One common usage of multi-point gradient colors is to define colors that have metallic look and feel. ChartDirector comes from several predefined gradient color arrays as follows.

Name | Value (in Hex)
goldGradient | 000000, FFE743, 000060, FFFFE0, 0000B0, FFF0B0, 000100, FFE743
silverGradient | 000000, C8C8C8, 000060, F8F8F8, 0000B0, E0E0E0, 000100, C8C8C8
redMetalGradient | 000000, E09898, 000060, FFF0F0, 0000B0, F0D8D8, 000100, E09898
greenMetalGradient | 000000, 98E098, 000060, F0FFF0, 0000B0, D8F0D8, 000100, 98E098
blueMetalGradient | 000000, 9898E0, 000060, F0F0FF, 0000B0, D8D8F0, 000100, 9898E0

Arguments

Argument | Default | Description
startX | (Mandatory) | The x coordinate of the starting point of the reference gradient line segment.
startY | (Mandatory) | The y coordinate of the starting point of the reference gradient line segment.
endX | (Mandatory) | The x coordinate of the ending point of the reference gradient line segment.
endY | (Mandatory) | The y coordinate of the ending point of the reference gradient line segment.
colorArray | (Mandatory) | An array defining the positions and colors of the pixels along the reference gradient line segment.
periodic | false | Specifies whether the gradient will repeat itself periodically. If the gradient does not repeat itself, the points that lie beyond the end points of the gradient line segment will assume the colors of the end points.

Return Value

A 32-bit integer representing the linear gradient color.


BaseChart.radialGradientColor

BaseChart.radialGradientColor

Usage

radialGradientColor(cx, cy, rx, ry, startColor, endColor [, periodic ])

Description

Creates a two-point radial gradient color.

Arguments

Argument | Default | Description
cx | (Mandatory) | The x coordinate of the center of the radial gradient.
cy | (Mandatory) | The y coordinate of the center of the radial gradient.
rx | (Mandatory) | The horizontal radius of the radial gradient defining ellipse.
ry | (Mandatory) | The vertical radius of the radial gradient defining ellipse.
startColor | (Mandatory) | The color at the center of the gradient defining ellipse.
endColor | (Mandatory) | The color at the perimeter of the gradient defining ellipse.
periodic | false | Specifies whether the gradient will repeat itself periodically. If the gradient does not repeat itself, the points that lie outside the gradient defining ellipse will assume the color at the perimeter of the gradient defining ellipse.

Return Value

A 32-bit integer representing the radial gradient color.


BaseChart.radialGradientColor2

BaseChart.radialGradientColor2

Usage

radialGradientColor2(cx, cy, rx, ry, colorArray [, periodic ])

Description

Creates a multi-point radial gradient color.

In this method, the color points are defined as an array of radial distances and colors, in the following format:

distance0, color0, distance1, color1, .... distanceN, colorN

The distances are specified as a number from 0 - 256 (0 - 100 in hex), in which 0 represents the center of the gradient defining ellipse, and 256 (100 in hex) represents the perimeter of the gradient defining ellipse.

For example, the array (in hex):

000000, FF0000, 000080, FFFF00, 000100, 00FF00

means the center (000000) is red (FF0000), the mid-point (000080 in hex) is yellow (FFFF00), and the perimeter (000100 in hex) is green (00FF00).

Arguments

Argument | Default | Description
cx | (Mandatory) | The x coordinate of the center of the radial gradient.
cy | (Mandatory) | The y coordinate of the center of the radial gradient.
rx | (Mandatory) | The horizontal radius of the radial gradient defining ellipse.
ry | (Mandatory) | The vertical radius of the radial gradient defining ellipse.
colorArray | (Mandatory) | An array defining the radial distances and colors.
periodic | false | Specifies whether the gradient will repeat itself periodically. If the gradient does not repeat itself, the points that lie outside the gradient defining ellipse will assume the color at the perimeter of the gradient defining ellipse.

Return Value

A 32-bit integer representing the radial gradient color.


BaseChart.gradientColor

BaseChart.gradientColor

Usage

gradientColor(startX, startY, endX, endY, startColor, endColor)

Description

Creates a two-point linear gradient color.

This method is for backward compatibility. Use BaseChart.linearGradientColor instead.

Arguments

Argument | Default | Description
startX | (Mandatory) | The x coordinate of the starting point of the reference gradient line segment.
startY | (Mandatory) | The y coordinate of the starting point of the reference gradient line segment.
endX | (Mandatory) | The x coordinate of the ending point of the reference gradient line segment.
endY | (Mandatory) | The y coordinate of the ending point of the reference gradient line segment.
startColor | (Mandatory) | The color at the starting point of the reference gradient line segment.
endColor | (Mandatory) | The color at the ending point of the reference gradient line segment.

Return Value

A 32-bit integer representing the linear gradient color.


BaseChart.gradientColor2

BaseChart.gradientColor2

Usage

gradientColor2(colorArray [, angle [, scale [, startX, startY ]]])

Description

Creates a multi-point linear gradient color.

This method is for backward compatibility. Use BaseChart.linearGradientColor2 instead.

Arguments

Argument | Default | Description
colorArray | (Mandatory) | An array defining the positions and colors of the pixels along the reference gradient line segment.
angle | 90 | The direction of the reference gradient line segment in degrees, measured clockwise, with 0 degree as the upward pointing direction. The default direction is horizontal from left to right (90 degrees).
scale | 1.0 | The scaling factor for the reference gradient line segment. By default, the reference gradient line segment is 256 pixels in length. The scaling factor can be use to stretch or compress the gradient line segment.
startX | 0 | The x coordinate of the starting point of the reference gradient line segment.
startY | 0 | The y coordinate of the starting point of the reference gradient line segment.

Return Value

A 32-bit integer representing the linear gradient color.


BaseChart.setDefaultFonts

BaseChart.setDefaultFonts

Usage

setDefaultFonts(normal [, bold [, italic [, boldItalic ]]])

Description

Sets the defaults for normal, bold, italic and bold-italic fonts.

See Font Specification for details on various font attributes.

Arguments

Argument | Default | Description
normal | (Mandatory) | The default normal font. This is the same as the first font in the font table.
bold | "" | The default bold font. This is the same as the second font in the font table. An empty string means the default is unchanged.
italic | "" | The default italic font. This is the same as the third font in the font table. An empty string means the default is unchanged.
boldItalic | "" | The default bold-italic font. This is the same as the fourth font in the font table. An empty string means the default is unchanged.

Return Value

None


BaseChart.setFontTable

BaseChart.setFontTable

Usage

setFontTable(index, font)

Description

Sets an entry in the font table to the specified font name.

The first 4 fonts in the font table have special significance. They are the defaults for normal, bold, italic and bold-italic fonts.

See Font Specification for details on various font attributes.

Arguments

Argument | Default | Description
index | (Mandatory) | An index to the font table, starting from 0.
font | (Mandatory) | The font name to be put into the font table.

Return Value

None


BaseChart.formatValue

BaseChart.formatValue

Usage

formatValue(value, formatString)

Description

Formats a number/date using the ChartDirector formatting syntax as is in Parameter Substitution and Formatting.

Arguments

Argument | Default | Description
value | (Mandatory) | The value to be formatted.
formatString | (Mandatory) | The format string, using {value} to denote the value. For example, ${value|2,} can be used to format the value to 2 decimal points, using "," as the thousand separator, and with a '$' sign in front.

Return Value

None


BaseChart.setNumberFormat

BaseChart.setNumberFormat

Usage

setNumberFormat([ thousandSeparator [, decimalPointChar [, signChar ]]])

Description

Sets the characters used for thousand separator, decimal point, and negative sign.

Arguments

Argument | Default | Description
thousandSeparator | '~' | The thousand separator. Use '~' to mean no thousand separator.
decimalPointChar | '.' | The decimal point character.
signChar | '-' | The negative sign character.

Return Value

None


BaseChart.setMonthNames

BaseChart.setMonthNames

Usage

setMonthNames(names)

Description

Sets the names of the months for date/time formatting purposes.

The default is to use the first 3 characters of the English month names (Jan, Feb, Mar ...).

Arguments

Argument | Default | Description
names | (Mandatory) | An array of 12 text strings to be used as the month names.

Return Value

None


BaseChart.setWeekDayNames

BaseChart.setWeekDayNames

Usage

setWeekDayNames(names)

Description

Sets the names of the week days for date/time formatting purposes.

The default is to use the first 3 characters of the English week day names (Sun, Mon, Tue, ...).

Arguments

Argument | Default | Description
names | (Mandatory) | An array of 7 text strings to be used as the week day names.

Return Value

None


BaseChart.setAMPM

BaseChart.setAMPM

Usage

setAMPM(am, pm)

Description

Sets the names to be used to denote morning and afternoon.

The default is to use "am" and "pm".

Arguments

Argument | Default | Description
am | (Mandatory) | The name used to denote morning.
pm | (Mandatory) | The name used to denote afternoon.

Return Value

None


BaseChart.layout

BaseChart.layout

Usage

layout()

Description

Perform auto-scaling of the axis and compute the positions of the various objects in the chart.

BaseChart.layout is automatically called when drawing the chart image (eg. using BaseChart.makeSession, BaseChart.makeChart or BaseChart.makeChart2). There is usually no need to call BaseChart.layout explicitly.

However, if you would like to add custom objects to the chart whose positions depend on the axis scales or position of other objects, you may need to call BaseChart.layout explicit to auto-scaling the axis. An example is to draw a custom label at the maximum value point of a data line.

Arguments

None

Return Value

None


BaseChart.makeChart

BaseChart.makeChart

Usage

makeChart(filename)

Description

Generates the chart image and save it into a file.

ChartDirector supports PNG, JPG, GIF, WBMP and BMP. The format used are selected based on file extension, which should be png, jpg, jpeg, gif, wbmp, wmp or bmp.

Arguments

Argument | Default | Description
filename | (Mandatory) | The name of the file to save the image.

Return Value

A true (non-zero) value indicates no error. A false (zero) value indicates the operation is unsuccessful.


BaseChart.makeChart2

BaseChart.makeChart2

Usage

makeChart2(format)

Description

Generates the chart as an image in memory.

This method is most often used to output the chart directly to an HTTP stream.

ChartDirector supports PNG, JPG, GIF, WBMP and BMP formats, denoted by the following predefined constants:

Constant | Value | Description
PNG | 0 | The PNG format.
GIF | 1 | The GIF format.
JPG | 2 | The JPEG format.
WMP | 3 | The WAP bitmap format.
BMP | 4 | The BMP format.

Arguments

Argument | Default | Description
format | (Mandatory) | A constant representing the format of the image.

Return Value

A byte array containing the binary image of the chart in the requested format.


BaseChart.makeChart3

BaseChart.makeChart3

Usage

makeChart3()

Description

Generates the chart in internal format and return a DrawArea object to allow adding custom drawings on top of the chart.

If you want to add custom drawings at the background of the chart, use the BaseChart.getDrawArea method to obtain the DrawArea instead.

After finish adding custom drawings, the resulting chart can then be output using other chart output methods.

Arguments

None

Return Value

A DrawArea object that can be used to add custom text and shapes to the chart.


BaseChart.makeSession

BaseChart.makeSession

Usage

public String makeSession(PageContext pageContext, string name [, int imageFormat ]);

Description

Generates the chart as an image and save it to a session variable.

Creating a chart in an HTML web page requires two HTTP requests. The browser first sends a request to the web server, and the web server creates the chart and returns the web page. However, the web server cannot return the chart image directly. According to HTML standard, it can only return an <IMG> tag to represent the chart image.

When the browser sees the <IMG> tag, it sends the second HTTP request to load the chart image.

Between the first and second requests, the server must find some temporarily location to store the chart image. A common method is to store it in a session variable. In this case, the <IMG> tag will contain a URL for a standard ChartDirector JSP or Servlet that returns the image in the session variable.

(An alternative is to use a temporary file instead of session variable to store the chart image. Please refer to BaseChart.makeTmpFile for details.)

The makeSession method is used to generate the chart as an image and save it to a session variable. The code will be similar to:

chart1URL = c.makeSession(GetPageContext(), "chart1");

The makeSession method returns a URL query string that can be used in the <IMG> tag as follows:

<img src="getchart.cfm?#chart1URL#">

In the above line, getchart.cfm is a standard ChartDirector CFM that retrieves the chart image from a session variable and returns it to the browser. This CFM is included in the ChartDirector distribution. You should copy it to a directory that matches with the URL in the <IMG> tag.

Arguments

Argument | Default | Description
pageContext | (Mandatory) | The PageContext object representing the current web page. This is typically obtained by using the ColdFusion "GetPageContext" function.
name | (Mandatory) | The name of the session variable used to store the chart image. If there are multiple chart images in the same web page, each image must use a different name.
imageFormat | PNG | A constant representing the format of the image. Must be one of the predefined constants PNG, JPG, GIF, BMP or WMP.

Return Value

A string representing the query parameters for retrieving the image using getchart.cfm.


BaseChart.makeTmpFile

BaseChart.makeTmpFile

Usage

makeTmpFile(dirname [, imageFormat [, lifeTime ]])

Description

Generates the chart as an image and save it to a temporary file, and automatically remove old files.

The makeTmpFile method creates the temporary file in the directory specified by dirname. To avoid building up of too many temporary files, it will automatically remove all files older than a certain life time (default 600 seconds) in that directory.

Note that makeTmpFile expects a file system path of the directory, not a URL path. You may use the ColdFusion "ExpandPath" function to translate a URL path to a file system path.

Please ensure the temporary file directory exists and is readable and writable by the web server anonymous user. ChartDirector will not create the directory. By default, most systems are configured to deny anonymous user write access to any web server directory. You may need to modify your security settings to allow "everyone" to write to the temporary file directory.

If makeTmpFile is unsuccessful, an empty string will be returned. In this case, please check that the temporary directory exists, and is readable and writable by the web server anonymous user, and "ExpandPath" has been used to map URLs to path names.

It is highly recommended you use a dedicated directory for storing temporary files created by ChartDirector. This is to avoid makeTmpFile from accidentally removing old files belonging to other applications.

Arguments

Argument | Default | Description
dirname | (Mandatory) | The directory to store the temporary file and to remove old files.
imageFormat | PNG | A constant representing the format of the image. Must be one of the predefined constants PNG, JPG, GIF, BMP or WMP.
lifeTime | 600 | The life time of files in seconds. Older files will be deleted. A negative value disables automatic temporary file removal.

Return Value

The temporary file name (not including the path), or an empty string in case of failure.


BaseChart.getHTMLImageMap

BaseChart.getHTMLImageMap

Usage

getHTMLImageMap(url [, queryFormat [, extraAttr [, offsetX, offsetY ]]])

Description

Generates an HTML image map for the chart.

This method generates an image map to represent all data points on the chart. It does not include legend box, title box or custom text box. Please use LegendBox.getHTMLImageMap or Box.getImageCoor to produce image maps for these objects.

This method should be called only after creating the chart image (eg. using BaseChart.makeSession, BaseChart.makeChart or BaseChart.makeChart2). The image map cannot be determined without creating the chart image first.

This method accepts a URL as its argument. When generating an image map, it appends query parameters to the URL to indicate which data point the user has clicked.

The following is an example image map generated for a bar chart with 3 bars.

<area shape="rect" coords="34,219,63,139" href="myurl.cfm?x=0&xLabel=Mon&dataSet=0&dataSetName=Revenue&value=100">
<area shape="rect" coords="74,219,103,119" href="myurl.cfm?x=1&xLabel=Tue&dataSet=0&dataSetName=Revenue&value=125">
<area shape="rect" coords="114,219,143,22" href="myurl.cfm?x=2&xLabel=Wed&dataSet=0&dataSetName=Revenue&value=245.78">

The image map consists of multiple <area> tags, one for each bar in the chart. In the "href" attributes, query parameters are appended to the URL to provide information on the bar clicked.

The image map produces by ChartDirector does not include the <map> and </map> tag. This is intentional so that you can add additional custom <area> tags to the image map, or append multiple image maps together.

The type of query parameters to append to the URL depends on the chart type and layer type. The default query parameters are as follows.

Chart/Layer Type | Default Query Format
Pie chart | sector={sector}&label={label}&value={value}&percent={percent}
Bar, Line, Spline, Step Line, Area and Scatter layers | x={x}&xLabel={xLabel}&dataSet={dataSet}&dataSetName={dataSetName}&value={value}
Percentage Bar and Percentage Area layers | x={x}&xLabel={xLabel}&dataSet={dataSet}&dataSetName={dataSetName}&value={value}&percent={percent}
HLOC and CandleStick layers | x={x}&xLabel={xLabel}&high={high}&low={low}&open={open}&close={close}
Box-Whisker layer | x={x}&xLabel={xLabel}&top={top}&bottom={bottom}&max={max}&min={min}&med={med}
Trend layer | dataSetName={dataSetName}
Vector layer and Polar Vector layer | x={x}&xLabel={xLabel}&dataSetName={dataSetName}&value={value}&dir={dir}&len={len}
Polar Line, Area, Spline Line and Spline Area layers | "x={x}&label={label}&name={name}&value={value}"

The texts in curly brackets (e.g. {sector}, {dataSet}, etc.) will be replaced by the actual values when generating the image map. For example, {sector} will be replaced by the sector number of the sector.

ChartDirector allows developers to modify the query parameters by using the queryFormat argument. For example, if "x={x}&v={value}" is used as the queryFormat for a XYChart, only the x position and the value of the data point will be included in query parameters.

Please refer to Parameter Substitution and Formatting on all available parameters and their meanings.

In addition to customizing the query parameters, ChartDirector supports additional HTML attributes in the <area> tags by using the extraAttr argument.

For example, the following extraAttr will add an "title" HTML attribute to every <area> tag. The attribute which will contain the x-axis label and the value of the data point. The "title" attribute will be displayed as "tool tip" when the mouse moves over the image map.

title='{xlabel}:{value}'

Another common usage of the extraAttr argument is to add "onmouseover" and "onmouseout" HTML attributes to handle user interaction using Javascript on the browser.

Arguments

Argument | Default | Description
url | (Mandatory) | The URL to be used in the "href" attribute of the image map. Parameter Substitution and Formatting is supported. Use an empty string if no href attribute is needed.
queryFormat | "" | A text string representing the template of the query parameters to be appended to the URL. Parameter Substitution and Formatting is supported. The special keyword "{default}" represents the default query parameters. This is useful for specifying appending to the default. Note that an empty string means to use the default query query parameters. To specify no query parameter, use a space character.
extraAttr | "" | A text string to specify additional attributes to add to the <area> tag. Parameter Substitution and Formatting is supported.
offsetX | 0 | An offset to be added to all x coordinates in the image map. This is useful if the current image will be shifted and inserted into another image. In this case, the image map will need to be shifted by the same offset.
offsetY | 0 | An offset to be added to all y coordinates in the image map. See offsetX above for description.

Return Value

A text string containing the image map generated.


BaseChart.getChartMetrics

BaseChart.getChartMetrics

Usage

getChartMetrics()

Description

Gets the chart metrics for passing to WebChartViewer.setChartMetrics to support view ports.

The format of the chart metrics is not published.

Arguments

None

Return Value

A text string representing the chart metrics.


MultiChart

MultiChart

The MultiChart class represents multi-chart. MultiChart is a subclass of BaseChart.

A multi-chart is a container to contain multiple charts. You can use a multi- chart to combine multiple BaseChart objects (or its subclass such as PieChart, XYChart, PolarChart, AngularMeter or LinearMeter) into one image.

Method | Inherited | Description
MultiChart | (Self) | Creates a new MultiChart object.
addChart | (Self) | Adds a BaseChart object (or its subclass such as PieChart, XYChart, PolarChart, AngularMeter or LinearMeter) into the multi-chart.
setMainChart | (Self) | Sets the chart that receives view port mouse actions (for zooming and scrolling support).
setSize | BaseChart | Sets the size of the chart.
setBackground | BaseChart | Sets the background color, border color and 3D border effect of the chart.
setRoundedFrame | BaseChart | Sets the border style of the chart to rounded corners.
setBorder | BaseChart | Sets the border color of the chart.
setWallpaper | BaseChart | Uses the image from the specified file as the wallpaper to repetitively fill the background of the chart.
setBgImage | BaseChart | Uses the image from the specified file as the background image of the chart.
setSearchPath | BaseChart | Sets the search path for loading image files.
setTransparentColor | BaseChart | Specifies a certain color to mean transparent when creating the image output, or to include alpha transparency channel in the output.
setAntiAlias | BaseChart | Controls whether anti-alias is used when drawing lines, shapes and text.
addTitle | BaseChart | Adds a title at the top center of the chart.
addTitle2 | BaseChart | Adds a title to the chart.
addLegend | BaseChart | Adds a legend box to the chart.
addLegend2 | BaseChart | Adds a legend box to the chart with grid layout.
getLegend | BaseChart | Gets the LegendBox object representing the legend box in the chart.
layoutLegend | BaseChart | Lays out and gets the LegendBox object representing the legend box in the chart.
getDrawArea | BaseChart | Retrieves the internal DrawArea object that is used to draw the chart.
addText | BaseChart | Adds a text box to the chart.
addLine | BaseChart | Adds a line to the chart.
addExtraField | BaseChart | Adds an array of text to be used as an extra field in various places.
addExtraField2 | BaseChart | Adds an array of numbers/dates to be used as an extra field in various places.
setColor | BaseChart | Change the color at the specified position in the palette.
setColors | BaseChart | Change the colors in the palette.
setColors2 | BaseChart | Change the colors in the palette, starting from the specified position in the palette.
getColor | BaseChart | Gets the color at the specified position of the palette.
halfColor | BaseChart | Creates a color that is half the intensity of the given color.
dashLineColor | BaseChart | Creates a dash line color.
patternColor | BaseChart | Creates a pattern color using an array of colors as the bitmap pattern.
patternColor2 | BaseChart | Creates a pattern color by loading the pattern from an image file.
linearGradientColor | BaseChart | Creates a two-point linear gradient color.
linearGradientColor2 | BaseChart | Creates a multi-point linear gradient color.
radialGradientColor | BaseChart | Creates a two-point radial gradient color.
radialGradientColor2 | BaseChart | Creates a multi-point radial gradient color.
gradientColor | BaseChart | Creates a two-point linear gradient color.
gradientColor2 | BaseChart | Creates a multi-point linear gradient color.
setDefaultFonts | BaseChart | Sets the defaults for normal, bold, italic and bold-italic fonts.
setFontTable | BaseChart | Sets an entry in the font table to the specified font name.
formatValue | BaseChart | Formats a number/date using the ChartDirector formatting syntax as is in Parameter Substitution and Formatting.
setNumberFormat | BaseChart | Sets the characters used for thousand separator, decimal point, and negative sign.
setMonthNames | BaseChart | Sets the names of the months for date/time formatting purposes.
setWeekDayNames | BaseChart | Sets the names of the week days for date/time formatting purposes.
setAMPM | BaseChart | Sets the names to be used to denote morning and afternoon.
layout | BaseChart | Perform auto-scaling of the axis and compute the positions of the various objects in the chart.
makeChart | BaseChart | Generates the chart image and save it into a file.
makeChart2 | BaseChart | Generates the chart as an image in memory.
makeChart3 | BaseChart | Generates the chart in internal format and return a DrawArea object to allow adding custom drawings on top of the chart.
makeSession | BaseChart | Generates the chart as an image and save it to a session variable.
makeTmpFile | BaseChart | Generates the chart as an image and save it to a temporary file, and automatically remove old files.
getHTMLImageMap | BaseChart | Generates an HTML image map for the chart.
getChartMetrics | BaseChart | Gets the chart metrics for passing to WebChartViewer.setChartMetrics to support view ports.


MultiChart.MultiChart

MultiChart.MultiChart

Usage

MultiChart(width, height [, bgColor [, edgeColor [, raisedEffect ]]])

Description

Creates a new MultiChart object.

Note: In the ColdFusion edition of ChartDirector, the MultiChart constructor is implemented as a method of the ChartDirector.CFChart object called ChartDirector.CFChart.MultiChart.

Arguments

Argument | Default | Description
width | (Mandatory) | The width of the chart in pixels.
height | (Mandatory) | The height of the chart in pixels.
bgColor | BackgroundColor | The background color of the chart.
edgeColor | Transparent | The edge color of the chart.
raisedEffect | 0 | The 3D border width. For positive values, the border will appear raised. For negative values, the border will appear depressed. A zero value means the border will appear flat.

Return Value

The MultiChart object created.


MultiChart.addChart

MultiChart.addChart

Usage

addChart(x, y, c)

Description

Adds a BaseChart object (or its subclass such as PieChart, XYChart, PolarChart, AngularMeter or LinearMeter) into the multi-chart.

Arguments

Argument | Default | Description
x | (Mandatory) | The x coordinate of a point in the multi-chart that is to align with the top-left corner of the added BaseChart.
y | (Mandatory) | The y coordinate of a point in the multi-chart that is to align with the top-left corner of the added BaseChart.
c | (Mandatory) | The BaseChart object to be added to the multi-chart.

Return Value

None


MultiChart.setMainChart

MultiChart.setMainChart

Usage

setMainChart(c)

Description

Sets the chart that receives view port mouse actions (for zooming and scrolling support).

Arguments

Argument | Default | Description
c | (Mandatory) | The chart that is to receive view port mouse actions.

Return Value

None


LegendBox

LegendBox

The class LegendBox represents legend boxes. It is a subclass of TextBox.

Use BaseChart.addLegend or BaseChart.addLegend2 to add legend boxes to charts.

By default, ChartDirector will add named data representation to the legend box. For pie charts, named sectors (sectors that have text labels) will be added. For xy charts, named data sets will be added. For polar charts, named layers will be added.

You may add custom entries to the legend box by using LegendBox.addKey or LegendBox.addKey2.

To control the ordering of the legend entries, ChartDirector employs a legend entry priority system. Each entry is given a priority number, and the entries are ordered according to ascending priority (unless reversed by using LegendBox.setReverse).

For a PieChart, the legend entry priority of a sector is 10000 x (sector_index + 1). The Nth sector has sector_index (N - 1). That means the ordering of the sectors in the legend box is the same as the data array.

For an XYChart, the base legend entry priority for a layer is 10000 x (layer_index + 1). Within a layer, the data set priority is 10 x (data_set_index + 1). For example, the legend entry priority for the 5th dataset in the 3rd layer will be 30050. That means the ordering of the data sets in the legend box follows the order in which the layers are created. For data sets within the same layer, the ordering follows the order in which the data sets are added. The ordering can be modified by using Layer.setLegendOrder.

For an PolarChart, the legend entry priority of a layer is 10000 x (layer_index + 1). That means the ordering of the layers in the legend box follows the order in which the layers are created.

For custom entries added using LegendBox.addKey2, you may control the legend entry priority. That means you may insert custom entries anywhere relative to the automatic entries added by ChartDirector.

Method | Inherited | Description
addKey | (Self) | Adds a custom entry to the legend box.
addKey2 | (Self) | Adds a custom entry to the legend box with a given legend entry priority.
setCols | (Self) | Sets the number of columns in the legend box.
setReverse | (Self) | Reverses the ordering of the legend entries.
setText | (Self) | Sets the template of the legend text.
setKeySize | (Self) | Sets the size of the legend icon and its distance from the legend text.
setKeySpacing | (Self) | Sets the distance between two legend entries.
setKeyBorder | (Self) | Sets the default border color of the legend icon.
getImageCoor2 | (Self) | Gets the image map coordinates of an legend entry as HTML image map attributes.
getHTMLImageMap | (Self) | Generates an HTML image map for the legend box.
setFontStyle | TextBox | Sets the font of the text by specifying the file that contains the font.
setFontSize | TextBox | Sets the font height and width in points.
setFontAngle | TextBox | Sets the rotation angle and layout direction of the text.
setFontColor | TextBox | Sets the color of the text.
setAlignment | TextBox | Sets the alignment of the text relative to the container box.
setWidth | TextBox | Sets the width of the text box and wraps text if necessary.
setHeight | TextBox | Sets the height of the text box.
setMaxWidth | TextBox | Sets the maximum width of the text box and wraps text if necessary.
setTruncate | TextBox | Sets the maximum number of lines in the text box, and truncate the text if it exceeds the line count.
setMargin | TextBox | Sets all margins (left, right, top, and bottom) of the text box to the same value.
setMargin2 | TextBox | Sets the margins of the text box in pixels.
setPos | Box | Sets the coordinates of the top-left corner of the box.
setSize | Box | Sets the width and height of the box.
setBackground | Box | Sets the background color, border color and 3D border effect of the box.
setRoundedCorners | Box | Sets the border style to use rounded corners.
getWidth | Box | Gets the width of the box.
getHeight | Box | Gets the height of the box.
getImageCoor | Box | Gets the image map coordinates of the box as HTML image map attributes.
setZOrder | Box | Sets the z-order (drawing order) for custom box objects.


LegendBox.addKey

LegendBox.addKey

Usage

addKey(text, color [, lineWidth [, drawarea ]])

Description

Adds a custom entry to the legend box.

This method adds an entry within a legend entry priority of 1 (followed by 2, 3, 4, ... for repeated calls). This has higher priority than entries added automatically by ChartDirector for representing data sets. As a result, by default, the custom entry will appear before the automatic entries.

To control the order of the custom entry relative to the automatic entries, use LegendBox.addKey2.

See LegendBox for more information on legend entry priority system.

Arguments

Argument | Default | Description
text | (Mandatory) | The text of the legend entry.
color | (Mandatory) | The icon color of the legend entry.
lineWidth | 0 | The line width for legend entry that represents lines in line charts.
drawarea | [Null] | A DrawArea containing the data symbol represents the legend entry. This is primarily used for legend entries in line charts with data symbols, or in scatter charts.

Return Value

None


LegendBox.addKey2

LegendBox.addKey2

Usage

addKey2(pos, text, color [, lineWidth [, drawarea ]])

Description

Adds a custom entry to the legend box with a given legend entry priority.

See LegendBox for more information on legend entry priority system.

Arguments

Argument | Default | Description
pos | (Mandatory) | The legend entry priority
text | (Mandatory) | The text of the legend entry.
color | (Mandatory) | The icon color of the legend entry.
lineWidth | 0 | The line width for legend entry that represents lines in line charts.
drawarea | [Null] | A DrawArea containing the data symbol represents the legend entry. This is primarily used for legend entries in line charts with data symbols, or in scatter charts.

Return Value

None


LegendBox.setCols

LegendBox.setCols

Usage

setCols(noOfCols)

Description

Sets the number of columns in the legend box.

Arguments

Argument | Default | Description
noOfCols | (Mandatory) | The number of columns in the legend box. The special value AutoGrid (= -2) means the number of columns is automatically determined. If this argument is 0, the legend box will use a flow layout (from left to right and then top to bottom, in which the entries may not be vertically aligned).

Return Value

None


LegendBox.setReverse

LegendBox.setReverse

Usage

setReverse([ b ])

Description

Reverses the ordering of the legend entries.

By default, the legend entries are ordered based on ascending legend entry priority number. This method can be used to change the ordering to following descending legend entry priority number instead.

See LegendBox for more information on legend entry priority system.

Arguments

Argument | Default | Description
b | true (non-zero) | A true (non-zero) value means the legend entries are ordered based on descending legend entry priority number. false (zero) value means the legend entries are ordered based on ascending legend entry priority number.

Return Value

None


LegendBox.setText

LegendBox.setText

Usage

setText(text)

Description

Sets the template of the legend text.

The default template is "{dataSetName}", which means the name of the data set will be used as the legend text.

The legend key text can be modified to include other information. For example, in a pie chart, "{label}: {value}" means the legend text will consist of the sector label followed by the sector value.

Please refer to Parameter Substitution and Formatting on all available parameters and how to format them.

Arguments

Argument | Default | Description
text | (Mandatory) | The legend text template.

Return Value

None


LegendBox.setKeySize

LegendBox.setKeySize

Usage

setKeySize(width [, height [, gap ]])

Description

Sets the size of the legend icon and its distance from the legend text.

Each legend entry consists of an icon and a text description. By default, the size of the icon and its distance from the text is determined automatically based on font size. This method can be used to override the default.

Arguments

Argument | Default | Description
width | (Mandatory) | The width of the legend icon in pixels.
height | -1 | The height of the legend icon in pixels. -1 means the height is automatically determined.
gap | -1 | The distance between the legend icon and the legend text in pixels. -1 means the distance is automatically determined.

Return Value

None


LegendBox.setKeySpacing

LegendBox.setKeySpacing

Usage

setKeySpacing(keySpacing [, lineSpacing ])

Description

Sets the distance between two legend entries.

In horizontal legend layout, the legend entries will flow from left to right, top to bottom, with a horizontal gap between two legend entries. In vertical legend layout, the legend entries will flow from top to bottom, with one entry per line.

By default, the horizontal gap and the line spacing is automatically determined based on font size. This method can be used to set the horizontal gap and line spacing in pixels.

Arguments

Argument | Default | Description
keySpacing | (Mandatory) | The horizontal gap between two legend entries for horizontal legend layout, expressed in pixels.
lineSpacing | -1 | The line spacing between two lines in the legend box, expressed in pixels. -1 means the line spacing is automatically determined.

Return Value

None


LegendBox.setKeyBorder

LegendBox.setKeyBorder

Usage

setKeyBorder(edgeColor [, raisedEffect ])

Description

Sets the default border color of the legend icon.

This method applies only to data sets of which the icons are rectangles showing the colors of the data sets. If the icon is a shape or symbol (such as for a line with data point symbols), the border color of the original shape or symbol is always used.

Arguments

Argument | Default | Description
edgeColor | (Mandatory) | The border color.
raisedEffect | 0 | The 3D border width. For positive values, the border will appear raised. For negative values, the border will appear depressed. A zero value means the border will appear flat. This argument is also used to support ChartDirector.CFChart.glassEffect and ChartDirector.CFChart.softLighting effects.

Return Value

None


LegendBox.getImageCoor2

LegendBox.getImageCoor2

Usage

getImageCoor2(dataItem [, offsetX, offsetY ])

Description

Gets the image map coordinates of an legend entry as HTML image map attributes.

The image map coordinates will be of the following format:

shape="rect" cords="[x1],[y1],[x2],[y2]"

where (x1, y1) and (x2, y2) are opposite corners of the box that enclosed the legend entry. The format is specially designed so that it can easily be included into HTML image maps.

This method should be called only after creating the chart image (eg. using BaseChart.makeSession, BaseChart.makeChart or BaseChart.makeChart2). The image map cannot be determined without creating the chart image first.

Arguments

Argument | Default | Description
dataItem | (Mandatory) | The legend entry number, starting from 0. The first legend entry is 0. The nth legend entry is (n-1).
offsetX | 0 | An offset to be added to all x coordinates in the image map. This is useful if the current image will be shifted and inserted into another image. In this case, the image map will need to be shifted by the same offset.
offsetY | 0 | An offset to be added to all y coordinates in the image map. See offsetX above for description.

Return Value

A text string representing the coordinates of the legend entry in HTML image map attribute format.


LegendBox.getHTMLImageMap

LegendBox.getHTMLImageMap

Usage

getHTMLImageMap(url [, queryFormat [, extraAttr [, offsetX, offsetY ]]])

Description

Generates an HTML image map for the legend box.

This method should be called only after creating the chart image (eg. using BaseChart.makeSession, BaseChart.makeChart or BaseChart.makeChart2). The image map cannot be determined without creating the chart image first.

This method accepts a URL as its argument. When generating an image map, it appends query parameters to the URL to indicate which legend entry the user has clicked.

The following is an example image map generated for a legend box with 3 entries.

<area shape="rect" coords="310,20,375,33" href='test.asp?dataSet=0&dataSetName=Web'>
<area shape="rect" coords="310,36,377,49" href='test.asp?dataSet=1&dataSetName=Email'>
<area shape="rect" coords="310,52,377,65" href='test.asp?dataSet=2&dataSetName=FTP'>

The image map consists of multiple <area> tags, one for each legend entry. In the "href" attributes, query parameters are appended to the URL to provide information on the entry clicked.

The image map produces by ChartDirector does not include the <map> and </map> tag. This is intentional so that you can add additional custom <area> tags to the image map, or append multiple image maps together.

The format of the appended URL parameters is determined using the queryFormat argument, which by default is:

dataSet={dataSet}&dataSetName={dataSetName}

The texts in curly brackets (i.e. {dataSet}, {dataSetName}) will be replaced by the actual values when generating the image map. For example, {dataSetName} will be replaced by the name of the data set.

Please refer to Parameter Substitution and Formatting on all available parameters and how to format them.

In addition to customizing the query parameters, ChartDirector supports additional HTML attributes in the <area> tags using the extraAttr argument.

For example, the following extraAttr will add an "title" HTML attribute to every <area> tag. The "title" attribute will be displayed as "tool tip" when the mouse moves over the image map.

title='Click me for details on {dataSetName}'

Another common usage of the extraAttr argument is to add "onmouseover" and "onmouseout" HTML attributes to handle user interaction using Javascript on the browser.

Arguments

Argument | Default | Description
url | (Mandatory) | The URL to be used in the "href" attribute of the image map. Parameter Substitution and Formatting is supported. Use an empty string if no href attribute is needed.
queryFormat | "" | A text string representing the template of the query parameters to be appended to the URL. Parameter Substitution and Formatting is supported. The special keyword "{default}" represents the default query parameters. This is useful for specifying appending to the default. Note that an empty string means to use the default query query parameters. To specify no query parameter, use a space character.
extraAttr | "" | A text string to specify additional attributes to add to the <area> tag. Parameter Substitution and Formatting is supported.
offsetX | 0 | An offset to be added to all x coordinates in the image map. This is useful if the current image will be shifted and inserted into another image. In this case, the image map will need to be shifted by the same offset.
offsetY | 0 | An offset to be added to all y coordinates in the image map. See offsetX above for description.

Return Value

A text string containing the image map generated.


PieChart

PieChart

The PieChart class represents pie charts. It is a subclass of BaseChart. In ChartDirector, pie charts includes donut charts.

Method | Inherited | Description
PieChart | (Self) | Creates a new PieChart object.
setPieSize | (Self) | Sets the position and size of the pie in the pie chart.
setDonutSize | (Self) | Sets the position and size of the donut in the donut chart.
set3D | (Self) | Adds 3D effects to the pie.
set3D2 | (Self) | Adds 3D effects to the pie, where each sector can have a different 3D depth.
setStartAngle | (Self) | Sets the angle of the first sector in the pie and the layout direction for the sectors.
setExplode | (Self) | Explode a sector from the pie.
setExplodeGroup | (Self) | Explode a group of sectors from the pie.
setLabelStyle | (Self) | Sets the style used to draw all sector labels.
setLabelFormat | (Self) | Sets the format of the all sector labels.
setLabelLayout | (Self) | Sets the layout method and location of the sector labels.
setLabelPos | (Self) | Sets the circular label layout method, and configure the join lines used to connect the sector labels to the sector perimeter.
setJoinLine | (Self) | Sets the color and width of the join lines used to connect the sector labels to the sector perimeter.
setLineColor | (Self) | Sets the sector edge color and join line color.
setData | (Self) | Sets the data used to draw the pie chart.
sector | (Self) | Retrieves the Sector object representing a single sector in the pie chart.
setSize | BaseChart | Sets the size of the chart.
setBackground | BaseChart | Sets the background color, border color and 3D border effect of the chart.
setRoundedFrame | BaseChart | Sets the border style of the chart to rounded corners.
setBorder | BaseChart | Sets the border color of the chart.
setWallpaper | BaseChart | Uses the image from the specified file as the wallpaper to repetitively fill the background of the chart.
setBgImage | BaseChart | Uses the image from the specified file as the background image of the chart.
setSearchPath | BaseChart | Sets the search path for loading image files.
setTransparentColor | BaseChart | Specifies a certain color to mean transparent when creating the image output, or to include alpha transparency channel in the output.
setAntiAlias | BaseChart | Controls whether anti-alias is used when drawing lines, shapes and text.
addTitle | BaseChart | Adds a title at the top center of the chart.
addTitle2 | BaseChart | Adds a title to the chart.
addLegend | BaseChart | Adds a legend box to the chart.
addLegend2 | BaseChart | Adds a legend box to the chart with grid layout.
getLegend | BaseChart | Gets the LegendBox object representing the legend box in the chart.
layoutLegend | BaseChart | Lays out and gets the LegendBox object representing the legend box in the chart.
getDrawArea | BaseChart | Retrieves the internal DrawArea object that is used to draw the chart.
addText | BaseChart | Adds a text box to the chart.
addLine | BaseChart | Adds a line to the chart.
addExtraField | BaseChart | Adds an array of text to be used as an extra field in various places.
addExtraField2 | BaseChart | Adds an array of numbers/dates to be used as an extra field in various places.
setColor | BaseChart | Change the color at the specified position in the palette.
setColors | BaseChart | Change the colors in the palette.
setColors2 | BaseChart | Change the colors in the palette, starting from the specified position in the palette.
getColor | BaseChart | Gets the color at the specified position of the palette.
halfColor | BaseChart | Creates a color that is half the intensity of the given color.
dashLineColor | BaseChart | Creates a dash line color.
patternColor | BaseChart | Creates a pattern color using an array of colors as the bitmap pattern.
patternColor2 | BaseChart | Creates a pattern color by loading the pattern from an image file.
linearGradientColor | BaseChart | Creates a two-point linear gradient color.
linearGradientColor2 | BaseChart | Creates a multi-point linear gradient color.
radialGradientColor | BaseChart | Creates a two-point radial gradient color.
radialGradientColor2 | BaseChart | Creates a multi-point radial gradient color.
gradientColor | BaseChart | Creates a two-point linear gradient color.
gradientColor2 | BaseChart | Creates a multi-point linear gradient color.
setDefaultFonts | BaseChart | Sets the defaults for normal, bold, italic and bold-italic fonts.
setFontTable | BaseChart | Sets an entry in the font table to the specified font name.
formatValue | BaseChart | Formats a number/date using the ChartDirector formatting syntax as is in Parameter Substitution and Formatting.
setNumberFormat | BaseChart | Sets the characters used for thousand separator, decimal point, and negative sign.
setMonthNames | BaseChart | Sets the names of the months for date/time formatting purposes.
setWeekDayNames | BaseChart | Sets the names of the week days for date/time formatting purposes.
setAMPM | BaseChart | Sets the names to be used to denote morning and afternoon.
layout | BaseChart | Perform auto-scaling of the axis and compute the positions of the various objects in the chart.
makeChart | BaseChart | Generates the chart image and save it into a file.
makeChart2 | BaseChart | Generates the chart as an image in memory.
makeChart3 | BaseChart | Generates the chart in internal format and return a DrawArea object to allow adding custom drawings on top of the chart.
makeSession | BaseChart | Generates the chart as an image and save it to a session variable.
makeTmpFile | BaseChart | Generates the chart as an image and save it to a temporary file, and automatically remove old files.
getHTMLImageMap | BaseChart | Generates an HTML image map for the chart.
getChartMetrics | BaseChart | Gets the chart metrics for passing to WebChartViewer.setChartMetrics to support view ports.


PieChart.PieChart

PieChart.PieChart

Usage

PieChart(width, height [, bgColor [, edgeColor [, raisedEffect ]]])

Description

Creates a new PieChart object.

Note: In the ColdFusion edition of ChartDirector, the PieChart constructor is implemented as a method of the ChartDirector.CFChart object called ChartDirector.CFChart.PieChart.

Arguments

Argument | Default | Description
width | (Mandatory) | The width of the chart in pixels.
height | (Mandatory) | The height of the chart in pixels.
bgColor | BackgroundColor | The background color of the chart.
edgeColor | Transparent | The edge color of the chart.
raisedEffect | 0 | The 3D border width. For positive values, the border will appear raised. For negative values, the border will appear depressed. A zero value means the border will appear flat.

Return Value

The PieChart object created.


PieChart.setPieSize

PieChart.setPieSize

Usage

setPieSize(x, y, r)

Description

Sets the position and size of the pie in the pie chart.

Arguments

Argument | Default | Description
x | (Mandatory) | The x coordinate of the pie center.
y | (Mandatory) | The y coordinate of the pie center.
r | (Mandatory) | The radius of the pie.

Return Value

None


PieChart.setDonutSize

PieChart.setDonutSize

Usage

setDonutSize(x, y, r, r2)

Description

Sets the position and size of the donut in the donut chart.

Arguments

Argument | Default | Description
x | (Mandatory) | The x coordinate of the donut center.
y | (Mandatory) | The y coordinate of the donut center.
r | (Mandatory) | The inner radius of the donut.
r2 | (Mandatory) | The outer radius of the donut.

Return Value

None


PieChart.set3D

PieChart.set3D

Usage

set3D([ depth [, angle [, shadowMode ]]])

Description

Adds 3D effects to the pie.

Arguments

Argument | Default | Description
depth | -1 | The 3D depth of the pie in pixels. -1 means the depth is automatically determined.
angle | -1 | The 3D view angle in degrees. Must be 0 - 90 for standard 3D mode, and 0 - 360 in shadow 3D mode. -1 means the angle is automatically determined.
shadowMode | false (zero) | Flag to indicate whether the pie is in standard 3D or shadow 3D mode. A true (non-zero) value means shadow 3D mode. A false (zero) value means standard 3D mode.

Return Value

None


PieChart.set3D2

PieChart.set3D2

Usage

set3D2(depths [, angle [, shadowMode ]])

Description

Adds 3D effects to the pie, where each sector can have a different 3D depth.

Arguments

Argument | Default | Description
depths | (Mandatory) | An array of integers representing the 3D depths for the sectors.
angle | 45 | The 3D view angle in degrees. Must be 0 - 90 for standard 3D mode, and 0 - 360 in shadow 3D mode. -1 means the angle is automatically determined.
shadowMode | false (zero) | Flag to indicate whether the pie is in standard 3D or shadow 3D mode. A true (non-zero) value means shadow 3D mode. A false (zero) value means standard 3D mode.

Return Value

None


PieChart.setStartAngle

PieChart.setStartAngle

Usage

setStartAngle(startAngle [, clockWise ])

Description

Sets the angle of the first sector in the pie and the layout direction for the sectors.

By default, the start angle is 0 degree (the upward pointing direction), and subsequent sectors are drawn clockwise.

Arguments

Argument | Default | Description
startAngle | (Mandatory) | The angle to start drawing the first sector in degrees. The angle is measured from the upward pointing direction in the clockwise direction.
clockWise | true (non-zero) | Flag to control the layout direction of the sectors. A true (non-zero) value means clockwise. A false (zero) value means anti-clockwise.

Return Value

None


PieChart.setExplode

PieChart.setExplode

Usage

setExplode(sectorNo [, distance ])

Description

Explode a sector from the pie.

Arguments

Argument | Default | Description
sectorNo | (Mandatory) | The sector number of the sector to be exploded from the pie, starting from 0. The first sector is 0. The nth sector is (n - 1).
distance | -1 | The explosion distance in pixels. -1 means the distance is automatically determined.

Return Value

None


PieChart.setExplodeGroup

PieChart.setExplodeGroup

Usage

setExplodeGroup(startSector, endSector [, distance ])

Description

Explode a group of sectors from the pie.

Arguments

Argument | Default | Description
startSector | (Mandatory) | The sector number of the first sector in the sector group to be exploded. The first sector is 0. The nth sector is (n - 1).
endSector | (Mandatory) | The sector number of the last sector in the sector group to be exploded. The first sector is 0. The nth sector is (n - 1).
distance | -1 | The explosion distance in pixels. -1 means the distance is automatically determined.

Return Value

None


PieChart.setLabelStyle

PieChart.setLabelStyle

Usage

setLabelStyle([ font [, fontSize [, fontColor ]]])

Description

Sets the style used to draw all sector labels.

This method affects all sectors. To set the label style for one particular sector only, use Sector.setLabelStyle.

See Font Specification for details on various font attributes.

Arguments

Argument | Default | Description
font | "" | The font used to draw the sector labels.
fontSize | 8 | The font size in points.
fontColor | TextColor | The text color for the sector labels.

Return Value

A TextBox object representing the prototype of the obj. This may be used to fine-tune the appearance of the obj.


PieChart.setLabelFormat

PieChart.setLabelFormat

Usage

setLabelFormat(formatString)

Description

Sets the format of the all sector labels.

This method affects all sectors. To set the label format for one particular sector only, use Sector.setLabelFormat.

The default sector label format depends on the label layout method used (see PieChart.setLabelLayout).

Label Layout Method Default Label Format
Circular Layout
{label}<*br*>{percent}%

(The "<*br*>" above is the CDML syntax for a line break.)
Side Layout
{label} ({percent}%)

Please refer to Parameter Substitution and Formatting on all available parameters and how to format them.

Arguments

Argument | Default | Description
formatString | (Mandatory) | The format string.

Return Value

None


PieChart.setLabelLayout

PieChart.setLabelLayout

Usage

setLabelLayout(layoutMethod [, pos [, topBound [, bottomBound ]]])

Description

Sets the layout method and location of the sector labels.

This method affects all sectors. To set the sector label layout method and location for one particular sector only, use Sector.setLabelLayout.

ChartDirector supports two sector label layout methods - circular layout and side layout. The layout method is determined using the layoutMethod argument, which must be one of the following predefined constants.

Constant | Value | Description
SideLayout | 0 | Side Label Layout
CircleLayout | 1 | Circular Label Layout

In the circular layout method, the sector labels are positioned around the perimeter of the pie.

In the side layout method, there is an invisible rectangle containing the pie, where the rectangle can be wider than the diameter of the pie.The sector labels are positioned on the left and right sides outside the rectangle. Because the labels can be quite far away from the sectors, join lines are typically used to connect the labels to the sectors.

The circular layout method usually uses less space and is the default layout method. However, if the pie chart contains a lot of small sectors, the labels may overlap with each others, due to insufficient space on the pie perimeter to position the labels.

The side layout method has the advantages that it can avoid label overlapping. In the side layout method, labels will automatically shift up and down to avoid overlapping.

One common issue in pie charts is the data contain a lot of small sectors. If the data are sorted, the small sectors will be crowded together instead of distributed evenly. Although the side layout method can avoid label overlapping by shifting the labels up and down, some labels may need to be shifted great distances.

Label layout can often be improved if the small sectors are near the horizontal axis. It is because the amount of vertical label space for a sector is greatest at the horizontal axis. This can be achieved by choosing an appropriate start angle (using PieChart.setStartAngle).

If the data is in ascending order (small sectors crowded at the beginning), a start angle of 45 degrees with clockwise sector layout is recommended. With this setting, the first few sectors (the smallest sectors) will be at around 45 - 135 degrees, so is near the horizontal axis (90 degrees). Similarly, if the data is in descending order (small sectors crowded at the end), a start angle of 135 degrees with clockwise sector layout can be used.

Arguments

Argument | Default | Description
layoutMethod | (Mandatory) | Specify the layout method. Must be one of the predefined constants CircleLayout or SideLayout.
pos | -1 | For circular layout, it is the distance between the sector perimeter and the sector label. A negative value (but not -1) means the sector label will be drawn in the interior of the sector. For side layout, it is the distance between the pie perimeter and the left or right edges of the invisible containing rectangle (equal to the width of the rectangle minus the pie diameter and then divided by 2). In either case, -1 means the distance is automatically determined.
topBound | -1 | This parameter applies only to side label layout. It controls the top bound of the labels (the minimum y coordinate), thereby limiting the extent that the labels can be shifted up to avoid overlapping. This parameter is typically used avoid the labels from moving up too much and overlap with other chart objects (such as the chart title).
bottomBound | -1 | This parameter applies only to side label layout. It controls the bottom bound of the labels (the maximum y coordinate), thereby limiting the extent which the labels can be shifted down to avoid overlapping. This parameter is typically used to avoid the labels from moving down too much and overlap with other chart objects.

Return Value

None


PieChart.setLabelPos

PieChart.setLabelPos

Usage

setLabelPos(pos [, joinLineColor ])

Description

Sets the circular label layout method, and configure the join lines used to connect the sector labels to the sector perimeter.

This method affects all sectors. To set the sector label position or join line color for one particular sector only, use Sector.setLabelPos.

Arguments

Argument | Default | Description
pos | (Mandatory) | The distance between the sector perimeter and the sector label. A negative value means the sector label will be drawn in the interior of the sector.
joinLineColor | -1 | The color of the line that joins the sector perimeter with the sector label. The default is Transparent. The join line is ignored if the sector label is inside the sector.

Return Value

None


PieChart.setJoinLine

PieChart.setJoinLine

Usage

setJoinLine(joinLineColor [, joinLineWidth ])

Description

Sets the color and width of the join lines used to connect the sector labels to the sector perimeter.

This method affects all sectors. To set the color and width of the join line for one particular sector only, use Sector.setJoinLine.

By default, for circular label layout, the join line color is Transparent. For side label layout, the join line color is SameAsMainColor.

Arguments

Argument | Default | Description
joinLineColor | (Mandatory) | The color of the line that joins the sector perimeter with the sector label.
joinLineWidth | 1 | The line width of the join line.

Return Value

None


PieChart.setLineColor

PieChart.setLineColor

Usage

setLineColor(edgeColor [, joinLineColor ])

Description

Sets the sector edge color and join line color.

This method affects all sectors. To set the sector label position and join line color for one particular sector, use Sector.setColor.

Arguments

Argument | Default | Description
edgeColor | (Mandatory) | The colors for the edges of the sectors. By default, the edge color is SameAsMainColor, which means the edge color is the same as the fill color of the sector, and the sector will appear borderless.
joinLineColor | -1 | The color of the line that join the sector perimeter with the sector label. By default, for circular label layout, the join line color is Transparent. For side label layout, the join line color is SameAsMainColor.

Return Value

None


PieChart.setData

PieChart.setData

Usage

setData(data [, labels ])

Description

Sets the data used to draw the pie chart.

Arguments

Argument | Default | Description
data | (Mandatory) | An array of numbers representing the data points.
labels | [Empty_Array] | An array of text strings representing the labels of the sectors. An empty array means no sector label.

Return Value

None


PieChart.sector

PieChart.sector

Usage

sector(sectorNo)

Description

Retrieves the Sector object representing a single sector in the pie chart.

Arguments

Argument | Default | Description
sectorNo | (Mandatory) | The sector number of the sector to retrieve, starting from 0. The first sector is 0. The nth sector is (n-1).

Return Value

The requested Sector object.


Sector

Sector

The Sector class represents sectors. The Sector object is obtained using PieChart.sector.

Method | Inherited | Description
setExplode | (Self) | Explode the sector.
setLabelStyle | (Self) | Sets the style used to draw the sector label.
setLabelFormat | (Self) | Sets the format of the sector label.
setLabelLayout | (Self) | Sets the layout method and location of the sector label.
setLabelPos | (Self) | Sets the circular label layout method, and configure the join lines used to connect the sector label to the sector perimeter.
setJoinLine | (Self) | Sets the color and width of the join line used to connect the sector label to the sector perimeter.
setColor | (Self) | Sets the fill color, edge color and join line color of the sector.
getImageCoor | (Self) | Gets the image map coordinates of the sector as HTML image map attributes.
getLabelCoor | (Self) | Gets the image map coordinates of the sector label as HTML image map attributes.


Sector.setExplode

Sector.setExplode

Usage

setExplode([ distance ])

Description

Explode the sector.

Arguments

Argument | Default | Description
distance | -1 | The explosion distance in pixels. -1 means the distance is automatically determined.

Return Value

None


Sector.setLabelStyle

Sector.setLabelStyle

Usage

setLabelStyle([ font [, fontSize [, fontColor ]]])

Description

Sets the style used to draw the sector label.

To set the label style for all sector labels, use PieChart.setLabelStyle.

See Font Specification for details on various font attributes.

Arguments

Argument | Default | Description
font | "" | The font used to draw the sector label.
fontSize | 8 | The font size in points.
fontColor | TextColor | The text color for the sector label.

Return Value

A TextBox object representing the prototype of the obj. This may be used to fine-tune the appearance of the obj.


Sector.setLabelFormat

Sector.setLabelFormat

Usage

setLabelFormat(formatString)

Description

Sets the format of the sector label.

To set the label format for all sectors, use PieChart.setLabelFormat.

Arguments

Argument | Default | Description
formatString | (Mandatory) | The format string. See PieChart.setLabelFormat for details.

Return Value

None


Sector.setLabelLayout

Sector.setLabelLayout

Usage

setLabelLayout(layoutMethod [, pos ])

Description

Sets the layout method and location of the sector label.

To set the sector label layout method and location for all sectors, use PieChart.setLabelLayout.

ChartDirector supports two sector label layout methods - circular layout and side layout. For detail descriptions, please refer to PieChart.setLabelLayout.

Arguments

Argument | Default | Description
layoutMethod | (Mandatory) | Specify the layout method. Must be one of the predefined constants CircleLayout or SideLayout.
pos | -1 | For circular layout, it is the distance between the sector perimeter and the sector label. A negative value (but not -1) means the sector label will be drawn in the interior of the sector. For side layout, it is the distance between the pie perimeter and the left or right edges of the invisible containing rectangle (equal to the width of the rectangle minus the pie diameter and then divided by 2). In either case, -1 means the distance is automatically determined.

Return Value

None


Sector.setLabelPos

Sector.setLabelPos

Usage

setLabelPos(pos [, joinLineColor ])

Description

Sets the circular label layout method, and configure the join lines used to connect the sector label to the sector perimeter.

To set the sector label position or join line color for all sectors, use PieChart.setLabelPos.

Arguments

Argument | Default | Description
pos | (Mandatory) | The distance between the sector perimeter and the sector label. A negative value means the sector label will be drawn in the interior of the sector.
joinLineColor | -1 | The color of the line that joins the sector perimeter with the sector label. The default is Transparent. The join line is ignored if the sector label is inside the sector.

Return Value

None


Sector.setJoinLine

Sector.setJoinLine

Usage

setJoinLine(joinLineColor [, joinLineWidth ])

Description

Sets the color and width of the join line used to connect the sector label to the sector perimeter.

To set the color and width of the join line for all sectors, use PieChart.setJoinLine.

By default, for circular label layout, the join line color is Transparent. For side label layout, the join line color is SameAsMainColor.

Arguments

Argument | Default | Description
joinLineColor | (Mandatory) | The color of the line that joins the sector perimeter with the sector label.
joinLineWidth | 1 | The line width of the join line.

Return Value

None


Sector.setColor

Sector.setColor

Usage

setColor(color [, edgeColor [, joinLineColor ]])

Description

Sets the fill color, edge color and join line color of the sector.

By default, the edge color is SameAsMainColor. For the join line color, if the circular label layout method is used, the default is Transparent, otherwise the default is SameAsMainColor.

Arguments

Argument | Default | Description
color | (Mandatory) | The color of the sector.
edgeColor | -1 | The edge color of the sector. -1 means the color is unchanged.
joinLineColor | -1 | The color of the line that join the sector perimeter with the sector label. -1 means the color is unchanged.

Return Value

None


Sector.getImageCoor

Sector.getImageCoor

Usage

getImageCoor([ offsetX, offsetY ])

Description

Gets the image map coordinates of the sector as HTML image map attributes.

The image map coordinates will be in the following format:

shape="poly" cords="[x1],[y1],[x2],[y2] ..."

where (x1, y1), (x2, y2) ... are vertices of a polygon that approximate the sector. The format is specially designed so that it can easily be incorporated into HTML image maps.

This method should be called only after creating the chart image (eg. using BaseChart.makeSession, BaseChart.makeChart or BaseChart.makeChart2). The image map cannot be determined without creating the chart image first.

Arguments

Argument | Default | Description
offsetX | 0 | An offset to be added to all x coordinates in the image map. This is useful if the current image will be shifted and inserted into another image. In this case, the image map will need to be shifted by the same offset.
offsetY | 0 | An offset to be added to all y coordinates in the image map. See offsetX above for description.

Return Value

A text string representing the coordinates of the sector in HTML image map attribute format.


Sector.getLabelCoor

Sector.getLabelCoor

Usage

getLabelCoor([ offsetX, offsetY ])

Description

Gets the image map coordinates of the sector label as HTML image map attributes.

The image map coordinates will be in the following format:

shape="rect" cords="[x1],[y1],[x2],[y2]"

where (x1, y1) and (x2, y2) are opposite corners of the box that encloses the sector label. The format is specially designed so that it can easily be incorporated into HTML image maps.

This method should be called only after creating the chart image (eg. using BaseChart.makeSession, BaseChart.makeChart or BaseChart.makeChart2). The image map cannot be determined without creating the chart image first.

Arguments

Argument | Default | Description
offsetX | 0 | An offset to be added to all x coordinates in the image map. This is useful if the current image will be shifted and inserted into another image. In this case, the image map will need to be shifted by the same offset.
offsetY | 0 | An offset to be added to all y coordinates in the image map. See offsetX above for description.

Return Value

A text string representing the coordinates of the sector label in HTML image map attribute format.


XYChart

XYChart

The XYChart class represents XY charts. The XYChart class is a subclass of BaseChart.

Method | Inherited | Description
XYChart | (Self) | Creates a new XYChart object.
yAxis | (Self) | Retrieves the Axis object representing the primary y-axis of the XYChart.
yAxis2 | (Self) | Retrieves the Axis object representing secondary y-axis of the XYChart.
syncYAxis | (Self) | Sets a linear formula to synchronize the secondary y-axis scale to the primary y-axis scale.
setYAxisOnRight | (Self) | Interchange the position of the primary y-axis and the secondary y-axis.
xAxis | (Self) | Retrieves the Axis object representing primary x-axis of the XYChart.
xAxis2 | (Self) | Retrieves the Axis object representing secondary x-axis of the XYChart.
setXAxisOnTop | (Self) | Interchange the position of the primary x-axis and the secondary x-axis.
setAxisAtOrigin | (Self) | Sets the chart into 4 quadrant mode. The axes may intersect at origin inside the plot area (as opposed to at the border of the plot area).
addAxis | (Self) | Adds an additional axis to the chart.
swapXY | (Self) | Swap the position of the x and y axes, so the x-axes will become vertical, and the y-axes will become horizontal.
setPlotArea | (Self) | Sets the position, size, background colors, edge color and grid colors of the plot area.
setClipping | (Self) | Enables clipping on the plot area.
setTrimData | (Self) | Uses only a subset of the data series to draw charts.
addBarLayer | (Self) | Adds a bar layer to the XYChart, and specify the data set to use for drawing the bars.
addBarLayer2 | (Self) | Adds an empty bar layer to the XYChart.
addBarLayer3 | (Self) | Adds a multi-color bar layer to the XYChart, and specify the data set to use for drawing the bars.
addLineLayer | (Self) | Adds a line layer to the XYChart, and specify the data set to use for drawing the line.
addLineLayer2 | (Self) | Adds an empty line layer to the XYChart.
addSplineLayer | (Self) | Adds a spline layer to the XYChart.
addStepLineLayer | (Self) | Adds a step line chart layer to the XYChart.
addTrendLayer | (Self) | Adds a trend chart layer to the XYChart, and specify the data set to use for drawing the trend line.
addTrendLayer2 | (Self) | Adds a trend chart layer to the XYChart, and specify the x and y values for drawing the trend line.
addInterLineLayer | (Self) | Adds an inter-line layer the XYChart. An inter-line layer is used to fill the region between any two lines (straight lines, spline curves, step lines, etc).
addScatterLayer | (Self) | Adds a scatter chart layer to the XYChart.
addAreaLayer | (Self) | Adds an area chart layer to the XYChart, and specify the data set to use for drawing the area.
addAreaLayer2 | (Self) | Adds an empty area chart layer to the XYChart.
addBoxWhiskerLayer | (Self) | Adds a box-whisker layer to the XYChart, and specify the data sets to use for drawing the layer.
addBoxWhiskerLayer2 | (Self) | Adds a multi-color box-whisker layer to the XYChart, and specify the data sets to use for drawing the layer.
addBoxLayer | (Self) | Adds a floating box layer to the XYChart, and specify the data sets to use for drawing the layer.
addVectorLayer | (Self) | Adds a vector layer to the chart.
addHLOCLayer | (Self) | Adds a high-low-open-close (HLOC) layer to the XYChart, and specify the data sets to use for drawing the layer.
addHLOCLayer2 | (Self) | Adds an empty high-low-open-close (HLOC) layer to the XYChart.
addHLOCLayer3 | (Self) | Adds a multi-color high-low-open-close (HLOC) layer to the XYChart, and specify the data sets to use for drawing the layer.
addCandleStickLayer | (Self) | Adds a candlestick layer to the XYChart, and specify the data sets to use for drawing the layer.
getXCoor | (Self) | Gets the x pixel coordinate of a point given the x data value.
getYCoor | (Self) | Gets the y pixel coordinate of a point given the y data value.
xZoneColor | (Self) | Creates a x-zone color. A x-zone will change from one color to another depending on a threshold value on the x-axis.
yZoneColor | (Self) | Creates a y-zone color. A y-zone will change from one color to another depending on a threshold value on the y-axis.
setSize | BaseChart | Sets the size of the chart.
setBackground | BaseChart | Sets the background color, border color and 3D border effect of the chart.
setRoundedFrame | BaseChart | Sets the border style of the chart to rounded corners.
setBorder | BaseChart | Sets the border color of the chart.
setWallpaper | BaseChart | Uses the image from the specified file as the wallpaper to repetitively fill the background of the chart.
setBgImage | BaseChart | Uses the image from the specified file as the background image of the chart.
setSearchPath | BaseChart | Sets the search path for loading image files.
setTransparentColor | BaseChart | Specifies a certain color to mean transparent when creating the image output, or to include alpha transparency channel in the output.
setAntiAlias | BaseChart | Controls whether anti-alias is used when drawing lines, shapes and text.
addTitle | BaseChart | Adds a title at the top center of the chart.
addTitle2 | BaseChart | Adds a title to the chart.
addLegend | BaseChart | Adds a legend box to the chart.
addLegend2 | BaseChart | Adds a legend box to the chart with grid layout.
getLegend | BaseChart | Gets the LegendBox object representing the legend box in the chart.
layoutLegend | BaseChart | Lays out and gets the LegendBox object representing the legend box in the chart.
getDrawArea | BaseChart | Retrieves the internal DrawArea object that is used to draw the chart.
addText | BaseChart | Adds a text box to the chart.
addLine | BaseChart | Adds a line to the chart.
addExtraField | BaseChart | Adds an array of text to be used as an extra field in various places.
addExtraField2 | BaseChart | Adds an array of numbers/dates to be used as an extra field in various places.
setColor | BaseChart | Change the color at the specified position in the palette.
setColors | BaseChart | Change the colors in the palette.
setColors2 | BaseChart | Change the colors in the palette, starting from the specified position in the palette.
getColor | BaseChart | Gets the color at the specified position of the palette.
halfColor | BaseChart | Creates a color that is half the intensity of the given color.
dashLineColor | BaseChart | Creates a dash line color.
patternColor | BaseChart | Creates a pattern color using an array of colors as the bitmap pattern.
patternColor2 | BaseChart | Creates a pattern color by loading the pattern from an image file.
linearGradientColor | BaseChart | Creates a two-point linear gradient color.
linearGradientColor2 | BaseChart | Creates a multi-point linear gradient color.
radialGradientColor | BaseChart | Creates a two-point radial gradient color.
radialGradientColor2 | BaseChart | Creates a multi-point radial gradient color.
gradientColor | BaseChart | Creates a two-point linear gradient color.
gradientColor2 | BaseChart | Creates a multi-point linear gradient color.
setDefaultFonts | BaseChart | Sets the defaults for normal, bold, italic and bold-italic fonts.
setFontTable | BaseChart | Sets an entry in the font table to the specified font name.
formatValue | BaseChart | Formats a number/date using the ChartDirector formatting syntax as is in Parameter Substitution and Formatting.
setNumberFormat | BaseChart | Sets the characters used for thousand separator, decimal point, and negative sign.
setMonthNames | BaseChart | Sets the names of the months for date/time formatting purposes.
setWeekDayNames | BaseChart | Sets the names of the week days for date/time formatting purposes.
setAMPM | BaseChart | Sets the names to be used to denote morning and afternoon.
layout | BaseChart | Perform auto-scaling of the axis and compute the positions of the various objects in the chart.
makeChart | BaseChart | Generates the chart image and save it into a file.
makeChart2 | BaseChart | Generates the chart as an image in memory.
makeChart3 | BaseChart | Generates the chart in internal format and return a DrawArea object to allow adding custom drawings on top of the chart.
makeSession | BaseChart | Generates the chart as an image and save it to a session variable.
makeTmpFile | BaseChart | Generates the chart as an image and save it to a temporary file, and automatically remove old files.
getHTMLImageMap | BaseChart | Generates an HTML image map for the chart.
getChartMetrics | BaseChart | Gets the chart metrics for passing to WebChartViewer.setChartMetrics to support view ports.


XYChart.XYChart

XYChart.XYChart

Usage

XYChart(width, height [, bgColor [, edgeColor [, raisedEffect ]]])

Description

Creates a new XYChart object.

Note: In the ColdFusion edition of ChartDirector, the XYChart constructor is implemented as a method of the ChartDirector.CFChart object called ChartDirector.CFChart.XYChart.

Arguments

Argument | Default | Description
width | (Mandatory) | The width of the chart in pixels.
height | (Mandatory) | The height of the chart in pixels.
bgColor | BackgroundColor | The background color of the chart.
edgeColor | Transparent | The edge color of the chart.
raisedEffect | 0 | The 3D border width. For positive values, the border will appear raised. For negative values, the border will appear depressed. A zero value means the border will appear flat.

Return Value

The XYChart object created.


XYChart.yAxis

XYChart.yAxis

Usage

yAxis()

Description

Retrieves the Axis object representing the primary y-axis of the XYChart.

By default, the primary y-axis is the y-axis on the left side of the plot area (bottom side if XYChart.swapXY is in effect), and the secondary y-axis is on the right side of the plot area (top side if XYChart.swapXY is in effect). You may interchange their positions using XYChart.setYAxisOnRight.

Arguments

None

Return Value

The Axis object representing the primary y-axis of the XYChart.


XYChart.yAxis2

XYChart.yAxis2

Usage

yAxis2()

Description

Retrieves the Axis object representing secondary y-axis of the XYChart.

By default, the primary y-axis is the y-axis on the left side of the plot area (bottom side if XYChart.swapXY is in effect), and the secondary y-axis is on the right side of the plot area (top side if XYChart.swapXY is in effect). You may interchange their positions using XYChart.setYAxisOnRight.

Arguments

None

Return Value

The Axis object representing the secondary y-axis of the XYChart.


XYChart.syncYAxis

XYChart.syncYAxis

Usage

syncYAxis([ slope [, intercept ]])

Description

Sets a linear formula to synchronize the secondary y-axis scale to the primary y-axis scale.

The formula is in the format:

y2 = y1 * slope + intercept

This method is usually used if the two y-axes represent the same measurement using different units. Examples including temperature in Celsius and in Fahrenheit, and length in meters and feet.

Arguments

Argument | Default | Description
slope | 1 | The slope parameter for the formula linking the secondary y-axis to the primary y-axis.
intercept | 0 | The intercept parameter for the formula linking the secondary y-axis to the primary y-axis.

Return Value

None


XYChart.setYAxisOnRight

XYChart.setYAxisOnRight

Usage

setYAxisOnRight([ b ])

Description

Interchange the position of the primary y-axis and the secondary y-axis.

By default, the primary y-axis is the y-axis on the left side of the plot area (bottom side if XYChart.swapXY is in effect), and the secondary y-axis is on the right side of the plot area (top side if XYChart.swapXY is in effect). This method can be used to interchange their positions.

Arguments

Argument | Default | Description
b | true (non-zero) | A true (non-zero) value means to interchange the positions of the primary and secondary y-axes. A false (zero) value means using the default positions for the primary and secondary y-axes.

Return Value

None


XYChart.xAxis

XYChart.xAxis

Usage

xAxis()

Description

Retrieves the Axis object representing primary x-axis of the XYChart.

By default, the primary x-axis is the x-axis on the bottom side of the plot area (left side if XYChart.swapXY is in effect), and the secondary x-axis is on the top side of the plot area (right side if XYChart.swapXY is in effect). You may interchange their positions using XYChart.setXAxisOnTop.

Arguments

None

Return Value

The Axis object representing the primary x-axis of the XYChart.


XYChart.xAxis2

XYChart.xAxis2

Usage

xAxis2()

Description

Retrieves the Axis object representing secondary x-axis of the XYChart.

By default, the primary x-axis is the x-axis on the bottom side of the plot area (left side if XYChart.swapXY is in effect), and the secondary x-axis is on the top side of the plot area (right side if XYChart.swapXY is in effect). You may interchange their positions using XYChart.setXAxisOnTop.

Arguments

None

Return Value

The Axis object representing the secondary x-axis of the XYChart.


XYChart.setXAxisOnTop

XYChart.setXAxisOnTop

Usage

setXAxisOnTop([ b ])

Description

Interchange the position of the primary x-axis and the secondary x-axis.

By default, the primary x-axis is the x-axis on the bottom side of the plot area (left side if XYChart.swapXY is in effect), and the secondary x-axis is on the top side of the plot area (right side if XYChart.swapXY is in effect). This method can be used to interchange their positions.

Arguments

Argument | Default | Description
b | true (non-zero) | A true (non-zero) value means to interchange the positions of the primary and secondary x-axes. A false (zero) value means using the default positions for the primary and secondary x-axes.

Return Value

None


XYChart.setAxisAtOrigin

XYChart.setAxisAtOrigin

Usage

setAxisAtOrigin([ originMode [, symmetryMode ]])

Description

Sets the chart into 4 quadrant mode. The axes may intersect at origin inside the plot area (as opposed to at the border of the plot area).

By default, ChartDirector puts the axes at the border of the plot area. This ensures the axes and the axes labels will not block the contents of the plot area.

However, in some cases, it may be desirable for the axes to intersect at the origin. The axes may need to move inside the plot area.

ChartDirector allows you to move the primary x-axis and/or y-axis to so that they intersect with the zero point of the other axis. The following constants represent different possibilities:

Constant | Value | Description
XAxisAtOrigin | 1 | Move the x-axis so that it will intersect with the zero point of the y-axis, if that point exists.
YAxisAtOrigin | 2 | Move the y-axis so that it will intersect with the zero point of the x-axis, if that point exists.
XYAxisAtOrigin | 3 | Move the x-axis so that it will intersect with the zero point of the y-axis, if that point exists. Move the y-axis so that it will intersect with the zero point of the x-axis, if that point exists.

In addition to ensure the axes intersects at the origin, ChartDirector allows you to control if the axes are symmetrical about the origin with the following flags. Multiple flags can be specified by "or" them together.

Constant | Value | Description
XAxisSymmetric | 1 | Adjust the x-axis so that it becomes symmetrical about the zero point, that is, the positive and negative part of the x-axis will be of the same length.
XAxisSymmetricIfNeeded | 2 | Adjust the x-axis will be symmetrical about the zero point if the axis scale needs both positive and negative values.
YAxisSymmetric | 4 | Adjust the y-axis so that it becomes symmetrical about the zero point, that is, the positive and negative part of the y-axis will be of the same length.
YAxisSymmetricIfNeeded | 8 | Adjust the y-axis will be symmetrical about the zero point if the axis scale needs both positive and negative values.
XYAxisSymmetric | 16 | Adjust the x-axes and y-axes so that they become symmetrical about the zero point. The positive and negative parts of the x-axes and the y-axes will all be of the same length.
XYAxisSymmetricIfNeeded | 32 | Adjust the x-axes and y-axes so that they become symmetrical about the zero point. However, if an axis does not need both positive and negative values, it will not be adjusted.

Arguments

Argument | Default | Description
originMode | XYAxisAtOrigin | predefined constants to determine which axis needs to move to intersect with the zero point of the other axis.
symmetryMode | 0 | Flags to determine if the axes need to be symmetrical about the origin.

Return Value

None


XYChart.addAxis

XYChart.addAxis

Usage

addAxis(align, offset)

Description

Adds an additional axis to the chart.

By default, ChartDirector XY charts have 2 x-axes and 2 y-axes at the 4 borders of the plot area. The addAxis method can be used to create additional axis.

The new axis will be put at one of the 4 borders of the plot area. To avoid overlapping with existing axis, the new axis will not be put exactly as the plot area border, but at an offset from it.

Arguments

Argument | Default | Description
align | (Mandatory) | Specifies which side of the plot area is the primary side of the axis. Must be one of the constants Left, Right, Top and Bottom for the 4 sides of the plot area.
offset | (Mandatory) | An offset in pixels to move the axis away from the plot area. If a negative value is used, it will mean to move the axis into the plot area.

Return Value

The Axis object representing the new axis added.


XYChart.swapXY

XYChart.swapXY

Usage

swapXY([ b ])

Description

Swap the position of the x and y axes, so the x-axes will become vertical, and the y-axes will become horizontal.

After swapping the x and y axes, the charts will appear rotated. For example, the bars in a bar chart will become horizontal instead of vertical, and the area in a stacked area chart will grow from left to right (instead of bottom to top).

Arguments

Argument | Default | Description
b | true (non-zero) | A true (non-zero) value means the x and y axes will be swapped. A false (zero) value means the x and y axes not be swapped.

Return Value

None


XYChart.setPlotArea

XYChart.setPlotArea

Usage

setPlotArea(x, y, width, height [, bgColor [, altBgColor [, edgeColor [, hGridColor [, vGridColor ]]]]])

Description

Sets the position, size, background colors, edge color and grid colors of the plot area.

Arguments

Argument | Default | Description
x | (Mandatory) | The x coordinate of the left of the plot area.
y | (Mandatory) | The y coordinate of the top of the plot area.
width | (Mandatory) | The width of the plot area in pixels.
height | (Mandatory) | The height of the plot area in pixels.
bgColor | Transparent | The background color of the plot area.
altBgColor | -1 | The second background color of the plot area. -1 means there is no second background color. If there is a second background color, the two background colors will be used alternatively as horizontal bands on the background grid.
edgeColor | -1 | The border color of the plot area. -1 means to use the default, which is LineColor. However, if the axes are configured in 4 quadrant mode (see XYChart.setAxisAtOrigin), the default will change to Transparent.
hGridColor | C0C0C0 | The horizontal grid color.
vGridColor | Transparent | The vertical grid color.

Return Value

A PlotArea object representing the plot area.


XYChart.setClipping

XYChart.setClipping

Usage

setClipping([ margin ])

Description

Enables clipping on the plot area.

In normal usage, ChartDirector will auto-scale the axis to ensure all the data points will be within the plot area.

However, if manual scaling is used (e.g. using Axis.setLinearScale), it is possible to choose an axis scale such that some data points will be outside the plot area. So some of the data representation (bars, lines, etc) will be outside the plot area.

This method can be used to clip the plot area, so that any data representation that is outside the plot area will not be drawn.

Arguments

Argument | Default | Description
margin | 0 | Additional margin, measured in pixels, to be added to the 4 sides of the plot area for the purpose of clipping. A positive value means the clipping region will be larger than the plot area. A negative value means the clipping region will be smaller than the plot area. The default value of 0 means the clipping region is equal to the plot area.

Return Value

None


XYChart.setTrimData

XYChart.setTrimData

Usage

setTrimData(startPos [, len ])

Description

Uses only a subset of the data series to draw charts.

In finance charts, "lead data" are commonly needed to plot technical indicators. For example, to show a 20-days moving average line for 30 days, one needs 50 days of data. It is because computing 20-days moving average requires 20 days of "lead data". The setTrimData method is a convenience method for trimming off these "lead data" so they will not appear on the chart.

Arguments

Argument | Default | Description
startPos | (Mandatory) | The index for the first data position to use for plotting charts.
len | 7FFFFFFF | The length of the data points used for plotting charts.

Return Value

None


XYChart.addBarLayer

XYChart.addBarLayer

Usage

addBarLayer(data [, color [, name [, depth ]]])

Description

Adds a bar layer to the XYChart, and specify the data set to use for drawing the bars.

Arguments

Argument | Default | Description
data | (Mandatory) | An array of numbers representing the data set.
color | -1 | The color to draw the bars. -1 means that the color is automatically selected from the palette.
name | "" | The name of the data set. The name will be used in the legend box, if one is available. An empty string means the data set has no name.
depth | 0 | The 3D depth of the bar layer.

Return Value

A BarLayer object representing the bar layer created.


XYChart.addBarLayer2

XYChart.addBarLayer2

Usage

addBarLayer2([ dataCombineMethod [, depth ]])

Description

Adds an empty bar layer to the XYChart.

This method is typically used to add multiple data sets to a single bar layer. First an empty bar layer is created, then the data sets can be added using Layer.addDataSet.

The dataCombineMethod parameter specifies how to combine the data sets together in the bar layer. The followings methods are supported:

Constant | Value | Description
Side | 3 | The data sets are combined by plotting the bars side by side.
Stack | 1 | The data sets are combined by stacking up the bar segments.
Overlay | 0 | The data sets are combined similar to stacked bars. However, in Overlay, one data set is assumed to already include the other data set. For example, if the data sets are "average" and "peak", the "peak" cannot be stacked on top of "average", because the "peak" already contains "average". In the Overlay style, only "peak - average" is stacked on top of "average", and so the total bar length will be "peak".
Percentage | 4 | The data sets are combined similar to stacked bars, except that the data in a bar are scaled so that they summed to 100. In other words, all stacked bars will be of the same length. A bar segment within a bar represents the percentage of the data item relative to sum of all the data items in the stacked bar.

Arguments

Argument | Default | Description
dataCombineMethod | Side | The method to combine the data sets together in the bar layer.
depth | 0 | The 3D depth of the bar layer.

Return Value

A BarLayer object representing the bar layer created.


XYChart.addBarLayer3

XYChart.addBarLayer3

Usage

addBarLayer3(data [, colors [, names [, depth ]]])

Description

Adds a multi-color bar layer to the XYChart, and specify the data set to use for drawing the bars.

A multi-color bar layer is a bar layer in which each bar has a different color. In a normal bar layer, each data set has a different color, but the bars in the same data set have the same color.

Arguments

Argument | Default | Description
data | (Mandatory) | An array of numbers representing the data set.
colors | [Empty_Array] | An array of colors to draw the bars. An empty array means the colors are automatically selected from the palette.
names | [Empty_Array] | An array of text strings as the names of the bars. The names will be used in the legend box, if one is available. An empty array means that bars have no name.
depth | 0 | The 3D depth of the bar layer.

Return Value

A BarLayer object representing the bar layer created.


XYChart.addLineLayer

XYChart.addLineLayer

Usage

addLineLayer(data [, color [, name [, depth ]]])

Description

Adds a line layer to the XYChart, and specify the data set to use for drawing the line.

Arguments

Argument | Default | Description
data | (Mandatory) | An array of numbers representing the data set.
color | -1 | The color to draw the line. -1 means that the color is automatically selected from the palette.
name | "" | The name of the data set. The name will be used in the legend box, if one is available. An empty string means the data set has no name.
depth | 0 | The 3D depth of the line layer.

Return Value

A LineLayer object representing the line layer created.


XYChart.addLineLayer2

XYChart.addLineLayer2

Usage

addLineLayer2([ dataCombineMethod [, depth ]])

Description

Adds an empty line layer to the XYChart.

This method is typically used to add multiple data sets to a single line layer. First an empty line layer is created, then the data sets can be added using Layer.addDataSet.

Arguments

Argument | Default | Description
dataCombineMethod | Overlay | In this version of ChartDirector, this parameter is ignored.
depth | 0 | The 3D depth of the line layer.

Return Value

A LineLayer object representing the line layer created.


XYChart.addSplineLayer

XYChart.addSplineLayer

Usage

addSplineLayer([ data [, color [, name ]]])

Description

Adds a spline layer to the XYChart.

In a spline layer, the data points are connected together using cardinal spline curves (as opposed to straight lines). The "tension" of the curve can be configured using SplineLayer.setTension.

Arguments

Argument | Default | Description
data | [Empty_Array] | An array of numbers representing the data set.
color | -1 | The color to draw the spline line. -1 means that the color is automatically selected from the palette.
name | "" | The name of the data set. The name will be used in the legend box, if one is available. An empty string means the data set has no name.

Return Value

A SplineLayer object representing the spline layer created.


XYChart.addStepLineLayer

XYChart.addStepLineLayer

Usage

addStepLineLayer([ data [, color [, name ]]])

Description

Adds a step line chart layer to the XYChart.

In a step line layer, the data points are connected together using steps. The alignment of the steps relative to the data points can be configured using StepLineLayer.setAlignment.

Arguments

Argument | Default | Description
data | [Empty_Array] | An array of numbers representing the data set.
color | -1 | The color to draw the step line. -1 means that the color is automatically selected from the palette.
name | "" | The name of the data set. The name will be used in the legend box, if one is available. An empty string means the data set has no name.

Return Value

A StepLineLayer object representing the step line layer created.


XYChart.addTrendLayer

XYChart.addTrendLayer

Usage

addTrendLayer(data [, color [, name [, depth ]]])

Description

Adds a trend chart layer to the XYChart, and specify the data set to use for drawing the trend line.

Arguments

Argument | Default | Description
data | (Mandatory) | An array of numbers representing the data set.
color | -1 | The color to draw the line. -1 means that the color is automatically selected from the palette.
name | "" | The name of the data set. The name will be used in the legend box, if one is available. An empty string means the data set has no name.
depth | 0 | The 3D depth of the line layer.

Return Value

A TrendLayer object representing the trend layer created.


XYChart.addTrendLayer2

XYChart.addTrendLayer2

Usage

addTrendLayer2(xData, yData [, color [, name [, depth ]]])

Description

Adds a trend chart layer to the XYChart, and specify the x and y values for drawing the trend line.

Arguments

Argument | Default | Description
xData | (Mandatory) | An array of numbers representing the x values of the data points.
yData | (Mandatory) | An array of numbers representing the y values of the data points.
color | -1 | The color to draw the line. -1 means that the color is automatically selected from the palette.
name | "" | The name of the data set. The name will be used in the legend box, if one is available. An empty string means the data set has no name.
depth | 0 | The 3D depth of the line layer.

Return Value

A TrendLayer object representing the trend layer created.


XYChart.addInterLineLayer

XYChart.addInterLineLayer

Usage

addInterLineLayer(line1, line2, color12 [, color21 ])

Description

Adds an inter-line layer the XYChart. An inter-line layer is used to fill the region between any two lines (straight lines, spline curves, step lines, etc).

This method expects two "line" objects representing the two lines. The line objects can be obtained using LineLayer.getLine (inherited by SplineLayer and StepLineLayer), TrendLayer.getLine, and Mark.getLine.

Arguments

Argument | Default | Description
line1 | (Mandatory) | An opaque line object representing the first line.
line2 | (Mandatory) | An opaque line object representing the second line.
color12 | (Mandatory) | The color used to fill the region of the lines when line1 > line2.
color21 | -1 | The color used to fill the region of the lines when line2 > line1. -1 means this color is the same as color12.

Return Value

An InterLineLayer object representing the inter-line layer created.


XYChart.addScatterLayer

XYChart.addScatterLayer

Usage

addScatterLayer(xData, yData [, name [, symbol [, symbolSize [, fillColor [, edgeColor ]]]]])

Description

Adds a scatter chart layer to the XYChart.

A scatter chart can be considered as a special configuration of a line chart, in the data symbols are enabled and the line width is set to zero. Therefore only the data symbols are visible and the chart appears as scattered.

Arguments

Argument | Default | Description
xData | (Mandatory) | An array of numbers representing the x values of the data points. If no explicit x coordinates are used in the chart (eg. using an enumerated x-axis), an empty array may be used for this argument.
yData | (Mandatory) | An array of numbers representing the y values of the data points.
name | "" | The name of the data set. The name will be used in the legend box, if one is available. An empty string means the data set has no name.
symbol | SquareShape | One of the predefined symbol constants to specify the symbol to use. (See Shape Specification for available built-in shapes.)
symbolSize | 5 | The width and height of the symbol in pixels.
fillColor | -1 | The color used to fill the symbol. -1 means that the color is automatically selected from the palette.
edgeColor | -1 | The edge color used to draw the edge of the symbol. The default value of -1 means using LineColor as the edge color.

Return Value

A ScatterLayer object representing the scatter layer created.


XYChart.addAreaLayer

XYChart.addAreaLayer

Usage

addAreaLayer(data [, color [, name [, depth ]]])

Description

Adds an area chart layer to the XYChart, and specify the data set to use for drawing the area.

Arguments

Argument | Default | Description
data | (Mandatory) | An array of numbers representing the data set.
color | -1 | The color to draw the area. -1 means that the color is automatically selected from the color palette.
name | "" | The name of the data set. The name will be used in the legend box, if one is available. An empty string means the data set has no name.
depth | 0 | The 3D depth of the area layer.

Return Value

An AreaLayer object representing the area layer created.


XYChart.addAreaLayer2

XYChart.addAreaLayer2

Usage

addAreaLayer2([ dataCombineMethod [, depth ]])

Description

Adds an empty area chart layer to the XYChart.

This method is typically used to add multiple data sets to a single bar layer. First an empty area chart layer is created, then the data sets can be added using Layer.addDataSet.

The dataCombineMethod parameter specifies how to combine the data sets together in the area layer. The followings methods are supported:

Constant | Value | Description
Stack | 1 | The data sets are combined by stacking up the areas.
Percentage | 4 | The data sets are combined similar to stacked area, except that the data are scaled so that the area always stacked up to 100. An area strip within the stacked area therefore represents the percentage of the data item relative to sum of all the data items in the stacked area.

Arguments

Argument | Default | Description
dataCombineMethod | Stack | The method to combine the data sets together in the area layer.
depth | 0 | The 3D depth of the area layer.

Return Value

An AreaLayer object representing the area layer created.


XYChart.addBoxWhiskerLayer

XYChart.addBoxWhiskerLayer

Usage

addBoxWhiskerLayer(boxTop, boxBottom [, maxData [, minData [, midData [, fillColor [, whiskerColor [, edgeColor ]]]]]])

Description

Adds a box-whisker layer to the XYChart, and specify the data sets to use for drawing the layer.

Traditionally, each box-whisker symbol represents 5 values, which are the as maximum, 3rd quartile, median, 1st quartile and minimum of some data samples.

A vertical box-whisker symbol (on a non-swapped XY chart) consists of a vertical line joining the maximum and minimum points, a box extending from the 1st quartile point to the 3rd quartile point, and 3 horizontal mark lines at the maximum, median and minimum points.

In practice, the box-whisker symbol is not limited to representing the maximum, 3rd quartile, median, 1st quartile and minimum values. It can be used to represent any ordered values.

The boxTop and boxBottom data sets specifies the top and bottom edges of the box. The maxData, minData and midData specifies the top, bottom and middle mark lines.

You can use empty arrays to disable showing some parts of the box-whisker symbol.

For example, if you just want to show a floating box, you can use only boxTop and boxBottom and set the maxData, minData and midData to empty arrays.

Similarly, if the boxTop, boxBottom and midData are set to empty arrays, only the top and bottom mark lines and the joining center line are visible. This style is most often used as "error bands" together with line charts.

In addition to maxData, minData and midData, you can add additional mark lines to the box-whisker element by adding more data sets using Layer.addDataSet.

By default, the box-whisker symbol will be drawn using the colors specified in the fillColor, whiskerColor and edgeColor argument. The fillColor and edgeColor are used as the fill and border colors of the box, while the whiskerColor is used as the color of the center line and the mark lines.

Internally, ChartDirector maps the colors of different parts of the box-whisker symbol to data set colors as shown in the following table. You may control the colors of the box-whisker symbol in more details by setting the data set colors directly. The data set objects can be obtained using Layer.getDataSet, and the colors can be changed using DataSet.setDataColor.

Box-Whisker Symbol Color | Data Set Color
Fill color of the box | Data Color for the first data set (index = 0)
Border color of the box | Edge Color for the first data set (index = 0)
Center line color | Data Color for the second data set (index = 1)
Maximum value mark line color | Data Color for the third data set (index = 2)
Minimum value mark line color | Data Color for the fourth data set (index = 3)
Middle value mark line color | Data Color for the fifth data set (index = 4)
Mark line color for additional mark lines | Data Color for the data set representing the additional mark line

Arguments

Argument | Default | Description
boxTop | (Mandatory) | An array of numbers representing the top edge of the box.
boxBottom | (Mandatory) | An array of numbers representing the bottom edge of the box.
maxData | [Empty_Array] | An array of numbers representing the maximum value mark lines.
minData | [Empty_Array] | An array of numbers representing the minimum value mark lines.
midData | [Empty_Array] | An array of numbers representing the middle value mark lines.
fillColor | -1 | The color used to fill the box. -1 means that the color is automatically selected from the palette.
whiskerColor | LineColor | The color used to draw the central line and mark lines.
edgeColor | LineColor | The color used to draw the border of the box.

Return Value

A BoxWhiskerLayer object representing the box-whisker layer created.


XYChart.addBoxWhiskerLayer2

XYChart.addBoxWhiskerLayer2

Usage

addBoxWhiskerLayer2(boxTop, boxBottom [, maxData [, minData [, midData [, fillColors [, whiskerBrightness [, names ]]]]]])

Description

Adds a multi-color box-whisker layer to the XYChart, and specify the data sets to use for drawing the layer.

This method is similar to XYChart.addBoxWhiskerLayer, except that the layer will be added in multi-color mode. Please refer to XYChart.addBoxWhiskerLayer on basic information of what is a box-whisker layer.

In multi-color mode, the boxes of a BoxWhiskerLayer can have different fill colors. For the whisker, instead of specifying a single whisker color for all boxes, ChartDirector computes the whisker colors by darkening or brightening the corresponding fill colors using a configurable brightness factor.

Arguments

Argument | Default | Description
boxTop | (Mandatory) | An array of numbers representing the top edge of the box.
boxBottom | (Mandatory) | An array of numbers representing the bottom edge of the box.
maxData | [Empty_Array] | An array of numbers representing the maximum value mark lines.
minData | [Empty_Array] | An array of numbers representing the minimum value mark lines.
midData | [Empty_Array] | An array of numbers representing the middle value mark lines.
fillColors | [Empty_Array] | An array of colors to be used as the fill color of the boxes. If there are insufficient colors in the array for the boxes, the remaining boxes will have their colors automatically selected from the palette.
whiskerBrightness | 0.5 | The brightness factor for whisker color. A value less than 1 means darkening. A value larger than 1 means brightening. A zero value means black.
names | [Empty_Array] | An array of names for the boxes to be used in the legend box, if one is configured for the chart.

Return Value

A BoxWhiskerLayer object representing the box-whisker layer created.


XYChart.addBoxLayer

XYChart.addBoxLayer

Usage

addBoxLayer(boxTop, boxBottom [, color [, name ]])

Description

Adds a floating box layer to the XYChart, and specify the data sets to use for drawing the layer.

This method is a simplification of XYChart.addBoxWhiskerLayer. Instead of adding a full box-whisker layer, only the box part is used, resulting in a chart layer displaying floating boxes.

Arguments

Argument | Default | Description
boxTop | (Mandatory) | An array of numbers representing the top edge of the box.
boxBottom | (Mandatory) | An array of numbers representing the bottom edge of the box.
color | -1 | The color to draw the area. -1 means that the color is automatically selected from the color palette.
name | "" | The name of the data set. The name will be used in the legend box, if one is available. An empty string means the data set has no name.

Return Value

A BoxWhiskerLayer object representing the box-whisker layer created.


XYChart.addVectorLayer

XYChart.addVectorLayer

Usage

addVectorLayer(xData, yData, lengths, directions [, lengthScale [, color [, name ]]])

Description

Adds a vector layer to the chart.

The vectors are specified as 4 data series, representing the x and y coordinates of the reference points to put the vectors, and the lengths and directions of the vectors.

By default, the vector starts from the reference point and points away from it. You may use VectorLayer.setArrowAlignment to specify other options, such as for the vectors to point into the reference point, or to have the reference as a pivot at the mid-point of the vector.

ChartDirector supports specifying vectors lengths as pixels or in axis scale. The unit is specified by using the following predefined constants.

Constant | Value | Description
PixelScale | 0 | The unit is measured in pixels.
XAxisScale | 1 | The unit is measured in x-axis scale.
YAxisScale | 2 | The unit is measured in y-axis scale.

Arguments

Argument | Default | Description
xData | (Mandatory) | An array of numbers representing the x coordinates for the reference points of the vectors.
yData | (Mandatory) | An array of numbers representing the y coordinates for the reference points of the vectors.
lengths | (Mandatory) | An array of numbers representing the lengths of the vectors, in unit as specified in the lengthScale argument.
directions | (Mandatory) | An array of numbers representing the direction of the vectors as a clockwise angle in degrees, where 0 is upward pointing direction.
lengthScale | PixelScale | The unit for the lengths, which must be one of the predefined constants in the table above.
color | -1 | The color to draw the data points. -1 means that the color is automatically selected from the palette.
name | "" | The name of the layer. The name will be used in the legend box, if one is available. An empty string means the layer has no name.

Return Value

A VectorLayer object representing the vector layer created.


XYChart.addHLOCLayer

XYChart.addHLOCLayer

Usage

addHLOCLayer(highData, lowData [, openData [, closeData [, color ]]])

Description

Adds a high-low-open-close (HLOC) layer to the XYChart, and specify the data sets to use for drawing the layer.

In this method, all HLOC symbols will be drawn using the color specified in the color argument. Use XYChart.addHLOCLayer3 for multi-color HLOC layers.

Internally, ChartDirector maps the colors of different parts of the HLOC symbol to data set colors as shown in the following table. You may control the colors of the HLOC symbol in more details by setting the data set colors directly. The data set objects can be obtained using Layer.getDataSet, and the colors can be changed using DataSet.setDataColor.

HLOC Symbol Color | Data Set Color
Central Line | Data Color for the first data set (index = 0)
Open Mark Line | Data Color for the third data set (index = 2)
Close Mark Line | Data Color for the fourth data set (index = 3)

Arguments

Argument | Default | Description
highData | (Mandatory) | An array of numbers representing the high values. An empty array means there is no high value data available.
lowData | (Mandatory) | An array of numbers representing the low values. An empty array means there is no low value data available.
openData | [Empty_Array] | An array of numbers representing the opening values. An empty array means there is no opening value data available.
closeData | [Empty_Array] | An array of numbers representing the closing values. An empty array means there is no closing value data available.
color | -1 | The color to draw the HLOC symbol. -1 means that the color is automatically selected from the palette.

Return Value

A HLOCLayer object representing the HLOC layer created.


XYChart.addHLOCLayer2

XYChart.addHLOCLayer2

Usage

addHLOCLayer2()

Description

Adds an empty high-low-open-close (HLOC) layer to the XYChart.

Arguments

None

Return Value

A HLOCLayer object representing the HLOC layer created.


XYChart.addHLOCLayer3

XYChart.addHLOCLayer3

Usage

addHLOCLayer3(highData, lowData, openData, closeData, upColor, downColor [, colorMode [, leadValue ]])

Description

Adds a multi-color high-low-open-close (HLOC) layer to the XYChart, and specify the data sets to use for drawing the layer.

ChartDirector supports drawing the HLOC symbol using different colors depending on whether the data represents an "up" day or "down" day. ChartDirector supports different definitions of what is an "up" day and "down" day, denoted using the following constants.

Constant | Value | Description
HLOCDefault | 0 | Do not distinguish between "up" and "down" days and use the same color for all HLOC symbols.
HLOCOpenClose | 1 | An up day is a day of which the closing value is on or above the opening value. This is the same definition commonly used in candlestick charts.
HLOCUpDown | 2 | An up day is a day of which the closing value is on or above the closing value of the previous day.

Arguments

Argument | Default | Description
highData | (Mandatory) | An array of numbers representing the high values. An empty array means there is no high value data available.
lowData | (Mandatory) | An array of numbers representing the low values. An empty array means there is no low value data available.
openData | (Mandatory) | An array of numbers representing the opening values. An empty array means there is no opening value data available.
closeData | (Mandatory) | An array of numbers representing the closing values. An empty array means there is no closing value data available.
upColor | (Mandatory) | The color to be used on an "up" day.
downColor | (Mandatory) | The color to be used on a "down" day.
colorMode | -1 | The method used to determine if a day is an "up" or "down". Must be one of the constants in the above table. The default value of -1 means the colorMode is automatically determine to be either HLOCDefault or HLOCUpDown, depending on whether upColor and downColor are the same or different.
leadValue | [-Infinity] | The lead value to act as the closing pricing before the first day, so as to determine if the first day is an "up" or "down" day.

Return Value

A HLOCLayer object representing the HLOC layer created.


XYChart.addCandleStickLayer

XYChart.addCandleStickLayer

Usage

addCandleStickLayer(highData, lowData, openData, closeData [, riseColor [, fallColor [, edgeColor ]]])

Description

Adds a candlestick layer to the XYChart, and specify the data sets to use for drawing the layer.

By default, the candlestick symbol will be drawn using the colors specified in the riseColor, fallColor and edgeColor argument. The riseColor and fallColor are used to fill the candle depending on whether the opening value or closing value is larger. The edgeColor is used to the center line and the border of the candle.

Internally, ChartDirector maps the colors of different parts of the candlestick symbol to data set colors as shown in the following table. You may control the colors of the candlestick symbol in more details by setting the data set colors directly. The data set objects can be obtained using Layer.getDataSet, and the colors can be changed using DataSet.setDataColor.

Candlestick Symbol Color | Data Set Color
Fill color for "up" candlesticks | Data Color for the first data set (index = 0).
Fill color for "down" candlesticks | Data Color for the second data set (index = 1).
Border color | Edge Color for the first data set (index = 0).
Center line color | Edge Color for the second data set (index = 1).

Arguments

Argument | Default | Description
highData | (Mandatory) | An array of numbers representing the high values.
lowData | (Mandatory) | An array of numbers representing the low values.
openData | (Mandatory) | An array of numbers representing the opening values.
closeData | (Mandatory) | An array of numbers representing the closing values.
riseColor | FFFFFF | The color used to fill the candle if the closing value is higher than the opening value.
fallColor | 000000 | The color used to fill the candle if the opening value is higher than the closing value.
edgeColor | LineColor | The color used to draw the center line and the border of the candle.

Return Value

A CandleStickLayer object representing the candlestick layer created.


XYChart.getXCoor

XYChart.getXCoor

Usage

getXCoor(v)

Description

Gets the x pixel coordinate of a point given the x data value.

Note: You must call BaseChart.layout first before calling this method. It is because ChartDirector needs to perform auto-scaling and determine the axis scale first before it can compute the coordinates.

For a 3D chart, this method will get the pixel coordinate of the data value on the top surface of the chart. Use Layer.getXCoor to obtain the pixel coordinate of the data value on a particular chart layer.

Arguments

Argument | Default | Description
v | (Mandatory) | The x data value.

Return Value

The x coordinate of the x data value.


XYChart.getYCoor

XYChart.getYCoor

Usage

getYCoor(v [, yAxis ])

Description

Gets the y pixel coordinate of a point given the y data value.

Note: You must call BaseChart.layout first before calling this method. It is because ChartDirector needs to perform auto-scaling and determine the axis scale first before it can compute the coordinates.

For a 3D chart, this method will get the pixel coordinate of the data value on the top surface of the chart. Use Layer.getYCoor to obtain the pixel coordinate of the data value on a particular chart layer.

Arguments

Argument | Default | Description
v | (Mandatory) | The y data value.
yAxis | [Null] | The y-axis to use to determine the pixel coordinates of data values. The y-axis may be obtained using XYChart.yAxis, XYChart.yAxis2 or XYChart.addAxis. The default is to use the primary y-axis.

Return Value

The y coordinate of the y data value.


XYChart.xZoneColor

XYChart.xZoneColor

Usage

xZoneColor(threshold, belowColor, aboveColor)

Description

Creates a x-zone color. A x-zone will change from one color to another depending on a threshold value on the x-axis.

For example, if a x-zone color is used as the line color in a line layer, the line will switch from one color to another when its passes through a certain value on the x-axis. Similarly, if a x-zone color is used as the fill color in an area layer, the area will switch from one color to another when it passes through a certain value on the x-axis.

The two colors used in a x-zone color can be other dynamic colors. For example, one color could be a solid color, while the other color could be a dash line color (see !BaseChart.dashLineColor). When this x-zone color is as the line color, the line will change from a solid style to a dash line style when the line passes through a certain value on the x-axis

You may create x-zone colors with more than 2 zones by cascading multiple x-zone colors.

For a 3D chart, this method will get the zone color at the top surface of the chart. Use Layer.xZoneColor to obtain the zone color for a particular chart layer.

Arguments

Argument | Default | Description
threshold | (Mandatory) | The x value serving as the threshold for switching between two colors.
belowColor | (Mandatory) | The color to use when the x-axis value of the pixel is smaller than the threshold.
aboveColor | (Mandatory) | The color to use when the x-axis value of the pixel is greater than the threshold.

Return Value

A 32-bit integer representing the x-zone color.


XYChart.yZoneColor

XYChart.yZoneColor

Usage

yZoneColor(threshold, belowColor, aboveColor [, yAxis ])

Description

Creates a y-zone color. A y-zone will change from one color to another depending on a threshold value on the y-axis.

For example, if a y-zone color is used as the fill color in an area layer, the area will switch from one color to another when its value is higher than a certain value on the y-axis.

The two colors used in a y-zone color can be other dynamic colors. You may create y-zone colors with more than 2 zones by cascading multiple y-zone colors.

For a 3D chart, this method will get the zone color at the top surface of the chart. Use Layer.yZoneColor to obtain the zone color for a particular chart layer.

Arguments

Argument | Default | Description
threshold | (Mandatory) | The y value serving as the threshold for switching between two colors.
belowColor | (Mandatory) | The color to use when the y-axis value of the pixel is smaller than the threshold.
aboveColor | (Mandatory) | The color to use when the y-axis value of the pixel is greater than the threshold.
yAxis | [Null] | The y-axis to use to determine the pixel coordinates of data values. The y-axis may be obtained using XYChart.yAxis, XYChart.yAxis2 or XYChart.addAxis. The default is to use the primary y-axis.

Return Value

A 32-bit integer representing the y-zone color.


PlotArea

PlotArea

The PlotArea class represents plot areas in XY charts. PlotArea objects are obtained by calling XYChart.setPlotArea.

Method | Inherited | Description
setBackground | (Self) | Sets the background colors and the border color of the plot area.
setBackground2 | (Self) | Sets the specified image file as the background image of the plot area.
setAltBgColor | (Self) | Sets alternating plot area background color.
set4QBgColor | (Self) | Sets using 4 background plot area colors for 4 quadrants.
setGridColor | (Self) | Sets the horizontal and vertical grid colors of the plot area.
setGridWidth | (Self) | Sets the horizontal and vertical grid line width.


PlotArea.setBackground

PlotArea.setBackground

Usage

setBackground(color [, altBgColor [, edgeColor ]])

Description

Sets the background colors and the border color of the plot area.

A plot area can have one or two background colors. If it has two background colors, they are drawn alternatively as horizontal bands on the major background grid.

ChartDirector Ver 4.0 introduces two new methods PlotArea.setAltBgColor and PlotArea.set4QBgColor. They are used for vertical alternating bands, and for supporting 4 background colors for 4 quadrants.

Arguments

Argument | Default | Description
color | (Mandatory) | The background color.
altBgColor | -1 | The second background color. -1 means there is no second background color.
edgeColor | -1 | The border color of the plot area. -1 means to use the default, which is LineColor. However, if the axes are configured in 4 quadrant mode (see XYChart.setAxisAtOrigin), the default will change to Transparent.

Return Value

None


PlotArea.setBackground2

PlotArea.setBackground2

Usage

setBackground2(img [, align ])

Description

Sets the specified image file as the background image of the plot area.

ChartDirector will automatically detect the image file format using the file extension, which must either png, jpg, jpeg, gif, wbmp or wmp (case insensitive).

Please refer to BaseChart.setSearchPath on the directory that ChartDirector will search for the file.

Arguments

Argument | Default | Description
img | (Mandatory) | The image file that is used as the background image of the plot area.
align | Center | The alignment of the background image relative to the plot area. See Alignment Specification for supported alignment types.

Return Value

None


PlotArea.setAltBgColor

PlotArea.setAltBgColor

Usage

setAltBgColor(horizontal, color1, color2 [, edgeColor ])

Description

Sets alternating plot area background color.

This method can be used to specify two colors that will be used alternatively to draw horizontal or vertical bands on the plot area background, using major grid lines as boundaries for the bands.

Arguments

Argument | Default | Description
horizontal | (Mandatory) | true (non-zero) means to use horizontal bands. false (zero) means to use vertical bands.
color1 | (Mandatory) | The first color to be used as the alternating background color.
color2 | (Mandatory) | The second color to be used as the alternating background color.
edgeColor | -1 | The border color of the plot area. -1 means to use the default, which is LineColor. However, if the axes are configured in 4 quadrant mode (see XYChart.setAxisAtOrigin), the default will change to Transparent.

Return Value

None


PlotArea.set4QBgColor

PlotArea.set4QBgColor

Usage

set4QBgColor(Q1Color, Q2Color, Q3Color, Q4Color [, edgeColor ])

Description

Sets using 4 background plot area colors for 4 quadrants.

The first quadrant is the region defined by x > 0 and y > 0. The second quadrant is the region defined by x < 0 and y > 0. The third quadrant is the region defined by x < 0 and y < 0. The fourth quadrant is the region defined by x > 0 and y < 0. These 4 regions can be colored using 4 different background colors.

Arguments

Argument | Default | Description
Q1Color | (Mandatory) | The background color to be used for the first quadrant.
Q2Color | (Mandatory) | The background color to be used for the second quadrant.
Q3Color | (Mandatory) | The background color to be used for the third quadrant.
Q4Color | (Mandatory) | The background color to be used for the fourth quadrant.
edgeColor | -1 | he border color of the plot area. -1 means to use the default, which is LineColor. However, if the axes are configured in 4 quadrant mode (see XYChart.setAxisAtOrigin), the default will change to Transparent.

Return Value

None


PlotArea.setGridColor

PlotArea.setGridColor

Usage

setGridColor(hGridColor [, vGridColor [, minorHGridColor [, minorVGridColor ]]])

Description

Sets the horizontal and vertical grid colors of the plot area.

Arguments

Argument | Default | Description
hGridColor | (Mandatory) | The color for the horizontal grid lines associated with major ticks.
vGridColor | Transparent | The color for the vertical grid lines associated with major ticks.
minorHGridColor | -1 | The color for the horizontal grid lines associated with minor ticks. -1 means the color is the same as hGridColor.
minorVGridColor | -1 | The color for the vertical grid lines associated with minor ticks. -1 means the color is the same as vGridColor.

Return Value

None


PlotArea.setGridWidth

PlotArea.setGridWidth

Usage

setGridWidth(hGridWidth [, vGridWidth [, minorHGridWidth [, minorVGridWidth ]]])

Description

Sets the horizontal and vertical grid line width.

Arguments

Argument | Default | Description
hGridWidth | (Mandatory) | The line width for the horizontal grid lines associated with major ticks.
vGridWidth | -1 | The line width for the vertical grid lines associated with major ticks. -1 means the vertical grid line width is the same as hGridWidth.
minorHGridWidth | -1 | The line width for the horizontal grid lines associated with minor ticks. -1 means the color is the same as hGridWidth.
minorVGridWidth | -1 | The line width for the horizontal grid lines associated with minor ticks. -1 means the color is the same as vGridWidth.

Return Value

None


Axis

Axis

The Axis class represents x and y axes in XY charts.

Method | Inherited | Description
setLabelStyle | (Self) | Sets the font style used to for the axis labels.
setLabelFormat | (Self) | Sets the format for numeric or date/time axis labels.
setMultiFormat | (Self) | Sets multiple formats for numeric or date/time axis labels.
setMultiFormat2 | (Self) | Adds one filter and format string to the multi-format lists.
setFormatCondition | (Self) | Specifies the condition that subsequent Axis.setLabelFormat and Axis.setMultiFormat will become applicable.
setLabelGap | (Self) | Sets the distance between the axis labels and the ticks on the axis.
setLabelOffset | (Self) | Shifts the axis labels from its default position along the axis.
setTitle | (Self) | Adds a title to the axis.
setTitlePos | (Self) | Sets the position of the axis title relative to the axis.
setColors | (Self) | Sets the colors of the axis itself, axis label, axis title and axis ticks.
setTickLength | (Self) | Sets the length of the axis ticks.
setTickLength2 | (Self) | Sets the length of the major and minor axis ticks.
setTickWidth | (Self) | Sets the width of the axis ticks.
setTickColor | (Self) | Sets the colors of the axis ticks.
setTickOffset | (Self) | Shifts the position of the ticks along the axis.
setMinTickInc | (Self) | Sets the minimum distance between two ticks on the axis for auto-scaled axis.
setWidth | (Self) | Sets the line width of the axis.
setMargin | (Self) | Reserve margins at the ends of the axis.
setIndent | (Self) | Specifies if the axis should be "indented" or not.
setAutoScale | (Self) | Sets the margins at the two ends of the axis during auto-scaling, and whether to start the axis from zero.
setRounding | (Self) | Controls whether to round the ends of the axis to align with tick positions.
setTickDensity | (Self) | Sets the density of the axis ticks.
setReverse | (Self) | Reverse the axis.
setLabels | (Self) | Sets the text labels to be used on the axis.
setLabels2 | (Self) | Sets the numeric/date/time labels to be used on the axis.
setLabelStep | (Self) | Shows a regularly spaced subset of the axis labels on the axis.
setLinearScale | (Self) | Sets the axis to use the given linear scale.
setLinearScale2 | (Self) | Sets the axis to use the given linear scale and the given labels.
setLinearScale3 | (Self) | Sets the axis to use linear auto-scale.
setLogScale | (Self) | Sets the axis to use the given logarithmic scale.
setLogScale2 | (Self) | Sets the axis to use the given logarithmic scale and the given labels.
setLogScale3 | (Self) | Sets the axis to use logarithmic auto-scale.
setDateScale | (Self) | Sets the axis to use the given date scale.
setDateScale2 | (Self) | Sets the axis to use the given date scale and the given labels.
setDateScale3 | (Self) | Sets the axis to use date auto-scale.
syncAxis | (Self) | Synchronizes this axis with another axis using a linear formula.
copyAxis | (Self) | Copies the scale and labels from another axis.
addLabel | (Self) | Adds an extra label on the axis.
addMark | (Self) | Adds a mark line to the chart.
addZone | (Self) | Adds a zone to the chart.
getMinValue | (Self) | Gets the lower bound of the axis.
getMaxValue | (Self) | Gets the upper bound of the axis.
getTicks | (Self) | Gets the values of the ticks.
getLabel | (Self) | Gets the label at the specified position on the axis.
getHTMLImageMap | (Self) | Generates an HTML image map for the axis labels.
getAxisImageMap | (Self) | Generates an HTML image map for the axis itself.


Axis.setLabelStyle

Axis.setLabelStyle

Usage

setLabelStyle([ font [, fontSize [, fontColor [, fontAngle ]]]])

Description

Sets the font style used to for the axis labels.

See Font Specification for details on various font attributes.

Arguments

Argument | Default | Description
font | "" | The font used to draw the labels.
fontSize | 8 | The font size used to draw the labels in points.
fontColor | TextColor | The color used to draw the labels.
fontAngle | 0 | The rotation angle of the labels.

Return Value

A TextBox object representing the prototype of the obj. This may be used to fine-tune the appearance of the obj.


Axis.setLabelFormat

Axis.setLabelFormat

Usage

setLabelFormat(formatString)

Description

Sets the format for numeric or date/time axis labels.

By default, ChartDirector will try to guess if the axis represents numbers or dates. If the axis represents numbers, it will use "{value}" as the default format. If the axis represents dates, it will guess the format based on resolution of the dates (e.g. whether the dates contain hourly data or monthly data, etc). It may use formats such as {value|mm/dd/yy<*br*>hh:nn:ss}, {value|mm/dd/yy hh:nn:ss}, {value|mm/dd/yyyy}, {value|mm/yyyy} or {value|yyyy}.

Please refer to Parameter Substitution and Formatting on all available parameters and how to format them.

Arguments

Argument | Default | Description
formatString | (Mandatory) | The format string.

Return Value

None


Axis.setMultiFormat

Axis.setMultiFormat

Usage

setMultiFormat(filter1, format1, filter2, format2 [, labelSpan [, promoteFirst ]])

Description

Sets multiple formats for numeric or date/time axis labels.

This method is typically used to format date/time labels. For example, for an axis that spans 90 days, this method can be used to format the first labels of each month in bold as "mmm-dd", while other labels are shown in normal font as "dd".

The multiple formats are defined as a list of filters and format strings. If the label value satisfies the first filter, it will be formatted using the first format string. Otherwise if the label value satisfies the second filter, it will be formatted using the second format string, and so on. If a label value does not satisfy any filter, it will be discarded.

In the above example, the first filter can be a "start of month" filter (created using ChartDirector.CFChart.StartOfMonthFilter), and the first format string can be "{value|mmm-dd}". The second filter can be the "all pass" filter (created using ChartDirector.CFChart.AllPassFilter), and the format string can be "{value|dd}".

Supported filters in ChartDirector include:

Filter | Description
ChartDirector.CFChart.StartOfHourFilter | Creates a data filter that matches date/times that represent the start of a new hour in a date/time series.
ChartDirector.CFChart.StartOfDayFilter | Creates a data filter that matches date/times that represent the start of a new day in a date/time series.
ChartDirector.CFChart.StartOfWeekFilter | Creates a data filter that matches date/times that represent the start of a new week in a date/time series.
ChartDirector.CFChart.StartOfMonthFilter | Creates a data filter that matches date/times that represent the start of a new month in a date/time series.
ChartDirector.CFChart.StartOfYearFilter | Creates a data filter that matches date/times that represent the start of a new year in a date/time series.
ChartDirector.CFChart.RegularSpacingFilter | Creates a data filter that matches 1 out of every N elements.
ChartDirector.CFChart.AllPassFilter | Creates a data filter that matches every element.
ChartDirector.CFChart.NonePassFilter | Creates a data filter that matches no element.
ChartDirector.CFChart.SelectItemFilter | Creates a data filter that matches one specified item.

For the format strings, please refer to Parameter Substitution and Formatting on their syntax.

A single setMultiFormat method supports two filters and two format strings. You can use multiple setMultiFormat and/or Axis.setMultiFormat2 methods to add more filters and format strings.

One common issue in putting labels on the axis is that there may be too many labels on the axis. The setMultiFormat method supports a labelSpan argument that specifies how many label positions a single label will occupy. If a label occupies more than 1 position, ChartDirector will not put labels on nearby positions, even if they meet the filter criteria.

The setMultiFormat method supports special handling of the first label on the axis. For example, in the above example, we may want to show the the first label as "mmm-dd", even if it is not actually the "start of month". The promoteFirst argument, if set to true, will cause the first label to be promoted to a higher filter category in the multi-format list. For example, if the first label satisfies only the second filter, it will be formatted as if it satisfies the first filter.

Arguments

Argument | Default | Description
filter1 | (Mandatory) | The filter that defines the first kind of labels.
format1 | (Mandatory) | The format string for the first kind of labels.
filter2 | (Mandatory) | The filter that defines the second kind of labels.
format2 | (Mandatory) | The format string for the second kind of labels.
labelSpan | 1 | The number of label positions that are claimed by one label. If a label occupies more than 1 position, ChartDirector will not put labels on nearby positions, even if they meet the filter criteria.
promoteFirst | true (non-zero) | If set to true, the first label will be promoted to a higher filter category in the multi-format list.

Return Value

None


Axis.setMultiFormat2

Axis.setMultiFormat2

Usage

setMultiFormat2(filterId, formatString [, labelSpan [, promoteFirst ]])

Description

Adds one filter and format string to the multi-format lists.

Please refer to Axis.setMultiFormat on how to use this method.

Arguments

Argument | Default | Description
filterId | (Mandatory) | The filter that defines a subset of labels.
formatString | (Mandatory) | The format string for formatting the subset defined by the above filter.
labelSpan | 1 | The number of label positions that are claimed by one label. If a label occupies more than 1 position, ChartDirector will not put labels on nearby positions, even if they meet the filter criteria.
promoteFirst | true (non-zero) | If set to true, the first label will be promoted to a higher filter category in the multi-format list.

Return Value

None


Axis.setFormatCondition

Axis.setFormatCondition

Usage

setFormatCondition(condition [, operand ])

Description

Specifies the condition that subsequent Axis.setLabelFormat and Axis.setMultiFormat will become applicable.

In some applications, the axis range can vary greatly. For example, for a date/time axis, the ticks on the axis can be hourly ticks if the duration is short, or daily ticks (or even monthly or yearly) if the duration is long. One can always use a universal axis format that is applicable in all cases (such as "mmm dd, yyyy<*br*>hh:nn:ss"), or one can leave ChartDirector to automatically come up with a suitable axis format.

Sometimes it may be desirable to explicitly specify different axis formats depending on tick types. For example, one may want to specify a certain format if the ticks are hourly, and another format if the ticks are daily.

If it is possible to predict which kind of ticks will be on the axis, one can always use "if" statements to specify different axis formats for various cases.

The setFormatCondition method is for cases in which it is difficult to predict which type of ticks would appear on the axis. For example, in an auto-scaled axis in which the duration can vary continuously, in some marginal cases, it is difficult to predict if auto-scaling will choose hourly or daily ticks.

The setFormatCondition method allows you to specify a condition to be tested against the auto-scaling result, so that subsequent Axis.setLabelFormat or Axis.setMultiFormat will be applicable only if the condition is true.

The types of condition supported are:

Condition | Description
"align" | Test if all the ticks are aligned to the operand. Use 3600 for testing hourly alignment, 86400 (1 day = 86400) for daily alignment, 30 * 86400 for monthly alignment and 360 * 86400 for yearly alignment. (Note: The values for monthly and yearly alignments are special values recognized by ChartDirector. They works even if a month or year is not exactly 30 or 360 days.)
">" | Test if the maximum absolute value of the ticks are larger than the operand. This is useful when one needs to apply different formats to large numbers (eg. use scientific formats if the axis range exceed certain values).
">=" | Test if the maximum absolute value of the ticks is larger than or equal to the operand.
"<" | Test if the maximum absolute value of the ticks is less than the operand.
"<=" | Test if the maximum absolute value of the ticks is less than or equal to the operand.
"==" | Test if the maximum absolute value of the ticks is equal to the operand.
"=" | Same as "==" above.
"!=" | Test if the maximum absolute value of the ticks is not equal to the operand.
"<>" | Same as "!=" above.
"else" | This condition is true if and only if the previous condition is false.
"true" | This condition is always true. It is useful as a "catch all" condition.
"false" | This condition is always false.

Arguments

Argument | Default | Description
condition | (Mandatory) | The type of condition to test. Must be one of the condition types in the above table. This text string is case sensitive.
operand | 0 | The operand for condition types that need an operand.

Return Value

None


Axis.setLabelGap

Axis.setLabelGap

Usage

setLabelGap(d)

Description

Sets the distance between the axis labels and the ticks on the axis.

Arguments

Argument | Default | Description
d | (Mandatory) | The distance between the axis label and the tick in pixels.

Return Value

None


Axis.setLabelOffset

Axis.setLabelOffset

Usage

setLabelOffset(offset)

Description

Shifts the axis labels from its default position along the axis.

This method expects the offset along the axis being a value on the axis scale. The Box.setPos method of the axis label prototype (obtained using Axis.setLabelStyle) can also be used to shift the labels, with the offsets specified in pixel units.

Arguments

Argument | Default | Description
offset | (Mandatory) | The distance to shift the labels along the axis as a value on the axis scale.

Return Value

None


Axis.setTitle

Axis.setTitle

Usage

setTitle(text [, font [, fontSize [, fontColor ]]])

Description

Adds a title to the axis.

See Font Specification for details on various font attributes.

Arguments

Argument | Default | Description
text | (Mandatory) | The title text.
font | "" | The font used to draw the title. If no font is specified, the default is "bold".
fontSize | 8 | The size of the font in points.
fontColor | TextColor | The color used to draw the title text.

Return Value

A TextBox object representing the axis title. This may be used to fine-tune the appearance of the axis title.


Axis.setTitlePos

Axis.setTitlePos

Usage

setTitlePos(alignment [, titleGap ])

Description

Sets the position of the axis title relative to the axis.

By default, the axis title will be drawn at the middle of the axis outside the plot area. You may change the location of the title. For example, instead of drawing the y-axis title at the middle of the axis, you may want draw it at the top of the axis.

Arguments

Argument | Default | Description
alignment | (Mandatory) | The position of the title relative to the axis.
titleGap | 3 | The distance between the axis title and the axis in pixels.

Return Value

None


Axis.setColors

Axis.setColors

Usage

setColors(axisColor [, labelColor [, titleColor [, tickColor ]]])

Description

Sets the colors of the axis itself, axis label, axis title and axis ticks.

By default, the axis and axis ticks are drawn using the LineColor, while the axis label and axis title are drawn using the TextColor. You may use this method to change their colors.

Arguments

Argument | Default | Description
axisColor | (Mandatory) | The color of the axis itself.
labelColor | TextColor | The color of the axis labels.
titleColor | -1 | The color of the axis title. -1 means the axis title color is the same as the axis label color.
tickColor | -1 | The color of the axis ticks. -1 means the axis ticks color is the same as the axis color.

Return Value

None


Axis.setTickLength

Axis.setTickLength

Usage

setTickLength(majorTickLen)

Description

Sets the length of the axis ticks.

A positive tick length means the ticks are drawn outside the plot area. A negative tick length means the ticks are drawn inside the plot area.

Arguments

Argument | Default | Description
majorTickLen | (Mandatory) | The length of the major ticks in pixels. The length of the minor ticks will automatically be set to half the length of the major ticks.

Return Value

None


Axis.setTickLength2

Axis.setTickLength2

Usage

setTickLength2(majorTickLen, minorTickLen)

Description

Sets the length of the major and minor axis ticks.

A positive tick length means the ticks are drawn outside the plot area. A negative tick length means the ticks are drawn inside the plot area.

Arguments

Argument | Default | Description
majorTickLen | (Mandatory) | The length of the major ticks in pixels.
minorTickLen | (Mandatory) | The length of the minor ticks in pixels.

Return Value

None


Axis.setTickWidth

Axis.setTickWidth

Usage

setTickWidth(majorTickWidth [, minorTickWidth ])

Description

Sets the width of the axis ticks.

Arguments

Argument | Default | Description
majorTickWidth | (Mandatory) | The width of the major ticks in pixels.
minorTickWidth | -1 | The width of the minor ticks in pixels. -1 means the width is the same as majorTickWidth.

Return Value

None


Axis.setTickColor

Axis.setTickColor

Usage

setTickColor(majorTickColor [, minorTickColor ])

Description

Sets the colors of the axis ticks.

Arguments

Argument | Default | Description
majorTickColor | (Mandatory) | The color of the major ticks.
minorTickColor | -1 | The color of the major ticks. -1 means the color is the same as majorTickColor.

Return Value

None


Axis.setTickOffset

Axis.setTickOffset

Usage

setTickOffset(offset)

Description

Shifts the position of the ticks along the axis.

By default, ChartDirector draws the ticks at the label position. This method is typically used to shift the ticks so that the ticks are between two labels, rather than aligned with the label.

The offset is specified as a value on the axis scale. For a label based axis (configured using Axis.setLabels), shifting with an offset of 0.5 means shifting half the label interval. This will achieve the effect of putting the ticks in between the labels.

Arguments

Argument | Default | Description
offset | (Mandatory) | The distance to shift the ticks along the axis as a value on the axis scale.

Return Value

None


Axis.setMinTickInc

Axis.setMinTickInc

Usage

setMinTickInc(inc)

Description

Sets the minimum distance between two ticks on the axis for auto-scaled axis.

The most common use of this method is to ensure the ticks are of integer values (the minimum distance set to 1).

ChartDirector auto-scaling will automatically determine the optimal number of ticks and labels on the axis. However, in some cases, the nature of the data may be such that the ticks should assume only certain discrete values (such as must be integers). This method will inform ChartDirector for this constraint when performing auto-scaling.

For a log scale axis, because the axis ticks are unevenly spaced, the minimum distance will be handled as the minimum value allowed for the axis scale.

Arguments

Argument | Default | Description
inc | (Mandatory) | The minimum distance between two ticks on the axis as a data value.

Return Value

None


Axis.setWidth

Axis.setWidth

Usage

setWidth(width)

Description

Sets the line width of the axis.

Arguments

Argument | Default | Description
width | (Mandatory) | The line width of the axis in pixels.

Return Value

None


Axis.setMargin

Axis.setMargin

Usage

setMargin(topMargin [, bottomMargin ])

Description

Reserve margins at the ends of the axis.

This method is usually used to reserve space in the plot area. For example, if some margin is reserved at the top of the vertical y-axis, the top of the plot area will contain no data points. It is because this region would be outside the active range of the y-axis. If anything is put at the top of the plot area (such as a legend box or custom text), it will not overlap with the data points.

Note if auto-scaling is used, there is an alternative way to reserve space at the top and/or bottom of the plot area - the Axis.setAutoScale method.

Arguments

Argument | Default | Description
topMargin | (Mandatory) | The margin reserved at the top end (or right end for horizontal axis) of the axis in pixels.
bottomMargin | 0 | The margin reserved at the bottom end (or left end for horizontal axis) of the axis in pixels.

Return Value

None


Axis.setIndent

Axis.setIndent

Usage

setIndent(indent)

Description

Specifies if the axis should be "indented" or not.

Normally, the x-axis is automatically scaled so that x coordinate of first data point is at the beginning of the x-axis, and the x coordinate last data point is at the end of the axis. If a line layer is drawn, the line will span from the left border of the plot area to the right border of the plot area.

However, for bar layer, if the x-axis is scaled as above, half of the first bar and half of the last bar will be outside the plot area. The same applies to HLOC layers, candlestick layers and box-whisker layers.

When the axis is "indented", some margins will be reserved at the ends of the axis, so that all data representation are within the plot area.

By default, "indented" mode is automatically used in x-axis for charts that contain bar, HLOC, candlestick or box-whisker layers.

The setIndent method allows you to manually configure whether "indented" mode is used or not. One common usage is to align the x-axes in different charts.

For example, suppose a web page contains a bar chart and a line chart. The bar chart will be using "indented" mode x-axis, while the line chart will be using "non-indented" mode. If the two charts are on top of one another for ease of comparison (common for finance style charts), it is desirable that their x-axes should align. In this case, the setIndent method can be used to force the line chart to use indented mode x-axis.

Arguments

Argument | Default | Description
indent | (Mandatory) | A true (non-zero) value sets the axis to indented mode. A false (zero) value sets the axis to non-indented mode.

Return Value

None


Axis.setAutoScale

Axis.setAutoScale

Usage

setAutoScale([ topExtension [, bottomExtension [, zeroAffinity ]]])

Description

Sets the margins at the two ends of the axis during auto-scaling, and whether to start the axis from zero.

During auto-scaling, it is often desirable to leave some margins at the ends of the axis. For example, suppose in a bar chart, the longest bar is 10 units. If auto-scaling chooses 0 - 10 as the scale, the longest bar will touch the top edge of the plot area. In many cases, the chart will look better if there is some margin so that the longest bar does not touch the top edge.

The setAutoScale can be used to reserve some margins at the ends of the axis by using a scale that is larger than necessary. For example, in the above case, if a scale of 0 - 12 is used, then the longest bar will not touch the top edge.

Other common reasons for reserving margins at the ends of the axis include making sure the data labels (which may be drawn on top of the data points) will not go outside the plot area, and that objects put at the top or bottom of the plot area (such as legend box and custom text box) will not overlap with the data points.

Note that there is an alternative way to reserve space at the ends of the axis - the Axis.setMargin method.

In the setAutoScale method, the amount of margins reserved is controlled by the topExtension and bottomExtension arguments. These arguments determine the portion of the axis where no data point can reach. For example, a topExtension of 0.2 will ensure no data point can fall within the top 20% of the axis.

Note that ChartDirector will not extend the scale across the 0 point.

For example, suppose the data range is 0.1 - 9.9. If 10% margin is added to the bottom end of the axis, the bottom end may become negative. In this case, ChartDirector will extend the bottom end to 0 at most.

In other words, if the data range is completely positive, ChartDirector will not extend the axis to negative, as it would be undesirable in most applications. The same applies if the data range is completely negative.

For a purely positive axis, the bottom end has "zero affinity". That means ChartDirector will tend to choose 0 as the bottom end because zero is a natural starting point for the axis. However, if the data range is too extreme (e.g. the data is in the range 10000 - 10005), it may be "unreasonable" to choose 0 as the axis starting point. In this case, ChartDirector will not use 0 as the axis starting point.

ChartDirector will determine that it is "unreasonable" to use 0 as the axis starting point if the data fluctuation (the difference between the maximum and minimum data values) is too small compare with the data value. ChartDirector test the "too small" condition using the formula:

maxDataValue * zeroAffinity < minDataValue

where zeroAffinity by default is 0.8.

Similar "zero affinity" mechanism applies to the top end of the axis for a purely negative axis. If the data range contains both positive and negative values, the zero point is always included.

The zeroAffinity argument of the setAutoScale method allows you to modify the zero affinity when performing auto-scaling. Zero affinity should be between 0 and 1. A large value encourages ChartDirector to start the axis from zero.

A zero affinity of 1 means the axis always includes the zero point. A zero affinity of 0 means that the axis is scaled purely according to the data range, without any preference for the zero point.

Note that zero affinity is ignored for log scale axis as log scale axis cannot contain 0.

Arguments

Argument | Default | Description
topExtension | 0.1 | The top portion of the axis that no data point should fall into. For example, a value of 0.2 means no data value will fall within the top 20% of the axis. The topExtension must be between 0 to 1.
bottomExtension | 0.1 | The bottom portion of the axis that no data point should fall into. For example, a value of 0.2 means no data value will fall within the bottom 20% of the axis. The bottomExtension must be between 0 to 1.
zeroAffinity | 0.8 | The tendency of ChartDirector to include zero in the axis during auto-scaling. The value must be between 0 and 1. A large value encourages ChartDirector to start the axis from zero. A value of 1 means the axis always includes the zero point. A value of 0 means there is no preference for the zero point during auto-scaling.

Return Value

None


Axis.setRounding

Axis.setRounding

Usage

setRounding(roundMin, roundMax)

Description

Controls whether to round the ends of the axis to align with tick positions.

For example, if the axis is from 0.33 - 9.7, ChartDirector may round it to 0 - 10 so that the ends 0 and 10 are properly aligned with the ticks.

By default, ChartDirector will round the axis ends for the y-axis, but not for the x-axis. An exception is a chart containing a scatter layer, where both x and y axes will be rounded.

Arguments

Argument | Default | Description
roundMin | (Mandatory) | A true (non-zero) value means the lesser end of the axis should be rounded to align with tick positions. A false (zero) value means no rounding.
roundMax | (Mandatory) | A true (non-zero) value means the greater end of the axis should be rounded to align with tick positions. A false (zero) value means no rounding.

Return Value

None


Axis.setTickDensity

Axis.setTickDensity

Usage

setTickDensity(majorTickSpacing [, minorTickSpacing ])

Description

Sets the density of the axis ticks.

Tick density is the desired distance between two ticks in pixels. When ChartDirector performs auto-scaling, it will decide how many ticks to put on the axis based on tick density.

Note that the actual tick density chosen in auto-scaling may not be exactly the same as the desired tick density. It is because ChartDirector may have other constraints in choosing the ticks, such as the ticks and axis range should be neat numbers, and the axis must contain an integral number of ticks, etc. ChartDirector may use a tick distance that is larger than suggested, but never smaller.

Arguments

Argument | Default | Description
majorTickSpacing | (Mandatory) | Specify the desired distance between two major ticks in pixels.
minorTickSpacing | -1 | Specify the desired distance between two minor ticks in pixels. -1 means minor ticks are not used.

Return Value

None


Axis.setReverse

Axis.setReverse

Usage

setReverse([ b ])

Description

Reverse the axis.

For a normal vertical axis, the axis starts from the bottom and increase its value towards the top. For a normal horizontal axis, the axis starts from the left and increase its value towards the right. The setReverse method can be used to reverse the direction of the axis.

Arguments

Argument | Default | Description
b | true (non-zero) | A true (non-zero) value means the axis is reversed. A false (zero) value means the axis is not reversed.

Return Value

None


Axis.setLabels

Axis.setLabels

Usage

setLabels(text)

Description

Sets the text labels to be used on the axis.

This method is typically used to set the x-axis to enumerated scale. In enumerated scale, the data points are associated with the x-axis by position. The first data point will be plotted at the first label position on the x-axis, the second data point at the second label position, and so on.

Enumerated axis is a very flexible axis type. It is most suitable for chart types where the data points are evenly spaced on the x-axis. The axis labels can be any text. They do not need to be numbers or dates. If they are numbers or dates, you can format them in any way you like before calling this method.

Internally, ChartDirector will assign a value of 0 to the first axis label, 1 to the second axis label, and so on. These values are not visible. Only the axis labels are visible. However, these values may be useful for some ChartDirector features that need to reference the axis position by value, such as adding mark lines using Axis.addMark.

By default, all axis labels will be associated major ticks. To associate a label with a minor tick, use '-' as the first character of the label. To draw a label without any tick at all, use '~' as the first character of the label.

Leading '-' or '~' characters are tick specification characters and will not appear on the labels. They just specify the the tick style to be associated with the labels. If you want have a label that actually begins these characters, add '\' as the first character as the escape character.

One common issue is that there may be too many labels on the axis. In this case, the Axis.setLabelStep method may be used show only a regularly spaced subset of labels on the axis.

Another method is to remove some labels is to replace them with empty strings before passing them to ChartDirector. If you want to remove the label text but leave a major tick, use a space character " " as the label text. If you want to remove the label text but leave a major tick, use "-" as the label text.

Arguments

Argument | Default | Description
text | (Mandatory) | An array of strings containing the text of the labels.

Return Value

A TextBox object representing the prototype of the obj. This may be used to fine-tune the appearance of the obj.


Axis.setLabels2

Axis.setLabels2

Usage

setLabels2(labels [, formatString ])

Description

Sets the numeric/date/time labels to be used on the axis.

This method is typically used to set the x-axis to enumerated scale. For more details on what is enumerated axis scale, please refer to Axis.setLabels.

This method assumes the labels are in their "native" form (that is, not formatted). Please refer to Date Representation for the native date/time formats supported in ChartDirector.

If the labels are already formatted into human readable form (that is, they are text strings), use Axis.setLabels instead.

One common issue is that there may be too many labels on the axis. In this case, the Axis.setLabelStep method may be used show only a regularly spaced subset of labels on the axis.

For date/time labels, another alternative is to use Axis.setMultiFormat, which uses filters to select important dates/times (such as dates/times representing the start of a month) for display as labels.

A third method to avoid too many labels is to remove some labels by replacing them with NoValue before passing them to ChartDirector. If you want to remove the label text but leave a minor tick, use MinorTickOnly as the label value.

Arguments

Argument | Default | Description
labels | (Mandatory) | An array of numbers/dates to be used as the axis labels.
formatString | "" | A format string to specified how to format the labels into human readable form. Please refer to Axis.setLabelFormat for the syntax of the format string. An empty string means the format will be automatically determined.

Return Value

A TextBox object representing the prototype of the obj. This may be used to fine-tune the appearance of the obj.


Axis.setLabelStep

Axis.setLabelStep

Usage

setLabelStep(majorTickStep [, minorTickStep [, majorTickOffset [, minorTickOffset ]]])

Description

Shows a regularly spaced subset of the axis labels on the axis.

This method is typically used in conjunction with Axis.setLabels or Axis.setLabels2. These two methods define the full set of labels on the axis, one for each data point in a data set. In many cases, there may be too many labels and the axis may become overcrowded with labels. The setLabelStep method will cause the axis to show a regularly spaced subset of labels instead all labels.

Arguments

Argument | Default | Description
majorTickStep | (Mandatory) | The spacing between visible labels (major ticks). For example, a value of 10 means displaying 1 label for every 10 labels.
minorTickStep | 0 | For labels that are not displayed, ChartDirector can optionally put a minor tick in its place. The argument specifies the spacing between minor ticks. For example, a value of 5 means displaying 1 minor tick for every 5 labels. The default value of 0 means no minor tick is used.
majorTickOffset | 0 | The offset used for selecting the labels. For example, if majorTickStep is set to 10, by default, ChartDirector will select the labels with index 0, 10, 20, 30 and so on. If the majorTickOffset argument is set to 3, then ChartDirector will select labels with index 3, 13, 23, 33 and so on.
minorTickOffset | -7fffffff | The offset used for selecting minor tick points. The usage is the same as the majorTickOffset argument, except it applies to minor tick points. The default is to use the same value as majorTickOffset.

Return Value

None


Axis.setLinearScale

Axis.setLinearScale

Usage

setLinearScale(lowerLimit, upperLimit [, majorTickInc [, minorTickInc ]])

Description

Sets the axis to use the given linear scale.

Arguments

Argument | Default | Description
lowerLimit | (Mandatory) | The lower bound of the axis.
upperLimit | (Mandatory) | The upper bound of the axis.
majorTickInc | 0 | Adds major ticks to the axis, where the major ticks are separated by majorTickInc in value. Each major tick will have an associated text label for the value if the axis at the tick. The default value of 0 means the major ticks will be automatically determined. In this case, the lowerLimit and upperLimit may be automatically adjusted to align with the ticks. Use NoValue to disable major ticks.
minorTickInc | 0 | Adds minor ticks to the axis, where the minor ticks are separated by minorTickInc in value. The default value of 0 means no minor tick is used.

Return Value

None


Axis.setLinearScale2

Axis.setLinearScale2

Usage

setLinearScale2(lowerLimit, upperLimit, labels)

Description

Sets the axis to use the given linear scale and the given labels.

Arguments

Argument | Default | Description
lowerLimit | (Mandatory) | The lower bound of the axis.
upperLimit | (Mandatory) | The upper bound of the axis.
labels | (Mandatory) | An array of text strings to be used as the labels on the axis. ChartDirector will distribute the labels evenly on the axis. By default, all labels are associated with major ticks. These can be modified by using '-' or '~' as the first character. Please refer to Axis.setLabels for details.

Return Value

None


Axis.setLinearScale3

Axis.setLinearScale3

Usage

setLinearScale3([ formatString ])

Description

Sets the axis to use linear auto-scale.

Arguments

Argument | Default | Description
formatString | "" | The format used for the labels on the axis. Please refer to Axis.setLabelFormat for the syntax of the format string. An empty string means the format will be automatically determined.

Return Value

None


Axis.setLogScale

Axis.setLogScale

Usage

setLogScale(lowerLimit, upperLimit [, majorTickInc [, minorTickInc ]])

Description

Sets the axis to use the given logarithmic scale.

Arguments

Argument | Default | Description
lowerLimit | (Mandatory) | The lower bound of the axis.
upperLimit | (Mandatory) | The upper bound of the axis.
majorTickInc | 0 | Adds major ticks to the axis, where the major ticks are separated by majorTickInc in ratio. For example, a value of 10 means each tick will be 10 times the value of the previous tick. Each major tick will have an associated text label for the value if the axis at the tick. The special predefined constant LogTick ( = 1.6e308) means the tick increment will be using the non-regular ratio 1, 2, 5, 10, 20, 50, 100, .... The default value of 0 means the major ticks will be automatically determined. In this case, the lowerLimit and upperLimit may be automatically adjusted to align with the ticks. Use NoValue to disable major ticks.
minorTickInc | 0 | Adds minor ticks to the axis, where the minor ticks are separated by minorTickInc in ratio. The special constant LogTick means the tick increment will be using the non- regular ratio 1, 2, 5, 10, 20, 50, 100, .... The default value of 0 means no minor tick is used.

Return Value

None


Axis.setLogScale2

Axis.setLogScale2

Usage

setLogScale2(lowerLimit, upperLimit, labels)

Description

Sets the axis to use the given logarithmic scale and the given labels.

Arguments

Argument | Default | Description
lowerLimit | (Mandatory) | The lower bound of the axis.
upperLimit | (Mandatory) | The upper bound of the axis.
labels | (Mandatory) | An array of text strings to be used as the labels on the axis. ChartDirector will distribute the labels evenly on the axis. By default, all labels are associated with major ticks. These can be modified by using '-' or '~' as the first character. Please refer to Axis.setLabels for details.

Return Value

None


Axis.setLogScale3

Axis.setLogScale3

Usage

setLogScale3([ formatString ])

Description

Sets the axis to use logarithmic auto-scale.

Arguments

Argument | Default | Description
formatString | "" | The format used for the labels on the axis. Please refer to Axis.setLabelFormat for the syntax of the format string. An empty string means the format will be automatically determined.

Return Value

None


Axis.setDateScale

Axis.setDateScale

Usage

setDateScale(lowerLimit, upperLimit [, majorTickInc [, minorTickInc ]])

Description

Sets the axis to use the given date scale.

Arguments

Argument | Default | Description
lowerLimit | (Mandatory) | The lower bound of the axis, representing using one of the ChartDirector supported date format.
upperLimit | (Mandatory) | The upper bound of the axis, representing using one of the ChartDirector supported date format.
majorTickInc | 0 | Adds major ticks to the axis, where the major ticks are separated by majorTickInc seconds. Each major tick will have an associated text label for the value if the axis at the tick. The value 30 * 86400 will be assume to mean one month (which actually contains a variable number of seconds), and 60 * 86400 will be assumed to mean 2 months and so on. The value 360 * 86400 therefore means 12 months, or 1 year. The default value of 0 means the major ticks will be automatically determined. In this case, the lowerLimit and upperLimit may be automatically adjusted to align with the ticks. Use NoValue to disable major ticks.
minorTickInc | 0 | Adds minor ticks to the x-axis, where the minor ticks are separated by minorTickInc seconds. The value 30 * 86400 will be assume to mean one month (which actually contains a variable number of seconds), and 60 * 86400 will be assumed to mean 2 months and so on. The value 360 * 86400 therefore means 12 months, or 1 year. The default value of 0 means no minor tick is used.

Return Value

None


Axis.setDateScale2

Axis.setDateScale2

Usage

setDateScale2(lowerLimit, upperLimit, labels)

Description

Sets the axis to use the given date scale and the given labels.

Arguments

Argument | Default | Description
lowerLimit | (Mandatory) | The lower bound of the axis, representing using one of the ChartDirector supported date format.
upperLimit | (Mandatory) | The upper bound of the axis, representing using one of the ChartDirector supported date format.
labels | (Mandatory) | An array of text strings to be used as the labels on the axis. ChartDirector will distribute the labels evenly on the axis. By default, all labels are associated with major ticks. These can be modified by using '-' or '~' as the first character. Please refer to Axis.setLabels for details.

Return Value

None


Axis.setDateScale3

Axis.setDateScale3

Usage

setDateScale3([ formatString ])

Description

Sets the axis to use date auto-scale.

Arguments

Argument | Default | Description
formatString | "" | The format used for the labels on the axis. Please refer to Axis.setLabelFormat for the syntax of the format string. An empty string means the format will be automatically determined.

Return Value

None


Axis.syncAxis

Axis.syncAxis

Usage

syncAxis(axis [, slope [, intercept ]])

Description

Synchronizes this axis with another axis using a linear formula.

This method is typically used if the two axes represent the same quantity but in different units. For example, one axis may represent temperature in Celsius, and the other in Fahrenheit, or they may represent lengths in meters and feet.

The scale of this axis (value) will be related to the scale of the another axis (value2) using the following formula:

value = value2 * slope + intercept

Typically, one of the axis will be for actual charting, and its scale will be determined in the standard way using auto or manual scaling. Then the second axis is set to synchronize with the first axis.

Arguments

Argument | Default | Description
axis | (Mandatory) | The axis to synchronize to.
slope | 1 | The slope for synchronizing this axis to the other axis.
intercept | 0 | The intercept parameter for synchronizing this axis to the other axis.

Return Value

None


Axis.copyAxis

Axis.copyAxis

Usage

copyAxis(axis)

Description

Copies the scale and labels from another axis.

This method is typically used to ensure the axes on different charts are identical. For example, if multiple charts are draw and are stacked up, and you want the x-axes of the charts to be the same for easy comparison, you may copy the x-axis from one chart to the other charts.

The differences between copyAxis and Axis.syncAxis are:

  • Axis.syncAxis relates the axes with a linear relationship, so the axes may not be exact copies of one another.

  • Axis.syncAxis synchronizes axis scale and copies only scale related labels, such as the labels generated by auto-scaling, Axis.setLinearScale, Axis.setLogScale or Axis.setDateScale.

  • copyAxis copies all labels, including labels created using Axis.setLabels and Axis.setLabels2, which may be arbitrary text.

Arguments

Argument | Default | Description
axis | (Mandatory) | The axis to copy from.

Return Value

None


Axis.addLabel

Axis.addLabel

Usage

addLabel(pos, label)

Description

Adds an extra label on the axis.

Arguments

Argument | Default | Description
pos | (Mandatory) | The position on the axis to add the label.
label | (Mandatory) | The text label to add.

Return Value

None


Axis.addMark

Axis.addMark

Usage

addMark(value, lineColor [, text [, font [, fontSize ]]])

Description

Adds a mark line to the chart.

A mark line is a line drawn on the plot area. This line is usually used to indicate some special values, such as a "target value", "threshold value", "target date", etc.

A mark line attached to the horizontal axis will be vertical across the plot area. A mark line drawn using the vertical axis will be horizontal across the plot area. In either case, the mark line label will be added to the axis at the mark line position.

The location of the mark line label can be changed by using TextBox.setAlignment. For example, by setting the alignment to TopCenter, the mark line label will be drawn on the top center of the mark line.

By default, the mark line is drawn at the front of the chart layers. You may change it to draw at the back of the plot area (that is, like grid lines) using Mark.setDrawOnTop.

Arguments

Argument | Default | Description
value | (Mandatory) | The value on the axis to draw the mark line.
lineColor | (Mandatory) | The color of the mark line.
text | "" | The text label for the mark line. An empty string means there is no text label. By default, the text label and the tick on the axis will be drawn using the same color as the mark line. You can modify the colors by using the Mark.setMarkColor method.
font | "" | The font used to draw the text label.
fontSize | 8 | The font size used to draw the text label in points.

Return Value

A Mark object representing the mark line added. You may use this object to fine- tune the appearance of the mark.


Axis.addZone

Axis.addZone

Usage

addZone(startValue, endValue, color)

Description

Adds a zone to the chart.

A zone is a range of values. For example, "10 to 20" is a zone. Typically, a zones are used to classify data ranges. For example, you may classify 0 - 60 as the normal zone, 60 - 90 as the warning zone, and 90 - 100 as the critical zone.

A zone based on a horizontal axis will be drawn as a vertical band. A zone based on a vertical axis will be drawn as a horizontal band. Zones are always drawn at the back of the plot area.

Arguments

Argument | Default | Description
startValue | (Mandatory) | The start value (the lower bound) for the zone.
endValue | (Mandatory) | The end value (the upper bound) for the zone.
color | (Mandatory) | The color of the zone.

Return Value

None


Axis.getMinValue

Axis.getMinValue

Usage

getMinValue()

Description

Gets the lower bound of the axis.

The lower bound of an axis is known only after auto-scaling. So this method should be called only after ChartDirector has finished auto-scaling (e.g. after calling BaseChart.layout to explicitly auto-scale the axis).

Arguments

None

Return Value

The lower bound of the axis.


Axis.getMaxValue

Axis.getMaxValue

Usage

getMaxValue()

Description

Gets the upper bound of the axis.

The upper bound of an axis is known only after auto-scaling. So this method should be called only after ChartDirector has finished auto-scaling (e.g. after calling BaseChart.layout to explicitly auto-scale the axis).

Arguments

None

Return Value

The upper bound of the axis.


Axis.getTicks

Axis.getTicks

Usage

getTicks()

Description

Gets the values of the ticks.

The ticks on the axis is known only after auto-scaling. So this method should be called only after ChartDirector has finished auto-scaling (e.g. after calling BaseChart.layout to explicitly auto-scale the axis).

Arguments

None

Return Value

An array of numbers representing the values of the ticks.


Axis.getLabel

Axis.getLabel

Usage

getLabel(i)

Description

Gets the label at the specified position on the axis.

Arguments

Argument | Default | Description
i | (Mandatory) | The position specified as a value on the axis scale.

Return Value

Returns the label at the specified position, or a null string if there is no label at that position.


Axis.getHTMLImageMap

Axis.getHTMLImageMap

Usage

getHTMLImageMap(url [, queryFormat [, extraAttr [, offsetX, offsetY ]]])

Description

Generates an HTML image map for the axis labels.

This method should be called only after creating the chart image (eg. using BaseChart.makeSession, BaseChart.makeChart or BaseChart.makeChart2). The image map cannot be determined without creating the chart image first.

This method accepts a URL as its argument. When generating an image map, it appends query parameters to the URL to indicate which legend entry the user has clicked.

The following is an example image map generated for an axis with 3 labels.

<area shape="rect" coords="30,220,70,239" href="handler.asp?value=0&label=John">
<area shape="rect" coords="70,220,110,239" href="handler.asp?value=1&label=Mary">
<area shape="rect" coords="110,220,150,239" href="handler.asp?value=2&label=Peter">

The image map consists of multiple <area> tags, one for each label. In the "href" attributes, query parameters are appended to the URL to provide information on the label clicked.

The image map produces by ChartDirector does not include the <map> and </map> tag. This is intentional so that you can add additional custom <area> tags to the image map, or append multiple image maps together.

The format of the appended URL parameters is determined using the queryFormat argument, which by default is:

value={value}&label={label}

The texts in curly brackets (i.e. {value}, {label}) will be replaced by the actual values when generating the image map. For example, {label} will be replaced by the label text.

Please refer to Parameter Substitution and Formatting on all available parameters and how to format them.

In addition to customizing the query parameters, ChartDirector supports additional HTML attributes in the <area> tags using the extraAttr argument.

For example, the following extraAttr will add a "title" HTML attribute to every <area> tag. The "title" attribute will be displayed as "tool tip" when the mouse moves over the image map.

title='Click me for details on {label}'

Another common usage of the extraAttr argument is to add "onmouseover" and "onmouseout" HTML attributes to handle user interaction using Javascript on the browser.

Arguments

Argument | Default | Description
url | (Mandatory) | The URL to be used in the "href" attribute of the image map. Parameter Substitution and Formatting is supported. Use an empty string if no href attribute is needed.
queryFormat | "" | A text string representing the template of the query parameters to be appended to the URL. Parameter Substitution and Formatting is supported. The special keyword "{default}" represents the default query parameters. This is useful for specifying appending to the default. Note that an empty string means to use the default query query parameters. To specify no query parameter, use a space character.
extraAttr | "" | A text string to specify additional attributes to add to the <area> tag. Parameter Substitution and Formatting is supported.
offsetX | 0 | An offset to be added to all x coordinates in the image map. This is useful if the current image will be shifted and inserted into another image. In this case, the image map will need to be shifted by the same offset.
offsetY | 0 | An offset to be added to all y coordinates in the image map. See offsetX above for description.

Return Value

A text string containing the image map generated.


Axis.getAxisImageMap

Axis.getAxisImageMap

Usage

getAxisImageMap(noOfSegments, mapWidth, url [, queryFormat [, extraAttr [, offsetX, offsetY ]]])

Description

Generates an HTML image map for the axis itself.

This method is similar to Axis.getHTMLImageMap. The difference is instead of generating an image map for the labels, it generates an image map for the axis itself. The axis will be divided into a number of segments, with an image map entry created for each segment.

Arguments

Argument | Default | Description
noOfSegments | (Mandatory) | The number of segments to divide the axis into.
mapWidth | (Mandatory) | The width of the axis used for the purpose of generating the image map.
url | (Mandatory) | The URL to be used in the "href" attribute of the image map. Parameter Substitution and Formatting is supported. Use an empty string if no href attribute is needed.
queryFormat | "" | A text string representing the template of the query parameters to be appended to the URL. Parameter Substitution and Formatting is supported. The special keyword "{default}" represents the default query parameters. This is useful for specifying appending to the default. Note that an empty string means to use the default query query parameters. To specify no query parameter, use a space character.
extraAttr | "" | A text string to specify additional attributes to add to the <area> tag. Parameter Substitution and Formatting is supported.
offsetX | 0 | An offset to be added to all x coordinates in the image map. This is useful if the current image will be shifted and inserted into another image. In this case, the image map will need to be shifted by the same offset.
offsetY | 0 | An offset to be added to all y coordinates in the image map. See offsetX above for description.

Return Value

A text string containing the image map generated.


Mark

Mark

The Mark class represents mark lines. It is a subclass of TextBox. Mark objects are created using Axis.addMark.

Method | Inherited | Description
setValue | (Self) | Sets the value of the mark line.
setMarkColor | (Self) | Sets the line, text and tick colors of the mark line.
setLineWidth | (Self) | Sets the line width of the mark line.
setDrawOnTop | (Self) | Determine whether the mark line is drawn at the front of the chart layers, or at the back of the plot area (that is, like grid lines).
getLine | (Self) | Retrieves an opaque LineObj representing the mark line. The opaque LineObj is to be used in XYChart.addInterLineLayer for adding coloring between lines.
setText | TextBox | Sets the text to be shown in the text box.
setFontStyle | TextBox | Sets the font of the text by specifying the file that contains the font.
setFontSize | TextBox | Sets the font height and width in points.
setFontAngle | TextBox | Sets the rotation angle and layout direction of the text.
setFontColor | TextBox | Sets the color of the text.
setAlignment | TextBox | Sets the alignment of the text relative to the container box.
setWidth | TextBox | Sets the width of the text box and wraps text if necessary.
setHeight | TextBox | Sets the height of the text box.
setMaxWidth | TextBox | Sets the maximum width of the text box and wraps text if necessary.
setTruncate | TextBox | Sets the maximum number of lines in the text box, and truncate the text if it exceeds the line count.
setMargin | TextBox | Sets all margins (left, right, top, and bottom) of the text box to the same value.
setMargin2 | TextBox | Sets the margins of the text box in pixels.
setPos | Box | Sets the coordinates of the top-left corner of the box.
setSize | Box | Sets the width and height of the box.
setBackground | Box | Sets the background color, border color and 3D border effect of the box.
setRoundedCorners | Box | Sets the border style to use rounded corners.
getWidth | Box | Gets the width of the box.
getHeight | Box | Gets the height of the box.
getImageCoor | Box | Gets the image map coordinates of the box as HTML image map attributes.
setZOrder | Box | Sets the z-order (drawing order) for custom box objects.


Mark.setValue

Mark.setValue

Usage

setValue(value)

Description

Sets the value of the mark line.

Arguments

Argument | Default | Description
value | (Mandatory) | The value of the mark.

Return Value

None


Mark.setMarkColor

Mark.setMarkColor

Usage

setMarkColor(lineColor [, textColor [, tickColor ]])

Description

Sets the line, text and tick colors of the mark line.

Arguments

Argument | Default | Description
lineColor | (Mandatory) | The color of the mark line.
textColor | -1 | The color of the text label that will be shown on the axis. -1 means the text label color is the same as the line color.
tickColor | -1 | The color of the tick that will be shown on the axis. -1 means the tick color is the same as the line color.

Return Value

None


Mark.setLineWidth

Mark.setLineWidth

Usage

setLineWidth(w)

Description

Sets the line width of the mark line.

Arguments

Argument | Default | Description
w | (Mandatory) | The mark line width in pixels.

Return Value

None


Mark.setDrawOnTop

Mark.setDrawOnTop

Usage

setDrawOnTop(b)

Description

Determine whether the mark line is drawn at the front of the chart layers, or at the back of the plot area (that is, like grid lines).

Arguments

Argument | Default | Description
b | (Mandatory) | A true (non-zero) value means drawing the mark line at the front of the chart layers. A false (zero) value means drawing the mark line at the back of the plot area.

Return Value

None


Mark.getLine

Mark.getLine

Usage

getLine()

Description

Retrieves an opaque LineObj representing the mark line. The opaque LineObj is to be used in XYChart.addInterLineLayer for adding coloring between lines.

Arguments

None

Return Value

An opaque LineObj representing the mark line.


Layer

Layer

The Layer class is the base class for all XYChart layer classes.

Method | Inherited | Description
set3D | (Self) | Sets the 3D depth of the layer, and the 3D gap between the current layer and the next layer.
setLineWidth | (Self) | Sets the default line width of lines when drawing data sets on the layer.
setBorderColor | (Self) | Sets the default border color and 3D raised effect when drawing data sets on the layer.
setLegendOrder | (Self) | Sets the order of the data set names as appeared in the legend box.
setLegend | (Self) | Sets the order of the data set names as appeared in the legend box.
setDataCombineMethod | (Self) | Sets the method used to combine multiple data sets in a layer.
addDataSet | (Self) | Adds a data set to the chart layer.
getDataSet | (Self) | Gets the requested DataSet object.
addDataGroup | (Self) | Open a new data group.
addExtraField | (Self) | Adds an array of text to be used as an extra field in various places.
addExtraField2 | (Self) | Adds an array of numbers/dates to be used as an extra field in various places.
setUseYAxis | (Self) | Determine the y-axis to use when drawing the data sets.
setUseYAxis2 | (Self) | Determine if the primary or secondary y-axis should be used when drawing the data sets.
setXData | (Self) | Sets the x values of the data points in the data sets.
setXData2 | (Self) | Sets the x values of the data points in the data sets as evenly distributed in a range.
alignLayer | (Self) | Aligns the layer with a data set of another bar chart layer in Side layout.
getXCoor | (Self) | Gets the x pixel coordinate of a point given the x data value.
getYCoor | (Self) | Gets the y pixel coordinate of a point given the y data value.
xZoneColor | (Self) | Creates a x-zone color. A x-zone will change from one color to another depending on a threshold value on the x-axis.
yZoneColor | (Self) | Creates a y-zone color. A y-zone will change from one color to another depending on a threshold value on the y-axis.
setDataLabelStyle | (Self) | Enables data labels and sets their styles.
setDataLabelFormat | (Self) | Sets the data label format.
addCustomDataLabel | (Self) | Adds a custom data label to a data point.
setAggregateLabelStyle | (Self) | Enables aggregate labels and sets their styles.
setAggregateLabelFormat | (Self) | Sets the aggregate label format.
addCustomAggregateLabel | (Self) | Adds a custom aggregate label to an aggregated object.
addCustomGroupLabel | (Self) | Adds a custom data group label to object representing the group.
getImageCoor | (Self) | Gets the image map coordinates of a data point as represented in the layer as HTML image map attributes.
getImageCoor2 | (Self) | Gets the image map coordinates of a region containing all data points at the given x-position as HTML image map attributes.
getHTMLImageMap | (Self) | Generates an HTML image map for all data points as represented on the layer.
setHTMLImageMap | (Self) | Override the default arguments used when generating HTML image map for the layer.


Layer.set3D

Layer.set3D

Usage

set3D([ d [, zGap ]])

Description

Sets the 3D depth of the layer, and the 3D gap between the current layer and the next layer.

Arguments

Argument | Default | Description
d | -1 | The 3D depth of the layer in pixels. -1 means the 3D depth is automatically calculated.
zGap | 0 | The 3D gap between the current layer and the next layer in pixels.

Return Value

None


Layer.setLineWidth

Layer.setLineWidth

Usage

setLineWidth(w)

Description

Sets the default line width of lines when drawing data sets on the layer.

This method only applies to layers that employ lines to represent data (e.g. line layer).

This method affect all data sets. To set the line width of one particular data set, use DataSet.setLineWidth.

Arguments

Argument | Default | Description
w | (Mandatory) | The width of the line in pixels.

Return Value

None


Layer.setBorderColor

Layer.setBorderColor

Usage

setBorderColor(color [, raisedEffect ])

Description

Sets the default border color and 3D raised effect when drawing data sets on the layer.

This method only applies to layers that represents data with elements that have borders (e.g. bar layer).

This method affect all data sets. To set the color of one particular data set, use DataSet.setDataColor.

Arguments

Argument | Default | Description
color | (Mandatory) | The border color.
raisedEffect | 0 | The 3D border width. For positive values, the border will appear raised. For negative values, the border will appear depressed. A zero value means the border will appear flat. This argument is also used to support ChartDirector.CFChart.glassEffect and ChartDirector.CFChart.softLighting effects.

Return Value

None


Layer.setLegendOrder

Layer.setLegendOrder

Usage

setLegendOrder(dataSetOrder [, layerOrder ])

Description

Sets the order of the data set names as appeared in the legend box.

By default, ChartDirector will add named data sets to the the legend box. The ordering of the entries follows the order in which the layers are created. For data sets within the same layer, the ordering follows the order in which the data sets are added.

To support flexible ordering of the legend entries, ChartDirector employs a legend entry priority system. Please refer to LegendBox for details of the legend entry priority system.

The base priority of the layer can be specified using the layerOrder argument. The priority of the data sets within a layer can be modified by using the dataSetOrder argument, which must be one of the following predefined constant.

Constant | Value | Description
NormalLegend | 0 | The data set priority is 10 x (data_set_index + 1). Legend entries are ordered in the order with which the data sets are created.
ReverseLegend | 1 | The data sets priority is the reverse of the normal data set priority. Legend entries are ordered in the reverse order with which the data sets are created.
NoLegend | 2 | The data set names are not added to the legend box at all.

Arguments

Argument | Default | Description
dataSetOrder | (Mandatory) | One of the predefined constants representing the legend entry ordering method for data sets within the layer.
layerOrder | -1 | The base legend entry priority of the layer. The default value of -1 means the priority is 10000 x (layer_index + 1).

Return Value

None


Layer.setLegend

Layer.setLegend

Usage

setLegend(m)

Description

Sets the order of the data set names as appeared in the legend box.

This method is for backward compatibility. It is equivalent to Layer.setLegendOrder(m).

Arguments

Argument | Default | Description
m | (Mandatory) | One of the predefined constants representing the legend entry ordering method for data sets within the layer.

Return Value

None


Layer.setDataCombineMethod

Layer.setDataCombineMethod

Usage

setDataCombineMethod(m)

Description

Sets the method used to combine multiple data sets in a layer.

This method is used only for layers that can combine multiple data sets in different ways. Some layers can only support a subset of the data combine methods defined below.

Constant | Value | Description
Side | 3 | The data sets are combined by plotting the data representation side by side.
Stack | 1 | The data sets are combined by stacking up their data representations.
Overlay | 0 | The data sets are combined by drawing them independently, overlapping each others.
Percentage | 4 | The data sets are combined similar to the Stack method, except that the data is scaled so that each stack always summed up to 100. In other words, the region that a data item occupies in a stack represents the percentage of the data item relative to sum of all the data items in the stack.

Arguments

Argument | Default | Description
m | (Mandatory) | one of the predefined constants representing the data combine method to use.

Return Value

None


Layer.addDataSet

Layer.addDataSet

Usage

addDataSet(data [, color [, name ]])

Description

Adds a data set to the chart layer.

Arguments

Argument | Default | Description
data | (Mandatory) | An array of numbers representing the data set.
color | -1 | The color to draw the data item. -1 means that the color is automatically selected from the palette.
name | "" | The name of the data set. The name will be used in the legend box, if one is available. An empty string means the data set has no name.

Return Value

A DataSet object representing the data set added. You may use the methods of this object to fine-tune how the data set is drawn on the chart.


Layer.getDataSet

Layer.getDataSet

Usage

getDataSet(dataSet)

Description

Gets the requested DataSet object.

Arguments

Argument | Default | Description
dataSet | (Mandatory) | A data set number, starting from 0. The first data set object is 0, and the nth data set is (n-1).

Return Value

The requested DataSet object.


Layer.addDataGroup

Layer.addDataGroup

Usage

addDataGroup([ name ])

Description

Open a new data group.

Currently, only stacked bar layers support data groups for creating "multi-stacked" bars.

In a normal stacked bar layer, all data sets are stacked on top of one another, creating one stacked bar per x-axis position. If data grouping is used, data sets within the same data group with be stacked up. So there may be multiple stacked bars in each x-axis position. These stacked bars are drawn side by side.

When you add a data set using Layer.addDataSet, the data set will belong to the current data group. The addDataGroup method can be used to open a new data group, so that subsequent data sets will belong to that new group.

You may associate a name with a data group. The name can then be used in data labels or image maps to identify the data group.

Arguments

Argument | Default | Description
name | "" | Name of the data group.

Return Value

None


Layer.addExtraField

Layer.addExtraField

Usage

addExtraField(texts)

Description

Adds an array of text to be used as an extra field in various places.

This method merely stores the data inside the layer object. The Parameter Substitution and Formatting mechanism will determine how the data are to be used.

A common use for extra fields is to specify extra information (such as a custom serial number for the data points) to be displayed on data labels or on tool tips, or to supply extra query parameters in clickable charts. All these are achieved by specifying the extra field on the data label template or image map templates during parameter substitution.

Arguments

Argument | Default | Description
texts | (Mandatory) | An array of text to be stored inside the layer object.

Return Value

None


Layer.addExtraField2

Layer.addExtraField2

Usage

addExtraField2(numbers)

Description

Adds an array of numbers/dates to be used as an extra field in various places.

This method merely stores the data inside the layer object. The Parameter Substitution and Formatting mechanism will determine how the data are to be used.

A common use for extra fields is to specify extra information (such as a custom serial number for the data points) to be displayed on data labels or on tool tips, or to supply extra query parameters in clickable charts. All these are achieved by specifying the extra field on the data label template or image map templates during parameter substitution.

Arguments

Argument | Default | Description
numbers | (Mandatory) | An array of numbers/dates to be stored inside the layer object.

Return Value

None


Layer.setUseYAxis

Layer.setUseYAxis

Usage

setUseYAxis(a)

Description

Determine the y-axis to use when drawing the data sets.

This method affects all data sets in the layer. To set the y-axis to use for a particular data set, use DataSet.setUseYAxis.

Arguments

Argument | Default | Description
a | (Mandatory) | The y-axis to use when drawing the data sets.

Return Value

None


Layer.setUseYAxis2

Layer.setUseYAxis2

Usage

setUseYAxis2([ b ])

Description

Determine if the primary or secondary y-axis should be used when drawing the data sets.

This method affects all data sets in the layer. To set the y-axis to use for a particular data set, use DataSet.setUseYAxis2.

Note: Layer.setUseYAxis is a more general method that can support more than 2 y-axes.

Arguments

Argument | Default | Description
b | true (non-zero) | A true (non-zero) value means the secondary y-axis will be used. A false (zero) value means the primary y-axis will be used.

Return Value

None


Layer.setXData

Layer.setXData

Usage

setXData(xData)

Description

Sets the x values of the data points in the data sets.

In most ChartDirector XY chart layers, when a data set is added, only the y Values for the data points are needed. For example, in a bar layer, you just need to specify the values of the bars (y values). ChartDirector will automatically layout the bars evenly on the x-axis. You can then specify the labels on the x-axis using Axis.setLabels.

In ChartDirector, this type of x-axis scaling is called "enumerated" scale. Please refer to Axis.setLabels for a more detail explanation of "enumerated" scale.

However, in some cases, it may be necessary to specify the x values explicitly. For example, if a chart contains data points that are not evenly distributed on the x-axis, it is necessary to specify the x values explicitly. It is because enumerated scale always assume the data points are distributed evenly on the x- axis. In this case, the setXData method can be used to specify the x values for the data points.

In general, if the data points are evenly distributed on the x-axis, it is recommended enumerated x-scale be used and no x values are necessary. Even the data points are evenly distributed, except that some data points are missing, it is still possible to use enumerated x-scale by using the NoValue constant to represent missing data points.

On the other hand, if the data points are by its nature not evenly distributed, the x values should be provided explicitly using the setXData method.

Each layer only supports one x values series. All data sets in the layer will use the same x value series. If two data sets have different x values, they should be put in two separate layers.

Arguments

Argument | Default | Description
xData | (Mandatory) | An array of numbers representing the x value series.

Return Value

None


Layer.setXData2

Layer.setXData2

Usage

setXData2(minValue, maxValue)

Description

Sets the x values of the data points in the data sets as evenly distributed in a range.

This method is most useful when two layers contain data at different x axis scale. An example is a line layer with one data point per minute, and another line layer with one data point per 5 minutes.

In the above example, in one hour, the first layer will have 60 data points, while the second layer will have 12 data points. If enumerated x-scale is used, the x-axis will contain 60 positions evenly distributed. The 60 data points in the first layer will corresponds to the 60 positions in the x-axis, which is correct. However, the 12 data points in the second layer will corresponds to the first 12 positions on the x-axis, which is not the desired result.

Instead, the 12 data points in the second layer should corresponds to positions 0, 5, 10, 15, .... A little thought will review that the 12 data points in the second layer should be distributed evenly among positions 0 - 55. The setXData2 method can be used to inform ChartDirector about the scaling used in the second layer.

Arguments

Argument | Default | Description
minValue | (Mandatory) | The x value of the first point in a data set.
maxValue | (Mandatory) | The x value of the last point in the data set.

Return Value

None


Layer.alignLayer

Layer.alignLayer

Usage

alignLayer(layer, dataSet)

Description

Aligns the layer with a data set of another bar chart layer in Side layout.

The Side layout is a layout method specific to the bar chart layer. In this layout method, multiple bars belonging to the same x-position are laid out side by side. Thus the bars are not centered exactly on the x-position, but are shifted. The shift amount depends on the data set numbers of the bars.

In some cases, it may be necessary to overlay another layer (eg. a line chart layer, or a box-whisker chart layer) on top of the bars. The alignLayer method ensures the data points are shifted by the same amount as a given data set on a given BarLayer.

Arguments

Argument | Default | Description
layer | (Mandatory) | The BarLayer which contains the bars to synchronize with.
dataSet | (Mandatory) | The data set of the bars to synchronize with.

Return Value

None


Layer.getXCoor

Layer.getXCoor

Usage

getXCoor(v)

Description

Gets the x pixel coordinate of a point given the x data value.

Note: You must call BaseChart.layout first before calling this method. It is because ChartDirector needs to perform auto-scaling and determine the axis scale first before it can compute the coordinates.

Arguments

Argument | Default | Description
v | (Mandatory) | The x data value.

Return Value

The x coordinate of the x data value.


Layer.getYCoor

Layer.getYCoor

Usage

getYCoor(v [, yAxis ])

Description

Gets the y pixel coordinate of a point given the y data value.

Note: You must call BaseChart.layout first before calling this method. It is because ChartDirector needs to perform auto-scaling and determine the axis scale first before it can compute the coordinates.

Arguments

Argument | Default | Description
v | (Mandatory) | The y data value.
yAxis | [Null] | The y-axis to use to determine the pixel coordinates of data values. The y-axis may be obtained using XYChart.yAxis, XYChart.yAxis2 or XYChart.addAxis. The default is to use the primary y-axis. For backward compatibility, the axis argument can also be a boolean value. A true (non-zero) value means the primary y-axis. A false (zero) value means the secondary y-axis.

Return Value

The y coordinate of the y data value.


Layer.xZoneColor

Layer.xZoneColor

Usage

xZoneColor(threshold, belowColor, aboveColor)

Description

Creates a x-zone color. A x-zone will change from one color to another depending on a threshold value on the x-axis.

For example, if a x-zone color is used as the line color in a line layer, the line will switch from one color to another when its passes through a certain value on the x-axis. Similarly, if a x-zone color is used as the fill color in an area layer, the area will switch from one color to another when it passes through a certain value on the x-axis.

The two colors used in a x-zone color can be other dynamic colors. For example, one color could be a solid color, while the other color could be a dash line color (see !BaseChart.dashLineColor). When this x-zone color is as the line color, the line will change from a solid style to a dash line style when the line passes through a certain value on the x-axis

You may create x-zone colors with more than 2 zones by cascading multiple x-zone colors.

Arguments

Argument | Default | Description
threshold | (Mandatory) | The x value serving as the threshold for switching between two colors.
belowColor | (Mandatory) | The color to use when the x-axis value of the pixel is smaller than the threshold.
aboveColor | (Mandatory) | The color to use when the x-axis value of the pixel is greater than the threshold.

Return Value

A 32-bit integer representing the x-zone color.


Layer.yZoneColor

Layer.yZoneColor

Usage

yZoneColor(threshold, belowColor, aboveColor [, yAxis ])

Description

Creates a y-zone color. A y-zone will change from one color to another depending on a threshold value on the y-axis.

For example, if a y-zone color is used as the fill color in an area layer, the area will switch from one color to another when its value is higher than a certain value on the y-axis.

The two colors used in a y-zone color can be other dynamic colors. You may create y-zone colors with more than 2 zones by cascading multiple y-zone colors.

Arguments

Argument | Default | Description
threshold | (Mandatory) | The y value serving as the threshold for switching between two colors.
belowColor | (Mandatory) | The color to use when the y-axis value of the pixel is smaller than the threshold.
aboveColor | (Mandatory) | The color to use when the y-axis value of the pixel is greater than the threshold.
yAxis | [Null] | The y-axis to use to determine the pixel coordinates of data values. The y-axis may be obtained using XYChart.yAxis, XYChart.yAxis2 or XYChart.addAxis. The default is to use the primary y-axis. For backward compatibility, the axis argument can also be a boolean value. A true (non-zero) value means the primary y-axis. A false (zero) value means the secondary y-axis.

Return Value

A 32-bit integer representing the y-zone color.


Layer.setDataLabelStyle

Layer.setDataLabelStyle

Usage

setDataLabelStyle([ font [, fontSize [, fontColor [, fontAngle ]]]])

Description

Enables data labels and sets their styles.

This method affects all data labels in the layer. To set the style for one particular data set only, use DataSet.setDataLabelStyle.

Data labels are text used label data points in the layer. Different layer types put data labels in different positions. For example, in a bar chart, data labels are put at the internal end of the bar. For a line chart, data labels are put above the data points.

For some chart types, the position of the data labels can be manipulated by calling the TextBox.setAlignment method of the TextBox object returned by the setDataLabelStyle method.

See Font Specification for details on various font attributes.

Arguments

Argument | Default | Description
font | "" | The font used to draw the labels.
fontSize | 8 | The font size used to draw the labels.
fontColor | TextColor | The color used to draw the labels.
fontAngle | 0 | The rotation angle of the labels.

Return Value

A TextBox object representing the prototype of the obj. This may be used to fine-tune the appearance of the obj.


Layer.setDataLabelFormat

Layer.setDataLabelFormat

Usage

setDataLabelFormat(formatString)

Description

Sets the data label format.

This method affects all data labels in the layer. To set the label format for one particular data set only, use DataSet.setDataLabelFormat.

Data labels are text used label data points in the layer. Please refer to Layer.setDataLabelStyle for a more detail description.

By default, the data label format is "{value}". Please refer to Parameter Substitution and Formatting on available parameters and how to format them.

Arguments

Argument | Default | Description
formatString | (Mandatory) | The format string.

Return Value

None


Layer.addCustomDataLabel

Layer.addCustomDataLabel

Usage

addCustomDataLabel(dataSet, dataItem, label [, font [, fontSize [, fontColor [, fontAngle ]]]])

Description

Adds a custom data label to a data point.

Data labels are text used label data points in the layer. Please refer to Layer.setDataLabelStyle for a more detail description.

See Font Specification for details on various font attributes.

Arguments

Argument | Default | Description
dataSet | (Mandatory) | The data set number for the data point. The first data set is 0, while the nth data set is (n - 1).
dataItem | (Mandatory) | The data point number for the data point within the data set. The first data point is 0, while the nth data point is (n - 1).
label | (Mandatory) | A text string representing the data label. Parameter Substitution and Formatting is supported.
font | "" | The font used to draw the label.
fontSize | 8 | The font size used to draw the label.
fontColor | TextColor | The color used to draw the label.
fontAngle | 0 | The rotation angle of the label.

Return Value

A TextBox object representing the prototype of the obj. This may be used to fine-tune the appearance of the obj.


Layer.setAggregateLabelStyle

Layer.setAggregateLabelStyle

Usage

setAggregateLabelStyle([ font [, fontSize [, fontColor [, fontAngle ]]]])

Description

Enables aggregate labels and sets their styles.

Aggregate data labels applies to layer types that contains "aggregated data", such as stacked bar layer and stacked area layer. In these layer types, data labels (see Layer.setDataLabelStyle) represents a single data item, while aggregate labels represents the stacked object.

See Font Specification for details on various font attributes.

Arguments

Argument | Default | Description
font | "" | The font used to draw the labels.
fontSize | 8 | The font size used to draw the labels.
fontColor | TextColor | The color used to draw the labels.
fontAngle | 0 | The rotation angle of the labels.

Return Value

A TextBox object representing the prototype of the obj. This may be used to fine-tune the appearance of the obj.


Layer.setAggregateLabelFormat

Layer.setAggregateLabelFormat

Usage

setAggregateLabelFormat(formatString)

Description

Sets the aggregate label format.

By default, the aggregate label format is "{value}". Please refer to Parameter Substitution and Formatting on available parameters and how to format them.

Arguments

Argument | Default | Description
formatString | (Mandatory) | The format string.

Return Value

None


Layer.addCustomAggregateLabel

Layer.addCustomAggregateLabel

Usage

addCustomAggregateLabel(dataItem, label [, font [, fontSize [, fontColor [, fontAngle ]]]])

Description

Adds a custom aggregate label to an aggregated object.

Aggregate data labels applies to layer types that contains "aggregated data", such as stacked bar layer and stacked area layer. In these layer types, data labels (see Layer.setDataLabelStyle) represents a single data item, while aggregate labels represents the stacked object.

See Font Specification for details on various font attributes.

Arguments

Argument | Default | Description
dataItem | (Mandatory) | The index of the aggregated object. The first aggregated object is 0, while the nth aggregated object is (n - 1).
label | (Mandatory) | A text string representing the custom aggregate label. Parameter Substitution and Formatting is supported.
font | "" | The font used to draw the labels.
fontSize | 8 | The font size used to draw the labels.
fontColor | TextColor | The color used to draw the labels.
fontAngle | 0 | The rotation angle of the labels.

Return Value

A TextBox object representing the prototype of the obj. This may be used to fine-tune the appearance of the obj.


Layer.addCustomGroupLabel

Layer.addCustomGroupLabel

Usage

addCustomGroupLabel(dataGroup, dataItem, label [, font [, fontSize [, fontColor [, fontAngle ]]]])

Description

Adds a custom data group label to object representing the group.

Data group label applies to layer types that may represent data groups. See Layer.addDataGroup on how data groups are created and the layer types that support data groups.

See Font Specification for details on various font attributes.

Arguments

Argument | Default | Description
dataGroup | (Mandatory) | The data group number for the data point. The first data group is 0, while the nth data group is (n - 1).
dataItem | (Mandatory) | The data point number for the data point within the data group. The first data point is 0, while the nth data point is (n - 1).
label | (Mandatory) | A text string representing the data label. Parameter Substitution and Formatting is supported.
font | "" | The font used to draw the label.
fontSize | 8 | The font size used to draw the label.
fontColor | TextColor | The color used to draw the label.
fontAngle | 0 | The rotation angle of the label.

Return Value

A TextBox object representing the prototype of the obj. This may be used to fine-tune the appearance of the obj.


Layer.getImageCoor

Layer.getImageCoor

Usage

getImageCoor(dataSet, dataItem [, offsetX, offsetY ])

Description

Gets the image map coordinates of a data point as represented in the layer as HTML image map attributes.

The image map coordinates will be in the following format:

shape="[shape]" cords="[x1],[y1],[x2],[y2] ..."

This format is specially designed so that it can easily be incorporated into HTML image maps.

This method should be called only after creating the chart image (eg. using BaseChart.makeSession, BaseChart.makeChart or BaseChart.makeChart2). The image map cannot be determined without creating the chart image first.

Arguments

Argument | Default | Description
dataSet | (Mandatory) | The data set number for the data point. The first data set is 0, while the nth data set is (n-1).
dataItem | (Mandatory) | The index of the data point within the data set. The first data point is 0, while the nth data point is (n-1).
offsetX | 0 | An offset to be added to all x coordinates in the image map. This is useful if the current image will be shifted and inserted into another image. In this case, the image map will need to be shifted by the same offset.
offsetY | 0 | An offset to be added to all y coordinates in the image map. See offsetX above for description.

Return Value

A text string representing the coordinates of the data point as represented in the layer in HTML image map attribute format.


Layer.getImageCoor2

Layer.getImageCoor2

Usage

getImageCoor2(dataItem [, offsetX, offsetY ])

Description

Gets the image map coordinates of a region containing all data points at the given x-position as HTML image map attributes.

For example, in a stacked bar chart, this method will obtain the image map coordinates of the whole stacked bar, which contains multiple data points at the same x-position.

The image map coordinates will be in the following format:

shape="" cords="[x1],[y1],[x2],[y2] ..."

This format is specially designed so that it can easily be included into HTML image maps.

This method should be called only after creating the chart image (eg. using BaseChart.makeSession, BaseChart.makeChart or BaseChart.makeChart2). The image map cannot be determined without creating the chart image first.

Arguments

Argument | Default | Description
dataItem | (Mandatory) | The x-position of the data points.
offsetX | 0 | An offset to be added to all x coordinates in the image map. This is useful if the current image will be shifted and inserted into another image. In this case, the image map will need to be shifted by the same offset.
offsetY | 0 | An offset to be added to all y coordinates in the image map. See offsetX above for description.

Return Value

A text string representing the image map coordinates of a region containing all data points at the given x-position as HTML image map attributes.


Layer.getHTMLImageMap

Layer.getHTMLImageMap

Usage

getHTMLImageMap(url [, queryFormat [, extraAttr [, offsetX, offsetY ]]])

Description

Generates an HTML image map for all data points as represented on the layer.

Please refer to BaseChart.getHTMLImageMap for the detail description of this method.

This method should be called only after creating the chart image (eg. using BaseChart.makeSession, BaseChart.makeChart or BaseChart.makeChart2). The image map cannot be determined without creating the chart image first.

Arguments

Argument | Default | Description
url | (Mandatory) | The URL to be used in the "href" attribute of the image map. Parameter Substitution and Formatting is supported. Use an empty string if no href attribute is needed.
queryFormat | "" | A text string representing the template of the query parameters to be appended to the URL. Parameter Substitution and Formatting is supported. The special keyword "{default}" represents the default query parameters. This is useful for specifying appending to the default. Note that an empty string means to use the default query query parameters. To specify no query parameter, use a space character.
extraAttr | "" | A text string to specify additional attributes to add to the <area> tag. Parameter Substitution and Formatting is supported.
offsetX | 0 | An offset to be added to all x coordinates in the image map. This is useful if the current image will be shifted and inserted into another image. In this case, the image map will need to be shifted by the same offset.
offsetY | 0 | An offset to be added to all y coordinates in the image map. See offsetX above for description.

Return Value

A text string containing the image map generated.


Layer.setHTMLImageMap

Layer.setHTMLImageMap

Usage

setHTMLImageMap(url [, queryFormat [, extraAttr ]])

Description

Override the default arguments used when generating HTML image map for the layer.

BaseChart.getHTMLImageMap can be used to generate HTML image map for the whole chart. When BaseChart.getHTMLImageMap is used, the image map for all layers will be generated based on the arguments supplied to BaseChart.getHTMLImageMap.

The setHTMLImageMap method can be used to override those arguments for a chart layer, so the image map for that layer can be different.

For a detail description of image maps, please refer to BaseChart.getHTMLImageMap.

Arguments

Argument | Default | Description
url | (Mandatory) | The URL to be used in the "href" attribute of the image map. Parameter Substitution and Formatting is supported. The special keyword "{default}" represents the global URL as specified in BaseChart.getHTMLImageMap. This field is useful for specifying appending to the global URL. Note that an empty string also means to use the global URL. To specify no URL, use the special keyword "{none}". To disable the entire image map, use the special keyword "{disable}".
queryFormat | "" | A text string representing the template of the query parameters to be appended to the URL. Parameter Substitution and Formatting is supported. The special keyword "{default}" represents the global query parameters as specified in BaseChart.getHTMLImageMap. This field is useful for specifying appending to the global query parameters. Note that an empty string also means to use the global query parameters. To specify no query parameters, use the special keyword "{none}".
extraAttr | "" | A text string to specify additional attributes to add to the <area> tag. Parameter Substitution and Formatting is supported. The special keyword "{default}" represents the global additional attributes as specified in BaseChart.getHTMLImageMap. This field is useful for specifying appending to the global additional attributes. Note that an empty string also means to use the global additional attributes. To specify no additional attributes, use the special keyword "{none}".

Return Value

None


BarLayer

BarLayer

The BarLayer class represents bar layers. BarLayer is a subclass of Layer.

BarLayer objects are created using XYChart.addBarLayer, XYChart.addBarLayer2 and XYChart.addBarLayer3.

Method | Inherited | Description
setBarGap | (Self) | Sets the gap between the bars in a bar chart layer.
setBarWidth | (Self) | Sets the width of the bars.
setOverlapRatio | (Self) | Sets overlapping among bars in within a bar group in a multi-bar chart.
setBarShape | (Self) | Sets the shape of the bar(s) using built-in shapes.
setBarShape2 | (Self) | Sets the shape of the bar(s) to a custom shape defined using an array of (x, y) coordinates.
setMinLabelSize | (Self) | Sets the minimum height (or width for horizontal bars) of the bar segments below which data labels will be hidden.
setIconSize | (Self) | Sets the size of the icon(s) to be used in legend box.
set3D | Layer | Sets the 3D depth of the layer, and the 3D gap between the current layer and the next layer.
setLineWidth | Layer | Sets the default line width of lines when drawing data sets on the layer.
setBorderColor | Layer | Sets the default border color and 3D raised effect when drawing data sets on the layer.
setLegendOrder | Layer | Sets the order of the data set names as appeared in the legend box.
setLegend | Layer | Sets the order of the data set names as appeared in the legend box.
setDataCombineMethod | Layer | Sets the method used to combine multiple data sets in a layer.
addDataSet | Layer | Adds a data set to the chart layer.
getDataSet | Layer | Gets the requested DataSet object.
addDataGroup | Layer | Open a new data group.
addExtraField | Layer | Adds an array of text to be used as an extra field in various places.
addExtraField2 | Layer | Adds an array of numbers/dates to be used as an extra field in various places.
setUseYAxis | Layer | Determine the y-axis to use when drawing the data sets.
setUseYAxis2 | Layer | Determine if the primary or secondary y-axis should be used when drawing the data sets.
setXData | Layer | Sets the x values of the data points in the data sets.
setXData2 | Layer | Sets the x values of the data points in the data sets as evenly distributed in a range.
alignLayer | Layer | Aligns the layer with a data set of another bar chart layer in Side layout.
getXCoor | Layer | Gets the x pixel coordinate of a point given the x data value.
getYCoor | Layer | Gets the y pixel coordinate of a point given the y data value.
xZoneColor | Layer | Creates a x-zone color. A x-zone will change from one color to another depending on a threshold value on the x-axis.
yZoneColor | Layer | Creates a y-zone color. A y-zone will change from one color to another depending on a threshold value on the y-axis.
setDataLabelStyle | Layer | Enables data labels and sets their styles.
setDataLabelFormat | Layer | Sets the data label format.
addCustomDataLabel | Layer | Adds a custom data label to a data point.
setAggregateLabelStyle | Layer | Enables aggregate labels and sets their styles.
setAggregateLabelFormat | Layer | Sets the aggregate label format.
addCustomAggregateLabel | Layer | Adds a custom aggregate label to an aggregated object.
addCustomGroupLabel | Layer | Adds a custom data group label to object representing the group.
getImageCoor | Layer | Gets the image map coordinates of a data point as represented in the layer as HTML image map attributes.
getImageCoor2 | Layer | Gets the image map coordinates of a region containing all data points at the given x-position as HTML image map attributes.
getHTMLImageMap | Layer | Generates an HTML image map for all data points as represented on the layer.
setHTMLImageMap | Layer | Override the default arguments used when generating HTML image map for the layer.


BarLayer.setBarGap

BarLayer.setBarGap

Usage

setBarGap(barGap [, subBarGap ])

Description

Sets the gap between the bars in a bar chart layer.

In the setBarGap method, the gap between the bars is expressed as the portion of the space between the bars. For example, a bar gap of 0.2 means 20% of the distance between two adjacent bars is the gap between the bars.

A bar gap of 0 means there is no gap in between the bars. The bar gap can be negative. In this case, the bars will overlap. The predefined constant TouchBar ( = -1.7E-100) means the bars will "touch", that is, the bar borders overlap, so two adjacent bars will share the same border.

For multi-bar layers (bar layers using the Side data combine method, or for stacked bar layers with multiple data groups), barGap refers to the portion of the space between bar groups, while subBarGap refers to the portion of the space between bars within the bar group.

Arguments

Argument | Default | Description
barGap | (Mandatory) | The portion of the space between the bars (or between bar groups for multi-bar layers).
subBarGap | 0.2 | This argument only applies to multi-bar charts. It is the portion of the space between the bars in a bar group.

Return Value

None


BarLayer.setBarWidth

BarLayer.setBarWidth

Usage

setBarWidth(barWidth [, subBarWidth ])

Description

Sets the width of the bars.

Arguments

Argument | Default | Description
barWidth | (Mandatory) | The width of the bars (or bar groups for multi-bar layers) in pixels.
subBarWidth | -1 | This argument only applies to multi-bar charts. It is the width of the bars in a bar group in pixels.

Return Value

None


BarLayer.setOverlapRatio

BarLayer.setOverlapRatio

Usage

setOverlapRatio(overlapRatio [, firstOnTop ])

Description

Sets overlapping among bars in within a bar group in a multi-bar chart.

By default, in a multi-bar chart, the bars are not overlapped, but are separated with a gap in between. This method can be used to set an alternative style, where the bars partially overlap.

Arguments

Argument | Default | Description
overlapRatio | (Mandatory) | The overlapping ratio between adjacent bars in a bar group. Should be between 0 to 1.
firstOnTop | true (non-zero) | If this value is true (non-zero), the first data set will be on top of the second data during overlapping, and the second data set will be on top of the third data set, and so on. If this value is false (zero), then the overlapping order will be reversed.

Return Value

None


BarLayer.setBarShape

BarLayer.setBarShape

Usage

setBarShape(shape [, dataGroup [, dataItem ]])

Description

Sets the shape of the bar(s) using built-in shapes.

Arguments

Argument | Default | Description
shape | (Mandatory) | The bar shape to use. Please refer to Shape Specification on how shapes are specified.
dataGroup | -1 | The index of the data group that the shape applies to. In a multi-stacked bar, the data sets that are stacked up into a single bar forms a data group. In a multi-bar chart, each data set is a data group by itself. The default value of -1 means the shape applies to all data groups.
dataItem | -1 | The index of the data points that the shape applies to. For example, if set to 3, the shape will only apply to the 4th bar (index starts from 0) in each data series. The default value of -1 means the shape applies to all data points.

Return Value

None


BarLayer.setBarShape2

BarLayer.setBarShape2

Usage

setBarShape2(shape [, dataGroup [, dataItem ]])

Description

Sets the shape of the bar(s) to a custom shape defined using an array of (x, y) coordinates.

Arguments

Argument | Default | Description
shape | (Mandatory) | The bar shape to use. Please refer to Shape Specification on how shapes are specified.
dataGroup | -1 | The index of the data group that the shape applies to. In a multi-stacked bar, the data sets that are stacked up into a single bar forms a data group. In a multi-bar chart, each data set is a data group by itself. The default value of -1 means the shape applies to all data groups.
dataItem | -1 | The index of the data points that the shape applies to. For example, if set to 3, the shape will only apply to the 4th bar (index starts from 0) in each data series. The default value of -1 means the shape applies to all data points.

Return Value

None


BarLayer.setMinLabelSize

BarLayer.setMinLabelSize

Usage

setMinLabelSize(s)

Description

Sets the minimum height (or width for horizontal bars) of the bar segments below which data labels will be hidden.

In ChartDirector, for a bar layer, data labels (Layer.setDataLabelStyle) are drawn internal to the bar segment, while the aggregate labels (Layer.setAggregateLabelStyle) are drawn external to the bar.

ChartDirector will disable data labels for a bar segment if the bar segment is too short to contain the data label.

By default, ChartDirector will automatically determine what is meant by "too short". The setMinLabelSize method can be used to manually defined the threshold for "too short".

Sometimes it may be desirable to display the data label even though it cannot be contained within the bar segment. In this case, the setMinLabelSize can be used to set the threshold to 0.

Arguments

Argument | Default | Description
s | (Mandatory) | The minimum length of the bar segments in pixels, below which data labels will be hidden.

Return Value

None


BarLayer.setIconSize

BarLayer.setIconSize

Usage

setIconSize(height [, width ])

Description

Sets the size of the icon(s) to be used in legend box.

By default, if a legend box is available on the chart, ChartDirector will insert an legend entry for any named data sets in the legend box. The icons for the data sets will be the shape of the bars. The size of the icons will be determined using the key size settings of the legend box (see LegendBox.setKeySize).

This method can be used to override the legend box settings to specify a custom width/height for the icons of the current BarLayer.

If the icon size is set to 0, a square color box will be used as the icon without regarding the shape of the bar.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the icon in pixels.
width | -1 | The width of the icon in pixels. The default value of -1 means the width is the same as the height.

Return Value

None


LineLayer

LineLayer

The LineLayer class represents line layers. LineLayer is a subclass of Layer.

LineLayer objects are created by using XYChart.addLineLayer and XYChart.addLineLayer2.

Method | Inherited | Description
setSymbolScale | (Self) | Sets the size of the symbol for each data point (for creating bubble charts).
setGapColor | (Self) | Sets the color and style of the line used for jumping across NoValue data points.
setImageMapWidth | (Self) | Sets the effective width of the line used for producing image maps.
getLine | (Self) | Retrieves an opaque LineObj representing a line in the line layer. The opaque LineObj is to be used in XYChart.addInterLineLayer for adding coloring between lines.
set3D | Layer | Sets the 3D depth of the layer, and the 3D gap between the current layer and the next layer.
setLineWidth | Layer | Sets the default line width of lines when drawing data sets on the layer.
setBorderColor | Layer | Sets the default border color and 3D raised effect when drawing data sets on the layer.
setLegendOrder | Layer | Sets the order of the data set names as appeared in the legend box.
setLegend | Layer | Sets the order of the data set names as appeared in the legend box.
setDataCombineMethod | Layer | Sets the method used to combine multiple data sets in a layer.
addDataSet | Layer | Adds a data set to the chart layer.
getDataSet | Layer | Gets the requested DataSet object.
addDataGroup | Layer | Open a new data group.
addExtraField | Layer | Adds an array of text to be used as an extra field in various places.
addExtraField2 | Layer | Adds an array of numbers/dates to be used as an extra field in various places.
setUseYAxis | Layer | Determine the y-axis to use when drawing the data sets.
setUseYAxis2 | Layer | Determine if the primary or secondary y-axis should be used when drawing the data sets.
setXData | Layer | Sets the x values of the data points in the data sets.
setXData2 | Layer | Sets the x values of the data points in the data sets as evenly distributed in a range.
alignLayer | Layer | Aligns the layer with a data set of another bar chart layer in Side layout.
getXCoor | Layer | Gets the x pixel coordinate of a point given the x data value.
getYCoor | Layer | Gets the y pixel coordinate of a point given the y data value.
xZoneColor | Layer | Creates a x-zone color. A x-zone will change from one color to another depending on a threshold value on the x-axis.
yZoneColor | Layer | Creates a y-zone color. A y-zone will change from one color to another depending on a threshold value on the y-axis.
setDataLabelStyle | Layer | Enables data labels and sets their styles.
setDataLabelFormat | Layer | Sets the data label format.
addCustomDataLabel | Layer | Adds a custom data label to a data point.
setAggregateLabelStyle | Layer | Enables aggregate labels and sets their styles.
setAggregateLabelFormat | Layer | Sets the aggregate label format.
addCustomAggregateLabel | Layer | Adds a custom aggregate label to an aggregated object.
addCustomGroupLabel | Layer | Adds a custom data group label to object representing the group.
getImageCoor | Layer | Gets the image map coordinates of a data point as represented in the layer as HTML image map attributes.
getImageCoor2 | Layer | Gets the image map coordinates of a region containing all data points at the given x-position as HTML image map attributes.
getHTMLImageMap | Layer | Generates an HTML image map for all data points as represented on the layer.
setHTMLImageMap | Layer | Override the default arguments used when generating HTML image map for the layer.


LineLayer.setSymbolScale

LineLayer.setSymbolScale

Usage

setSymbolScale(zDataX [, scaleTypeX [, zDataY [, scaleTypeY ]]])

Description

Sets the size of the symbol for each data point (for creating bubble charts).

One common usage for this method is to draw circle symbols of different sizes at each data points, creating a bubble chart.

This method supports any valid data symbols. You can create bubble charts with square bubbles, or even custom data symbols. Also, this method supports independent x and y direction sizing, so you can create bubbles elliptical in shape, and use the horizontal and vertical radius to represent different data.

ChartDirector supports specifying sizes as pixels or in axis scale. The unit is specified by using the following predefined constants.

Constant | Value | Description
PixelScale | 0 | The unit is measured in pixels.
XAxisScale | 1 | The unit is measured in x-axis scale.
YAxisScale | 2 | The unit is measured in y-axis scale.

Arguments

Argument | Default | Description
zDataX | (Mandatory) | The sizes of the symbols at the x-axis direction, expressed using the unit defined by the scaleTypeX argument.
scaleTypeX | PixelScale | The unit for zDataX, which must be one of the predefined constants in the table above.
zDataY | [Empty_Array] | The sizes of the symbols at the y-axis direction, expressed using the unit defined by the scaleTypeY argument. An empty array means the sizes at the y-axis direction are the means as the sizes at the x-axis direction.
scaleTypeY | PixelScale | The unit for zDataY, which must be one of the predefined constants in the table above.

Return Value

None


LineLayer.setGapColor

LineLayer.setGapColor

Usage

setGapColor(lineColor [, lineWidth ])

Description

Sets the color and style of the line used for jumping across NoValue data points.

By default, the color of the line for jumping across NoValue data points is Transparent, which means the line will become discontinuous.

Arguments

Argument | Default | Description
lineColor | (Mandatory) | The line color of the line used for jumping across NoValue data points
lineWidth | -1 | The line width of the line used for jumping across NoValue data points. -1 means the width will be the same as the line width of the line for drawing normal data points.

Return Value

None


LineLayer.setImageMapWidth

LineLayer.setImageMapWidth

Usage

setImageMapWidth(width)

Description

Sets the effective width of the line used for producing image maps.

For thin lines, it is hard to click on the lines. So for the purpose of producing image maps for a line chart, ChartDirector can assume the line is very thick. The default is 10 pixels.

Arguments

Argument | Default | Description
width | (Mandatory) | The effective width of the line used for producing image maps.

Return Value

None


LineLayer.getLine

LineLayer.getLine

Usage

getLine([ dataSet ])

Description

Retrieves an opaque LineObj representing a line in the line layer. The opaque LineObj is to be used in XYChart.addInterLineLayer for adding coloring between lines.

Arguments

Argument | Default | Description
dataSet | 0 | The data set number for the line. The first data set is 0. The nth data set is (n - 1).

Return Value

An opaque LineObj representing the requested line.


SplineLayer

SplineLayer

The SplineLayer class represents spline layers. SplineLayer is a subclass of Layer.

In the current version of ChartDirector, SplineLayer is implemented as a special configuration of LineLayer.

SplineLayer objects are created by using XYChart.addSplineLayer.

Method | Inherited | Description
setTension | (Self) | Sets the tension to use when computing the spline curve.
setSymbolScale | LineLayer | Sets the size of the symbol for each data point (for creating bubble charts).
setGapColor | LineLayer | Sets the color and style of the line used for jumping across NoValue data points.
setImageMapWidth | LineLayer | Sets the effective width of the line used for producing image maps.
getLine | LineLayer | Retrieves an opaque LineObj representing a line in the line layer. The opaque LineObj is to be used in XYChart.addInterLineLayer for adding coloring between lines.
set3D | Layer | Sets the 3D depth of the layer, and the 3D gap between the current layer and the next layer.
setLineWidth | Layer | Sets the default line width of lines when drawing data sets on the layer.
setBorderColor | Layer | Sets the default border color and 3D raised effect when drawing data sets on the layer.
setLegendOrder | Layer | Sets the order of the data set names as appeared in the legend box.
setLegend | Layer | Sets the order of the data set names as appeared in the legend box.
setDataCombineMethod | Layer | Sets the method used to combine multiple data sets in a layer.
addDataSet | Layer | Adds a data set to the chart layer.
getDataSet | Layer | Gets the requested DataSet object.
addDataGroup | Layer | Open a new data group.
addExtraField | Layer | Adds an array of text to be used as an extra field in various places.
addExtraField2 | Layer | Adds an array of numbers/dates to be used as an extra field in various places.
setUseYAxis | Layer | Determine the y-axis to use when drawing the data sets.
setUseYAxis2 | Layer | Determine if the primary or secondary y-axis should be used when drawing the data sets.
setXData | Layer | Sets the x values of the data points in the data sets.
setXData2 | Layer | Sets the x values of the data points in the data sets as evenly distributed in a range.
alignLayer | Layer | Aligns the layer with a data set of another bar chart layer in Side layout.
getXCoor | Layer | Gets the x pixel coordinate of a point given the x data value.
getYCoor | Layer | Gets the y pixel coordinate of a point given the y data value.
xZoneColor | Layer | Creates a x-zone color. A x-zone will change from one color to another depending on a threshold value on the x-axis.
yZoneColor | Layer | Creates a y-zone color. A y-zone will change from one color to another depending on a threshold value on the y-axis.
setDataLabelStyle | Layer | Enables data labels and sets their styles.
setDataLabelFormat | Layer | Sets the data label format.
addCustomDataLabel | Layer | Adds a custom data label to a data point.
setAggregateLabelStyle | Layer | Enables aggregate labels and sets their styles.
setAggregateLabelFormat | Layer | Sets the aggregate label format.
addCustomAggregateLabel | Layer | Adds a custom aggregate label to an aggregated object.
addCustomGroupLabel | Layer | Adds a custom data group label to object representing the group.
getImageCoor | Layer | Gets the image map coordinates of a data point as represented in the layer as HTML image map attributes.
getImageCoor2 | Layer | Gets the image map coordinates of a region containing all data points at the given x-position as HTML image map attributes.
getHTMLImageMap | Layer | Generates an HTML image map for all data points as represented on the layer.
setHTMLImageMap | Layer | Override the default arguments used when generating HTML image map for the layer.


SplineLayer.setTension

SplineLayer.setTension

Usage

setTension(tension)

Description

Sets the tension to use when computing the spline curve.

The tension parameter should be between -1 and 1. A positive tension will make the spline tighter. The spline curve will become straight line segments when tension is 1. A negative tension will make the spline looser.

Arguments

Argument | Default | Description
tension | (Mandatory) | The tension of the spline, which should be between -1 and 1.

Return Value

None


StepLineLayer

StepLineLayer

The StepLineLayer class represents step line layers. StepLineLayer is a subclass of LineLayer.

StepLineLayer objects are created by using XYChart.addStepLineLayer.

Method | Inherited | Description
setAlignment | (Self) | Sets the alignment of the steps relative to the data points.
setSymbolScale | LineLayer | Sets the size of the symbol for each data point (for creating bubble charts).
setGapColor | LineLayer | Sets the color and style of the line used for jumping across NoValue data points.
setImageMapWidth | LineLayer | Sets the effective width of the line used for producing image maps.
getLine | LineLayer | Retrieves an opaque LineObj representing a line in the line layer. The opaque LineObj is to be used in XYChart.addInterLineLayer for adding coloring between lines.
set3D | Layer | Sets the 3D depth of the layer, and the 3D gap between the current layer and the next layer.
setLineWidth | Layer | Sets the default line width of lines when drawing data sets on the layer.
setBorderColor | Layer | Sets the default border color and 3D raised effect when drawing data sets on the layer.
setLegendOrder | Layer | Sets the order of the data set names as appeared in the legend box.
setLegend | Layer | Sets the order of the data set names as appeared in the legend box.
setDataCombineMethod | Layer | Sets the method used to combine multiple data sets in a layer.
addDataSet | Layer | Adds a data set to the chart layer.
getDataSet | Layer | Gets the requested DataSet object.
addDataGroup | Layer | Open a new data group.
addExtraField | Layer | Adds an array of text to be used as an extra field in various places.
addExtraField2 | Layer | Adds an array of numbers/dates to be used as an extra field in various places.
setUseYAxis | Layer | Determine the y-axis to use when drawing the data sets.
setUseYAxis2 | Layer | Determine if the primary or secondary y-axis should be used when drawing the data sets.
setXData | Layer | Sets the x values of the data points in the data sets.
setXData2 | Layer | Sets the x values of the data points in the data sets as evenly distributed in a range.
alignLayer | Layer | Aligns the layer with a data set of another bar chart layer in Side layout.
getXCoor | Layer | Gets the x pixel coordinate of a point given the x data value.
getYCoor | Layer | Gets the y pixel coordinate of a point given the y data value.
xZoneColor | Layer | Creates a x-zone color. A x-zone will change from one color to another depending on a threshold value on the x-axis.
yZoneColor | Layer | Creates a y-zone color. A y-zone will change from one color to another depending on a threshold value on the y-axis.
setDataLabelStyle | Layer | Enables data labels and sets their styles.
setDataLabelFormat | Layer | Sets the data label format.
addCustomDataLabel | Layer | Adds a custom data label to a data point.
setAggregateLabelStyle | Layer | Enables aggregate labels and sets their styles.
setAggregateLabelFormat | Layer | Sets the aggregate label format.
addCustomAggregateLabel | Layer | Adds a custom aggregate label to an aggregated object.
addCustomGroupLabel | Layer | Adds a custom data group label to object representing the group.
getImageCoor | Layer | Gets the image map coordinates of a data point as represented in the layer as HTML image map attributes.
getImageCoor2 | Layer | Gets the image map coordinates of a region containing all data points at the given x-position as HTML image map attributes.
getHTMLImageMap | Layer | Generates an HTML image map for all data points as represented on the layer.
setHTMLImageMap | Layer | Override the default arguments used when generating HTML image map for the layer.


StepLineLayer.setAlignment

StepLineLayer.setAlignment

Usage

setAlignment(a)

Description

Sets the alignment of the steps relative to the data points.

Arguments

Argument | Default | Description
a | (Mandatory) | The alignment of the steps relative to the data points. Must be one of the predefined constants Left, Center or Right.

Return Value

None


TrendLayer

TrendLayer

The TrendLayer class represents trend layers. TrendLayer is a subclass Layer.

TrendLayer objects are created by using XYChart.addTrendLayer and XYChart.addTrendLayer2.

The trend layer performs linear regression analysis on the data points, and represents the result as a best fit straight line with optional confidence and prediction bands.

In linear regression analysis, the data points are assumed to be related by:

y = m * x + c + err

where m and c are constants, and err is a random variable.

Linear regression analysis estimates m, c and err based on available data using the least square method. Using estimated values of m and c, the line y = m * x + c are plotted as the best fit straight line based on available data.

However, as m and c are estimations based on available data, it may not be exactly equal to the "real" m and c. In ChartDirector, the uncertainties are represented visually as a confidence band around the regression line. For example, the 95% confidence band means there are 95% probability that the "real" line is in that band.

To predict a data point (infer y given x), we can use the formula:

y = m * x + c + err

based on estimated values of m, c and err.

The uncertainties of the data point is contributed by the uncertainties in m and c, as well as err. In ChartDirector, the uncertainties of the data points are represented visually as a prediction band around the regression line. For example, a 95% prediction band means there are 95% probability that a data point will be in that band.

The prediction band is always wider than the confidence band. It is because the uncertainties of the regression line is contributed by m and c, while the uncertainties of the data points are contributed by m, c and err. The err term makes the data points less certain that the regression line.

Method | Inherited | Description
addConfidenceBand | (Self) | Adds a confidence band to the trend layer.
addPredictionBand | (Self) | Adds a prediction band to the trend layer.
getSlope | (Self) | Gets the slope of the trend line.
getIntercept | (Self) | Gets the y-axis intercept of the trend line.
getCorrelation | (Self) | Gets the correlation coefficient of the trend line.
getStdError | (Self) | Gets the standard error of the trend line.
setImageMapWidth | (Self) | Sets the effective width of the line used for producing image maps.
getLine | (Self) | Retrieves an opaque LineObj representing the trend line. The opaque LineObj is to be used in XYChart.addInterLineLayer for adding coloring between lines.
set3D | Layer | Sets the 3D depth of the layer, and the 3D gap between the current layer and the next layer.
setLineWidth | Layer | Sets the default line width of lines when drawing data sets on the layer.
setBorderColor | Layer | Sets the default border color and 3D raised effect when drawing data sets on the layer.
setLegendOrder | Layer | Sets the order of the data set names as appeared in the legend box.
setLegend | Layer | Sets the order of the data set names as appeared in the legend box.
setDataCombineMethod | Layer | Sets the method used to combine multiple data sets in a layer.
addDataSet | Layer | Adds a data set to the chart layer.
getDataSet | Layer | Gets the requested DataSet object.
addDataGroup | Layer | Open a new data group.
addExtraField | Layer | Adds an array of text to be used as an extra field in various places.
addExtraField2 | Layer | Adds an array of numbers/dates to be used as an extra field in various places.
setUseYAxis | Layer | Determine the y-axis to use when drawing the data sets.
setUseYAxis2 | Layer | Determine if the primary or secondary y-axis should be used when drawing the data sets.
setXData | Layer | Sets the x values of the data points in the data sets.
setXData2 | Layer | Sets the x values of the data points in the data sets as evenly distributed in a range.
alignLayer | Layer | Aligns the layer with a data set of another bar chart layer in Side layout.
getXCoor | Layer | Gets the x pixel coordinate of a point given the x data value.
getYCoor | Layer | Gets the y pixel coordinate of a point given the y data value.
xZoneColor | Layer | Creates a x-zone color. A x-zone will change from one color to another depending on a threshold value on the x-axis.
yZoneColor | Layer | Creates a y-zone color. A y-zone will change from one color to another depending on a threshold value on the y-axis.
setDataLabelStyle | Layer | Enables data labels and sets their styles.
setDataLabelFormat | Layer | Sets the data label format.
addCustomDataLabel | Layer | Adds a custom data label to a data point.
setAggregateLabelStyle | Layer | Enables aggregate labels and sets their styles.
setAggregateLabelFormat | Layer | Sets the aggregate label format.
addCustomAggregateLabel | Layer | Adds a custom aggregate label to an aggregated object.
addCustomGroupLabel | Layer | Adds a custom data group label to object representing the group.
getImageCoor | Layer | Gets the image map coordinates of a data point as represented in the layer as HTML image map attributes.
getImageCoor2 | Layer | Gets the image map coordinates of a region containing all data points at the given x-position as HTML image map attributes.
getHTMLImageMap | Layer | Generates an HTML image map for all data points as represented on the layer.
setHTMLImageMap | Layer | Override the default arguments used when generating HTML image map for the layer.


TrendLayer.addConfidenceBand

TrendLayer.addConfidenceBand

Usage

addConfidenceBand(confidence, upperFillColor [, upperEdgeColor [, upperLineWidth [, lowerFillColor [, lowerEdgeColor [, lowerLineWidth ]]]]])

Description

Adds a confidence band to the trend layer.

Please refer to the description of TrendLayer on what is a confidence band.

Arguments

Argument | Default | Description
confidence | (Mandatory) | The confidence level - must be between 0 - 1.
upperFillColor | (Mandatory) | The fill color for the upper side of the confidence band (the portion that is above the regression line).
upperEdgeColor | Transparent | The border color for the upper side of the confidence band (the portion that is above the regression line).
upperLineWidth | 1 | The border width for the upper side of the confidence band (the portion that is above the regression line).
lowerFillColor | -1 | The fill color for the lower side of the confidence band (the portion that is below the regression line). -1 means the color is the same as upperFillColor.
lowerEdgeColor | -1 | The border color for the lower side of the confidence band (the portion that is below the regression line). -1 means the color is the same as upperEdgeColor.
lowerLineWidth | -1 | The border width for the lower side of the confidence band (the portion that is below the regression line). -1 means the color is the same as upperLineWidth.

Return Value

None


TrendLayer.addPredictionBand

TrendLayer.addPredictionBand

Usage

addPredictionBand(confidence, upperFillColor [, upperEdgeColor [, upperLineWidth [, lowerFillColor [, lowerEdgeColor [, lowerLineWidth ]]]]])

Description

Adds a prediction band to the trend layer.

Please refer to the description of TrendLayer on what is a prediction band.

Arguments

Argument | Default | Description
confidence | (Mandatory) | The confidence level - must be between 0 - 1.
upperFillColor | (Mandatory) | The fill color for the upper side of the prediction band (the portion that is above the regression line).
upperEdgeColor | Transparent | The border color for the upper side of the prediction band (the portion that is above the regression line).
upperLineWidth | 1 | The border width for the upper side of the prediction band (the portion that is above the regression line).
lowerFillColor | -1 | The fill color for the lower side of the prediction band (the portion that is below the regression line). -1 means the color is the same as upperFillColor.
lowerEdgeColor | -1 | The border color for the lower side of the prediction band (the portion that is below the regression line). -1 means the color is the same as upperEdgeColor.
lowerLineWidth | -1 | The border width for the lower side of the prediction band (the portion that is below the regression line). -1 means the color is the same as upperLineWidth.

Return Value

None


TrendLayer.getSlope

TrendLayer.getSlope

Usage

getSlope()

Description

Gets the slope of the trend line.

Arguments

None

Return Value

None


TrendLayer.getIntercept

TrendLayer.getIntercept

Usage

getIntercept()

Description

Gets the y-axis intercept of the trend line.

Arguments

None

Return Value

None


TrendLayer.getCorrelation

TrendLayer.getCorrelation

Usage

getCorrelation()

Description

Gets the correlation coefficient of the trend line.

Arguments

None

Return Value

None


TrendLayer.getStdError

TrendLayer.getStdError

Usage

getStdError()

Description

Gets the standard error of the trend line.

Arguments

None

Return Value

None


TrendLayer.setImageMapWidth

TrendLayer.setImageMapWidth

Usage

setImageMapWidth(width)

Description

Sets the effective width of the line used for producing image maps.

For thin lines, it is hard to click on the lines. So for the purpose of producing image maps for a line chart, ChartDirector can assume the line is very thick. The default is 10 pixels.

Arguments

Argument | Default | Description
width | (Mandatory) | The effective width of the line used for producing image maps.

Return Value

None


TrendLayer.getLine

TrendLayer.getLine

Usage

getLine()

Description

Retrieves an opaque LineObj representing the trend line. The opaque LineObj is to be used in XYChart.addInterLineLayer for adding coloring between lines.

Arguments

None

Return Value

An opaque LineObj representing the trend line.


InterLineLayer

InterLineLayer

The InterLineLayer class represents interline layers. InterLineLayer is a subclass of Layer.

Interline layers are used to color the region between two lines. The lines can come from a variety of layer types, such as line layers, spline layers, step line layers, trend layers or axis mark lines.

InterLineLayer objects are created by using XYChart.addInterLineLayer.

Method | Inherited | Description
setGapColor | (Self) | Sets the color used to fill the area under NoValue data points.
set3D | Layer | Sets the 3D depth of the layer, and the 3D gap between the current layer and the next layer.
setLineWidth | Layer | Sets the default line width of lines when drawing data sets on the layer.
setBorderColor | Layer | Sets the default border color and 3D raised effect when drawing data sets on the layer.
setLegendOrder | Layer | Sets the order of the data set names as appeared in the legend box.
setLegend | Layer | Sets the order of the data set names as appeared in the legend box.
setDataCombineMethod | Layer | Sets the method used to combine multiple data sets in a layer.
addDataSet | Layer | Adds a data set to the chart layer.
getDataSet | Layer | Gets the requested DataSet object.
addDataGroup | Layer | Open a new data group.
addExtraField | Layer | Adds an array of text to be used as an extra field in various places.
addExtraField2 | Layer | Adds an array of numbers/dates to be used as an extra field in various places.
setUseYAxis | Layer | Determine the y-axis to use when drawing the data sets.
setUseYAxis2 | Layer | Determine if the primary or secondary y-axis should be used when drawing the data sets.
setXData | Layer | Sets the x values of the data points in the data sets.
setXData2 | Layer | Sets the x values of the data points in the data sets as evenly distributed in a range.
alignLayer | Layer | Aligns the layer with a data set of another bar chart layer in Side layout.
getXCoor | Layer | Gets the x pixel coordinate of a point given the x data value.
getYCoor | Layer | Gets the y pixel coordinate of a point given the y data value.
xZoneColor | Layer | Creates a x-zone color. A x-zone will change from one color to another depending on a threshold value on the x-axis.
yZoneColor | Layer | Creates a y-zone color. A y-zone will change from one color to another depending on a threshold value on the y-axis.
setDataLabelStyle | Layer | Enables data labels and sets their styles.
setDataLabelFormat | Layer | Sets the data label format.
addCustomDataLabel | Layer | Adds a custom data label to a data point.
setAggregateLabelStyle | Layer | Enables aggregate labels and sets their styles.
setAggregateLabelFormat | Layer | Sets the aggregate label format.
addCustomAggregateLabel | Layer | Adds a custom aggregate label to an aggregated object.
addCustomGroupLabel | Layer | Adds a custom data group label to object representing the group.
getImageCoor | Layer | Gets the image map coordinates of a data point as represented in the layer as HTML image map attributes.
getImageCoor2 | Layer | Gets the image map coordinates of a region containing all data points at the given x-position as HTML image map attributes.
getHTMLImageMap | Layer | Generates an HTML image map for all data points as represented on the layer.
setHTMLImageMap | Layer | Override the default arguments used when generating HTML image map for the layer.


InterLineLayer.setGapColor

InterLineLayer.setGapColor

Usage

setGapColor(gapColor12 [, gapColor21 ])

Description

Sets the color used to fill the area under NoValue data points.

By default, if there are NoValue data points on the lines, ChartDirector will interpolate across the points. The region will remain continuous.

This method can be used to set up an alternative colors to represent the regions at NoValue data point positions. In particular, if the colors are set to Transparent, the NoValue data points will result in gaps in the fill region.

Arguments

Argument | Default | Description
gapColor12 | (Mandatory) | The color used to fill the region under NoValue positions when value of the first line is greater of the value of the second line.
gapColor21 | -1 | The color used to fill the region under NoValue positions when value of the second line is greater of the value of the first line. The default value of -1 means it is the same as gapColor12.

Return Value

None


ScatterLayer

ScatterLayer

The ScatterLayer class represents scatter layers. ScatterLayer is a subclass of LineLayer.

ScatterLayer objects are created by using XYChart.addScatterLayer.

Method | Inherited | Description
setSymbolScale | LineLayer | Sets the size of the symbol for each data point (for creating bubble charts).
setGapColor | LineLayer | Sets the color and style of the line used for jumping across NoValue data points.
setImageMapWidth | LineLayer | Sets the effective width of the line used for producing image maps.
getLine | LineLayer | Retrieves an opaque LineObj representing a line in the line layer. The opaque LineObj is to be used in XYChart.addInterLineLayer for adding coloring between lines.
set3D | Layer | Sets the 3D depth of the layer, and the 3D gap between the current layer and the next layer.
setLineWidth | Layer | Sets the default line width of lines when drawing data sets on the layer.
setBorderColor | Layer | Sets the default border color and 3D raised effect when drawing data sets on the layer.
setLegendOrder | Layer | Sets the order of the data set names as appeared in the legend box.
setLegend | Layer | Sets the order of the data set names as appeared in the legend box.
setDataCombineMethod | Layer | Sets the method used to combine multiple data sets in a layer.
addDataSet | Layer | Adds a data set to the chart layer.
getDataSet | Layer | Gets the requested DataSet object.
addDataGroup | Layer | Open a new data group.
addExtraField | Layer | Adds an array of text to be used as an extra field in various places.
addExtraField2 | Layer | Adds an array of numbers/dates to be used as an extra field in various places.
setUseYAxis | Layer | Determine the y-axis to use when drawing the data sets.
setUseYAxis2 | Layer | Determine if the primary or secondary y-axis should be used when drawing the data sets.
setXData | Layer | Sets the x values of the data points in the data sets.
setXData2 | Layer | Sets the x values of the data points in the data sets as evenly distributed in a range.
alignLayer | Layer | Aligns the layer with a data set of another bar chart layer in Side layout.
getXCoor | Layer | Gets the x pixel coordinate of a point given the x data value.
getYCoor | Layer | Gets the y pixel coordinate of a point given the y data value.
xZoneColor | Layer | Creates a x-zone color. A x-zone will change from one color to another depending on a threshold value on the x-axis.
yZoneColor | Layer | Creates a y-zone color. A y-zone will change from one color to another depending on a threshold value on the y-axis.
setDataLabelStyle | Layer | Enables data labels and sets their styles.
setDataLabelFormat | Layer | Sets the data label format.
addCustomDataLabel | Layer | Adds a custom data label to a data point.
setAggregateLabelStyle | Layer | Enables aggregate labels and sets their styles.
setAggregateLabelFormat | Layer | Sets the aggregate label format.
addCustomAggregateLabel | Layer | Adds a custom aggregate label to an aggregated object.
addCustomGroupLabel | Layer | Adds a custom data group label to object representing the group.
getImageCoor | Layer | Gets the image map coordinates of a data point as represented in the layer as HTML image map attributes.
getImageCoor2 | Layer | Gets the image map coordinates of a region containing all data points at the given x-position as HTML image map attributes.
getHTMLImageMap | Layer | Generates an HTML image map for all data points as represented on the layer.
setHTMLImageMap | Layer | Override the default arguments used when generating HTML image map for the layer.


AreaLayer

AreaLayer

The AreaLayer class represents area layers. AreaLayer is a subclass of Layer.

AreaLayer objects are created by using XYChart.addAreaLayer and XYChart.addAreaLayer2.

Method | Inherited | Description
setGapColor | (Self) | Sets the color used to fill the area under NoValue data points.
setMinLabelSize | (Self) | Sets the minimum height (or width if x and y axes are swapped) of an area below which data labels will be hidden.
set3D | Layer | Sets the 3D depth of the layer, and the 3D gap between the current layer and the next layer.
setLineWidth | Layer | Sets the default line width of lines when drawing data sets on the layer.
setBorderColor | Layer | Sets the default border color and 3D raised effect when drawing data sets on the layer.
setLegendOrder | Layer | Sets the order of the data set names as appeared in the legend box.
setLegend | Layer | Sets the order of the data set names as appeared in the legend box.
setDataCombineMethod | Layer | Sets the method used to combine multiple data sets in a layer.
addDataSet | Layer | Adds a data set to the chart layer.
getDataSet | Layer | Gets the requested DataSet object.
addDataGroup | Layer | Open a new data group.
addExtraField | Layer | Adds an array of text to be used as an extra field in various places.
addExtraField2 | Layer | Adds an array of numbers/dates to be used as an extra field in various places.
setUseYAxis | Layer | Determine the y-axis to use when drawing the data sets.
setUseYAxis2 | Layer | Determine if the primary or secondary y-axis should be used when drawing the data sets.
setXData | Layer | Sets the x values of the data points in the data sets.
setXData2 | Layer | Sets the x values of the data points in the data sets as evenly distributed in a range.
alignLayer | Layer | Aligns the layer with a data set of another bar chart layer in Side layout.
getXCoor | Layer | Gets the x pixel coordinate of a point given the x data value.
getYCoor | Layer | Gets the y pixel coordinate of a point given the y data value.
xZoneColor | Layer | Creates a x-zone color. A x-zone will change from one color to another depending on a threshold value on the x-axis.
yZoneColor | Layer | Creates a y-zone color. A y-zone will change from one color to another depending on a threshold value on the y-axis.
setDataLabelStyle | Layer | Enables data labels and sets their styles.
setDataLabelFormat | Layer | Sets the data label format.
addCustomDataLabel | Layer | Adds a custom data label to a data point.
setAggregateLabelStyle | Layer | Enables aggregate labels and sets their styles.
setAggregateLabelFormat | Layer | Sets the aggregate label format.
addCustomAggregateLabel | Layer | Adds a custom aggregate label to an aggregated object.
addCustomGroupLabel | Layer | Adds a custom data group label to object representing the group.
getImageCoor | Layer | Gets the image map coordinates of a data point as represented in the layer as HTML image map attributes.
getImageCoor2 | Layer | Gets the image map coordinates of a region containing all data points at the given x-position as HTML image map attributes.
getHTMLImageMap | Layer | Generates an HTML image map for all data points as represented on the layer.
setHTMLImageMap | Layer | Override the default arguments used when generating HTML image map for the layer.


AreaLayer.setGapColor

AreaLayer.setGapColor

Usage

setGapColor(fillColor)

Description

Sets the color used to fill the area under NoValue data points.

By default, if there are NoValue data points, ChartDirector will interpolate using the remaining data points. The area will remain continuous.

This method can be used to set up an alternative color to represent the area at NoValue data point positions. In particular, if the fillColor argument is set to Transparent, the NoValue data points will result in gaps in the area.

Arguments

Argument | Default | Description
fillColor | (Mandatory) | The color used to fill the area region at NoValue data point positions.

Return Value

None


AreaLayer.setMinLabelSize

AreaLayer.setMinLabelSize

Usage

setMinLabelSize(s)

Description

Sets the minimum height (or width if x and y axes are swapped) of an area below which data labels will be hidden.

In ChartDirector, for an area layer, data labels (Layer.setDataLabelStyle) are drawn internal to the area, while the aggregate labels (Layer.setAggregateLabelStyle) are drawn external to the area.

ChartDirector will disable data labels if the area height (or width if x and y axes are swapped) is too small to contain the data label.

By default, ChartDirector will automatically determine what is meant by "too small". The setMinLabelSize method can be used to manually defined the threshold for "too small".

Sometimes it may be desirable to display the data label even though it cannot be contained within the area. In this case, the setMinLabelSize can be used to set the threshold to 0.

Arguments

Argument | Default | Description
s | (Mandatory) | The minimum height (or width if x and y axes are swapped) of an area below which data labels will be hidden.

Return Value

None


BaseBoxLayer

BaseBoxLayer

The BaseBoxLayer class is the base class for layers that uses isolated symbols to represent multiple data sets. These include BoxWhiskerLayer, HLOCLayer and CandleStickLayer. BaseBoxLayer is a subclass of Layer.

Method | Inherited | Description
setDataGap | (Self) | Sets the symbol width by specifying the gap ratio between adjacent symbols.
setDataWidth | (Self) | Sets the symbol width by specifying the pixel width of the symbols.
set3D | Layer | Sets the 3D depth of the layer, and the 3D gap between the current layer and the next layer.
setLineWidth | Layer | Sets the default line width of lines when drawing data sets on the layer.
setBorderColor | Layer | Sets the default border color and 3D raised effect when drawing data sets on the layer.
setLegendOrder | Layer | Sets the order of the data set names as appeared in the legend box.
setLegend | Layer | Sets the order of the data set names as appeared in the legend box.
setDataCombineMethod | Layer | Sets the method used to combine multiple data sets in a layer.
addDataSet | Layer | Adds a data set to the chart layer.
getDataSet | Layer | Gets the requested DataSet object.
addDataGroup | Layer | Open a new data group.
addExtraField | Layer | Adds an array of text to be used as an extra field in various places.
addExtraField2 | Layer | Adds an array of numbers/dates to be used as an extra field in various places.
setUseYAxis | Layer | Determine the y-axis to use when drawing the data sets.
setUseYAxis2 | Layer | Determine if the primary or secondary y-axis should be used when drawing the data sets.
setXData | Layer | Sets the x values of the data points in the data sets.
setXData2 | Layer | Sets the x values of the data points in the data sets as evenly distributed in a range.
alignLayer | Layer | Aligns the layer with a data set of another bar chart layer in Side layout.
getXCoor | Layer | Gets the x pixel coordinate of a point given the x data value.
getYCoor | Layer | Gets the y pixel coordinate of a point given the y data value.
xZoneColor | Layer | Creates a x-zone color. A x-zone will change from one color to another depending on a threshold value on the x-axis.
yZoneColor | Layer | Creates a y-zone color. A y-zone will change from one color to another depending on a threshold value on the y-axis.
setDataLabelStyle | Layer | Enables data labels and sets their styles.
setDataLabelFormat | Layer | Sets the data label format.
addCustomDataLabel | Layer | Adds a custom data label to a data point.
setAggregateLabelStyle | Layer | Enables aggregate labels and sets their styles.
setAggregateLabelFormat | Layer | Sets the aggregate label format.
addCustomAggregateLabel | Layer | Adds a custom aggregate label to an aggregated object.
addCustomGroupLabel | Layer | Adds a custom data group label to object representing the group.
getImageCoor | Layer | Gets the image map coordinates of a data point as represented in the layer as HTML image map attributes.
getImageCoor2 | Layer | Gets the image map coordinates of a region containing all data points at the given x-position as HTML image map attributes.
getHTMLImageMap | Layer | Generates an HTML image map for all data points as represented on the layer.
setHTMLImageMap | Layer | Override the default arguments used when generating HTML image map for the layer.


BaseBoxLayer.setDataGap

BaseBoxLayer.setDataGap

Usage

setDataGap(gap)

Description

Sets the symbol width by specifying the gap ratio between adjacent symbols.

Arguments

Argument | Default | Description
gap | (Mandatory) | The gap between two adjacent symbols as the portion of the space between the midpoints of the elements. The gap must be in the range 0 - 1. A value of 0 (the default) means there is no gap between two adjacent symbols.

Return Value

None


BaseBoxLayer.setDataWidth

BaseBoxLayer.setDataWidth

Usage

setDataWidth(width)

Description

Sets the symbol width by specifying the pixel width of the symbols.

Arguments

Argument | Default | Description
width | (Mandatory) | The width of the symbols in pixels.

Return Value

None


HLOCLayer

HLOCLayer

The HLOCLayer class represents high-low-open-close layers. HLOCLayer is a subclass of BaseBoxLayer.

HLOCLayer objects are created by using XYChart.addHLOCLayer and XYChart.addHLOCLayer3.

Method | Inherited | Description
setColorMethod | (Self) | Sets the coloring method for the HLOC symbols.
setDataGap | BaseBoxLayer | Sets the symbol width by specifying the gap ratio between adjacent symbols.
setDataWidth | BaseBoxLayer | Sets the symbol width by specifying the pixel width of the symbols.
set3D | Layer | Sets the 3D depth of the layer, and the 3D gap between the current layer and the next layer.
setLineWidth | Layer | Sets the default line width of lines when drawing data sets on the layer.
setBorderColor | Layer | Sets the default border color and 3D raised effect when drawing data sets on the layer.
setLegendOrder | Layer | Sets the order of the data set names as appeared in the legend box.
setLegend | Layer | Sets the order of the data set names as appeared in the legend box.
setDataCombineMethod | Layer | Sets the method used to combine multiple data sets in a layer.
addDataSet | Layer | Adds a data set to the chart layer.
getDataSet | Layer | Gets the requested DataSet object.
addDataGroup | Layer | Open a new data group.
addExtraField | Layer | Adds an array of text to be used as an extra field in various places.
addExtraField2 | Layer | Adds an array of numbers/dates to be used as an extra field in various places.
setUseYAxis | Layer | Determine the y-axis to use when drawing the data sets.
setUseYAxis2 | Layer | Determine if the primary or secondary y-axis should be used when drawing the data sets.
setXData | Layer | Sets the x values of the data points in the data sets.
setXData2 | Layer | Sets the x values of the data points in the data sets as evenly distributed in a range.
alignLayer | Layer | Aligns the layer with a data set of another bar chart layer in Side layout.
getXCoor | Layer | Gets the x pixel coordinate of a point given the x data value.
getYCoor | Layer | Gets the y pixel coordinate of a point given the y data value.
xZoneColor | Layer | Creates a x-zone color. A x-zone will change from one color to another depending on a threshold value on the x-axis.
yZoneColor | Layer | Creates a y-zone color. A y-zone will change from one color to another depending on a threshold value on the y-axis.
setDataLabelStyle | Layer | Enables data labels and sets their styles.
setDataLabelFormat | Layer | Sets the data label format.
addCustomDataLabel | Layer | Adds a custom data label to a data point.
setAggregateLabelStyle | Layer | Enables aggregate labels and sets their styles.
setAggregateLabelFormat | Layer | Sets the aggregate label format.
addCustomAggregateLabel | Layer | Adds a custom aggregate label to an aggregated object.
addCustomGroupLabel | Layer | Adds a custom data group label to object representing the group.
getImageCoor | Layer | Gets the image map coordinates of a data point as represented in the layer as HTML image map attributes.
getImageCoor2 | Layer | Gets the image map coordinates of a region containing all data points at the given x-position as HTML image map attributes.
getHTMLImageMap | Layer | Generates an HTML image map for all data points as represented on the layer.
setHTMLImageMap | Layer | Override the default arguments used when generating HTML image map for the layer.


HLOCLayer.setColorMethod

HLOCLayer.setColorMethod

Usage

setColorMethod(colorMethod, riseColor [, fallColor [, leadValue ]])

Description

Sets the coloring method for the HLOC symbols.

See XYChart.addHLOCLayer3 for the supported coloring methods for HLOC symbols.

Arguments

Argument | Default | Description
colorMethod | (Mandatory) | The method to color the HLOC layer. Please refer to XYChart.addHLOCLayer3 for the supported coloring methods.
riseColor | (Mandatory) | The color to be used on an "up" day.
fallColor | -1 | The color to be used on a "down" day. The default value of -1 means it is the same as the riseColor.
leadValue | [-Infinity] | The lead value to act as the closing pricing before the first day, so as to determine if the first day is an "up" or "down" day.

Return Value

None


CandleStickLayer

CandleStickLayer

The CandleStickLayer class represents candlestick layers. It is a subclass of BaseBoxLayer.

CandleStickLayer objects are created by using XYChart.addCandleStickLayer.

Method | Inherited | Description
setDataGap | BaseBoxLayer | Sets the symbol width by specifying the gap ratio between adjacent symbols.
setDataWidth | BaseBoxLayer | Sets the symbol width by specifying the pixel width of the symbols.
set3D | Layer | Sets the 3D depth of the layer, and the 3D gap between the current layer and the next layer.
setLineWidth | Layer | Sets the default line width of lines when drawing data sets on the layer.
setBorderColor | Layer | Sets the default border color and 3D raised effect when drawing data sets on the layer.
setLegendOrder | Layer | Sets the order of the data set names as appeared in the legend box.
setLegend | Layer | Sets the order of the data set names as appeared in the legend box.
setDataCombineMethod | Layer | Sets the method used to combine multiple data sets in a layer.
addDataSet | Layer | Adds a data set to the chart layer.
getDataSet | Layer | Gets the requested DataSet object.
addDataGroup | Layer | Open a new data group.
addExtraField | Layer | Adds an array of text to be used as an extra field in various places.
addExtraField2 | Layer | Adds an array of numbers/dates to be used as an extra field in various places.
setUseYAxis | Layer | Determine the y-axis to use when drawing the data sets.
setUseYAxis2 | Layer | Determine if the primary or secondary y-axis should be used when drawing the data sets.
setXData | Layer | Sets the x values of the data points in the data sets.
setXData2 | Layer | Sets the x values of the data points in the data sets as evenly distributed in a range.
alignLayer | Layer | Aligns the layer with a data set of another bar chart layer in Side layout.
getXCoor | Layer | Gets the x pixel coordinate of a point given the x data value.
getYCoor | Layer | Gets the y pixel coordinate of a point given the y data value.
xZoneColor | Layer | Creates a x-zone color. A x-zone will change from one color to another depending on a threshold value on the x-axis.
yZoneColor | Layer | Creates a y-zone color. A y-zone will change from one color to another depending on a threshold value on the y-axis.
setDataLabelStyle | Layer | Enables data labels and sets their styles.
setDataLabelFormat | Layer | Sets the data label format.
addCustomDataLabel | Layer | Adds a custom data label to a data point.
setAggregateLabelStyle | Layer | Enables aggregate labels and sets their styles.
setAggregateLabelFormat | Layer | Sets the aggregate label format.
addCustomAggregateLabel | Layer | Adds a custom aggregate label to an aggregated object.
addCustomGroupLabel | Layer | Adds a custom data group label to object representing the group.
getImageCoor | Layer | Gets the image map coordinates of a data point as represented in the layer as HTML image map attributes.
getImageCoor2 | Layer | Gets the image map coordinates of a region containing all data points at the given x-position as HTML image map attributes.
getHTMLImageMap | Layer | Generates an HTML image map for all data points as represented on the layer.
setHTMLImageMap | Layer | Override the default arguments used when generating HTML image map for the layer.


BoxWhiskerLayer

BoxWhiskerLayer

The BoxWhiskerLayer class represents box-whisker layers. It is a subclass of BaseBoxLayer.

BoxWhiskerLayer objects are created by using XYChart.addBoxWhiskerLayer and XYChart.addBoxWhiskerLayer2.

Method | Inherited | Description
setBoxColor | (Self) | Sets the color for a single box.
setBoxColors | (Self) | Sets the colors for all boxes.
setWhiskerBrightness | (Self) | Sets the whisker colors as darken or brightened fill colors of the boxes for BoxWhiskerLayer in multi-color mode.
setDataGap | BaseBoxLayer | Sets the symbol width by specifying the gap ratio between adjacent symbols.
setDataWidth | BaseBoxLayer | Sets the symbol width by specifying the pixel width of the symbols.
set3D | Layer | Sets the 3D depth of the layer, and the 3D gap between the current layer and the next layer.
setLineWidth | Layer | Sets the default line width of lines when drawing data sets on the layer.
setBorderColor | Layer | Sets the default border color and 3D raised effect when drawing data sets on the layer.
setLegendOrder | Layer | Sets the order of the data set names as appeared in the legend box.
setLegend | Layer | Sets the order of the data set names as appeared in the legend box.
setDataCombineMethod | Layer | Sets the method used to combine multiple data sets in a layer.
addDataSet | Layer | Adds a data set to the chart layer.
getDataSet | Layer | Gets the requested DataSet object.
addDataGroup | Layer | Open a new data group.
addExtraField | Layer | Adds an array of text to be used as an extra field in various places.
addExtraField2 | Layer | Adds an array of numbers/dates to be used as an extra field in various places.
setUseYAxis | Layer | Determine the y-axis to use when drawing the data sets.
setUseYAxis2 | Layer | Determine if the primary or secondary y-axis should be used when drawing the data sets.
setXData | Layer | Sets the x values of the data points in the data sets.
setXData2 | Layer | Sets the x values of the data points in the data sets as evenly distributed in a range.
alignLayer | Layer | Aligns the layer with a data set of another bar chart layer in Side layout.
getXCoor | Layer | Gets the x pixel coordinate of a point given the x data value.
getYCoor | Layer | Gets the y pixel coordinate of a point given the y data value.
xZoneColor | Layer | Creates a x-zone color. A x-zone will change from one color to another depending on a threshold value on the x-axis.
yZoneColor | Layer | Creates a y-zone color. A y-zone will change from one color to another depending on a threshold value on the y-axis.
setDataLabelStyle | Layer | Enables data labels and sets their styles.
setDataLabelFormat | Layer | Sets the data label format.
addCustomDataLabel | Layer | Adds a custom data label to a data point.
setAggregateLabelStyle | Layer | Enables aggregate labels and sets their styles.
setAggregateLabelFormat | Layer | Sets the aggregate label format.
addCustomAggregateLabel | Layer | Adds a custom aggregate label to an aggregated object.
addCustomGroupLabel | Layer | Adds a custom data group label to object representing the group.
getImageCoor | Layer | Gets the image map coordinates of a data point as represented in the layer as HTML image map attributes.
getImageCoor2 | Layer | Gets the image map coordinates of a region containing all data points at the given x-position as HTML image map attributes.
getHTMLImageMap | Layer | Generates an HTML image map for all data points as represented on the layer.
setHTMLImageMap | Layer | Override the default arguments used when generating HTML image map for the layer.


BoxWhiskerLayer.setBoxColor

BoxWhiskerLayer.setBoxColor

Usage

setBoxColor(item, boxColor)

Description

Sets the color for a single box.

Arguments

Argument | Default | Description
item | (Mandatory) | The index of the box to change color. The first box is 0, while the Nth box is N - 1.
boxColor | (Mandatory) | The color to use to fill the box.

Return Value

None


BoxWhiskerLayer.setBoxColors

BoxWhiskerLayer.setBoxColors

Usage

setBoxColors(colors [, names ])

Description

Sets the colors for all boxes.

The method will set the BoxWhiskerLayer into multi-color mode. The colors of each box will be obtained from the given colors array. If there are insufficient colors in the array, the remaining boxes will be auto-colored.

If the names argument is given, the names will appear in the legend box if one is configured for the chart.

Arguments

Argument | Default | Description
colors | (Mandatory) | An array of colors to be used as the color of the boxes.
names | [Empty_Array] | An array of names to be used in the legend box, if one is configured for the chart.

Return Value

None


BoxWhiskerLayer.setWhiskerBrightness

BoxWhiskerLayer.setWhiskerBrightness

Usage

setWhiskerBrightness(whiskerBrightness)

Description

Sets the whisker colors as darken or brightened fill colors of the boxes for BoxWhiskerLayer in multi-color mode.

In multi-color mode, the boxes of a BoxWhiskerLayer can have different fill colors. Instead of specifying a single whisker color for all boxes, ChartDirector supports deriving the whisker colors by darkening or brightening the corresponding fill colors.

Arguments

Argument | Default | Description
whiskerBrightness | (Mandatory) | The brightness factor. A value less than 1 means darkening. A value larger than 1 means brightening. A zero value means black.

Return Value

None


VectorLayer

VectorLayer

The VectorLayer class represents vector layers. VectorLayer is a subclass of Layer.

VectorLayer objects are created by using XYChart.addVectorLayer.

Method | Inherited | Description
setVector | (Self) | Sets the lengths and directions for the vectors.
setArrowHead | (Self) | Sets the size of the arrow head.
setArrowHead2 | (Self) | Sets a custom shape to be used as the arrow head.
setArrowStem | (Self) | Sets a custom shape to be used as the arrow stem.
setArrowAlignment | (Self) | Sets the alignment of the vector relative to the data point.
setIconSize | (Self) | Sets the size of the icon to be used in legend box.
set3D | Layer | Sets the 3D depth of the layer, and the 3D gap between the current layer and the next layer.
setLineWidth | Layer | Sets the default line width of lines when drawing data sets on the layer.
setBorderColor | Layer | Sets the default border color and 3D raised effect when drawing data sets on the layer.
setLegendOrder | Layer | Sets the order of the data set names as appeared in the legend box.
setLegend | Layer | Sets the order of the data set names as appeared in the legend box.
setDataCombineMethod | Layer | Sets the method used to combine multiple data sets in a layer.
addDataSet | Layer | Adds a data set to the chart layer.
getDataSet | Layer | Gets the requested DataSet object.
addDataGroup | Layer | Open a new data group.
addExtraField | Layer | Adds an array of text to be used as an extra field in various places.
addExtraField2 | Layer | Adds an array of numbers/dates to be used as an extra field in various places.
setUseYAxis | Layer | Determine the y-axis to use when drawing the data sets.
setUseYAxis2 | Layer | Determine if the primary or secondary y-axis should be used when drawing the data sets.
setXData | Layer | Sets the x values of the data points in the data sets.
setXData2 | Layer | Sets the x values of the data points in the data sets as evenly distributed in a range.
alignLayer | Layer | Aligns the layer with a data set of another bar chart layer in Side layout.
getXCoor | Layer | Gets the x pixel coordinate of a point given the x data value.
getYCoor | Layer | Gets the y pixel coordinate of a point given the y data value.
xZoneColor | Layer | Creates a x-zone color. A x-zone will change from one color to another depending on a threshold value on the x-axis.
yZoneColor | Layer | Creates a y-zone color. A y-zone will change from one color to another depending on a threshold value on the y-axis.
setDataLabelStyle | Layer | Enables data labels and sets their styles.
setDataLabelFormat | Layer | Sets the data label format.
addCustomDataLabel | Layer | Adds a custom data label to a data point.
setAggregateLabelStyle | Layer | Enables aggregate labels and sets their styles.
setAggregateLabelFormat | Layer | Sets the aggregate label format.
addCustomAggregateLabel | Layer | Adds a custom aggregate label to an aggregated object.
addCustomGroupLabel | Layer | Adds a custom data group label to object representing the group.
getImageCoor | Layer | Gets the image map coordinates of a data point as represented in the layer as HTML image map attributes.
getImageCoor2 | Layer | Gets the image map coordinates of a region containing all data points at the given x-position as HTML image map attributes.
getHTMLImageMap | Layer | Generates an HTML image map for all data points as represented on the layer.
setHTMLImageMap | Layer | Override the default arguments used when generating HTML image map for the layer.


VectorLayer.setVector

VectorLayer.setVector

Usage

setVector(lengths, directions [, lengthScale ])

Description

Sets the lengths and directions for the vectors.

ChartDirector supports specifying lengths as pixels or in axis scale. The unit is specified by using the following predefined constants.

Constant | Value | Description
PixelScale | 0 | The unit is measured in pixels.
XAxisScale | 1 | The unit is measured in x-axis scale.
YAxisScale | 2 | The unit is measured in y-axis scale.

Arguments

Argument | Default | Description
lengths | (Mandatory) | An array of numbers representing the lengths of the vectors, in unit as specified in the lengthScale argument.
directions | (Mandatory) | An array of numbers representing the direction of the vectors as a clockwise angle in degrees, where 0 is upward pointing direction.
lengthScale | PixelScale | The unit for the lengths, which must be one of the predefined constants in the table above.

Return Value

None


VectorLayer.setArrowHead

VectorLayer.setArrowHead

Usage

setArrowHead(width [, height ])

Description

Sets the size of the arrow head.

Arguments

Argument | Default | Description
width | (Mandatory) | The width of the arrow head in pixels. The default width is 8 pixels.
height | 0 | The height of the arrow head in pixels. The default value of 0 means the height is the same as the width.

Return Value

None


VectorLayer.setArrowHead2

VectorLayer.setArrowHead2

Usage

setArrowHead2(polygon)

Description

Sets a custom shape to be used as the arrow head.

The custom shape is specified as an array of integers x0, y0, x1, y1, x2, y2 ... representing the coordinates of the vertices of the custom polygonal shape.

The polygon should be defined with a bounding square of 10 x 10 units, in which the x-axis is from left to right, and the y-axis from bottom to top. The origin is assumed to be the bottom center of the arrow (the point where the arrow head joins the arrow stem). The shape is assumed to represent an arrow pointing upwards.

As an example, the followings are the integer array that represents the standard ChartDirector vector arrow head:

-5, -5, 0, 0, 5, -5, 0, 5

ChartDirector will automatically scale the shape to the actual width and height as specified in VectorLayer.setArrowHead.

Arguments

Argument | Default | Description
polygon | (Mandatory) | An array of integers x0, y0, x1, y1, x2, y2 ... representing the coordinates the polygon vertices on a 10 x 10 units grid.

Return Value

None


VectorLayer.setArrowStem

VectorLayer.setArrowStem

Usage

setArrowStem(polygon)

Description

Sets a custom shape to be used as the arrow stem.

By default, the arrow stem is just a straight line, with the line width controlled using Layer.setLineWidth. The setArrowStem method can specify a custom shape for the arrow stem.

The custom shape is specified as an array of integers x0, y0, x1, y1, x2, y2 ... representing the coordinates of the vertices of the custom polygonal shape.

The polygon should be defined with a bounding square of 10 x 100 units, in which the x-axis is from left to right, and the y-axis from bottom to top. The origin is assumed to be the starting point of the arrow stem, and the shape is assumed to represent an arrow stem pointing upwards.

ChartDirector will automatically scale the shape so that the total arrow length (head + stem) is the required length of the arrow as according to actual data, and the stem width is as specified in Layer.setLineWidth.

Arguments

Argument | Default | Description
polygon | (Mandatory) | An array of integers x0, y0, x1, y1, x2, y2 ... representing the coordinates the polygon vertices on a 10 x 100 units grid.

Return Value

None


VectorLayer.setArrowAlignment

VectorLayer.setArrowAlignment

Usage

setArrowAlignment(alignment)

Description

Sets the alignment of the vector relative to the data point.

Arguments

Argument | Default | Description
alignment | (Mandatory) | A BottomCenter value means the vector will point away from the data point (the default). A TopCenter value means the vector will point into the data point. A Center value means the center of the vector will be at the data point.

Return Value

None


VectorLayer.setIconSize

VectorLayer.setIconSize

Usage

setIconSize(height [, width ])

Description

Sets the size of the icon to be used in legend box.

By default, if a legend box is available on the chart, ChartDirector will insert an legend entry if the VectorLayer is named. The size of the icon will be the size of the vectors used on the chart, using a short vector length to fit the legend box.

This method can be used to override the legend box settings to specify a custom width/height for the icons of the current VectorLayer.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the icon in pixels.
width | 0 | The width of the icon in pixels. The default value of 0 means the width is automatically determined.

Return Value

None


DataSet

DataSet

The DataSet class represents data sets. DataSet objects are created by using Layer.addDataSet. Existing DataSet objects can be retrieved using Layer.getDataSet.

Method | Inherited | Description
setDataName | (Self) | Sets the name of the data set.
setDataColor | (Self) | Sets the colors used to draw the data set.
setDataSymbol | (Self) | Uses one of the built-in symbols as the graphics symbol to plot the data points.
setDataSymbol2 | (Self) | Load an image from a file and use it as the graphics symbol to plot the data points.
setDataSymbol3 | (Self) | Uses a DrawArea object as the graphics symbol to plot the data points.
setDataSymbol4 | (Self) | Uses a custom polygon as the graphics symbol to plot the data points.
setLineWidth | (Self) | Sets the line width of lines when drawing the data set.
setDataLabelStyle | (Self) | Enables data labels and sets their styles.
setDataLabelFormat | (Self) | Sets the data label format for the data set.
setUseYAxis | (Self) | Determine the y-axis to use when drawing the data set.
setUseYAxis2 | (Self) | Determine if the primary or secondary y-axis should be used when drawing the data set.


DataSet.setDataName

DataSet.setDataName

Usage

setDataName(name)

Description

Sets the name of the data set.

The name will be used in the legend box, if one is available for the chart.

Arguments

Argument | Default | Description
name | (Mandatory) | The name of the data set.

Return Value

None


DataSet.setDataColor

DataSet.setDataColor

Usage

setDataColor(dataColor [, edgeColor [, shadowColor [, shadowEdgeColor ]]])

Description

Sets the colors used to draw the data set.

The usage of the colors depend on the layer type. For example, in a bar layer, the dataColor and edgeColor are used as the fill and border color of the bar. In a line layer, the dataColor is used as the color of the line, while the edgeColor is used as the border of the line for 3D lines, and is ignored for 2D lines..

Arguments

Argument | Default | Description
dataColor | (Mandatory) | The main color used to draw the data set.
edgeColor | -1 | The color used to draw the edges or borders of the data set, if any. -1 means that the edges are drawn using the default border color of the layer (defined using Layer.setBorderColor).
shadowColor | -1 | The color to use to draw 3D shadows of the data set, if any. -1 means the shadow color will be a "darker" version of the dataColor, created by reducing the RGB intensities of the dataColor in half.
shadowEdgeColor | -1 | The color to use to draw edges of the 3D shadows of the data set, if any. -1 means the shadow color will be a "darker" version of the edgeColor, created by by reducing the RGB intensities of the edgeColor in half.

Return Value

None


DataSet.setDataSymbol

DataSet.setDataSymbol

Usage

setDataSymbol(symbol [, size [, fillColor [, edgeColor [, lineWidth ]]]])

Description

Uses one of the built-in symbols as the graphics symbol to plot the data points.

In the current version of ChartDirector, data symbols are supported only in LineLayer, SplineLayer, StepLineLayer and ScatterLayer. To use data symbols in other layer types, add a ScatterLayer on top of that layer.

Arguments

Argument | Default | Description
symbol | (Mandatory) | One of the predefined shape constants representing the symbol shape. See Shape Specification for the available built-in shapes.
size | 5 | The width and height of the symbol in pixels.
fillColor | -1 | The color used to fill the symbol. -1 means the color of the data set will be used.
edgeColor | -1 | The edge color used to draw the edge of the symbol. -1 means the edge color of the data set will be used.
lineWidth | 1 | The line width used for drawing the symbols.

Return Value

None


DataSet.setDataSymbol2

DataSet.setDataSymbol2

Usage

setDataSymbol2(image)

Description

Load an image from a file and use it as the graphics symbol to plot the data points.

ChartDirector will automatically detect the image file format using the file extension, which must either png, jpg, jpeg, gif, wbmp or wmp (case insensitive).

Please refer to BaseChart.setSearchPath on the directory that ChartDirector will search for the file.

In the current version of ChartDirector, data symbols are supported only in LineLayer, SplineLayer, StepLineLayer and ScatterLayer. To use data symbols in other layer types, add a ScatterLayer on top of that layer.

Arguments

Argument | Default | Description
image | (Mandatory) | The filename of the image file. The image type is determined based on file extension, which must be png, jpg/jpeg, gif or wbmp/wmp.

Return Value

None


DataSet.setDataSymbol3

DataSet.setDataSymbol3

Usage

setDataSymbol3(obj)

Description

Uses a DrawArea object as the graphics symbol to plot the data points.

In the current version of ChartDirector, data symbols are supported only in LineLayer, SplineLayer, StepLineLayer and ScatterLayer. To use data symbols in other layer types, add a ScatterLayer on top of that layer.

Arguments

Argument | Default | Description
obj | (Mandatory) | A DrawArea object to be used as the symbol.

Return Value

None


DataSet.setDataSymbol4

DataSet.setDataSymbol4

Usage

setDataSymbol4(polygon [, size [, fillColor [, edgeColor ]]])

Description

Uses a custom polygon as the graphics symbol to plot the data points.

In the current version of ChartDirector, data symbols are supported only in LineLayer, SplineLayer, StepLineLayer and ScatterLayer. To use data symbols in other layer types, add a ScatterLayer on top of that layer.

Arguments

Argument | Default | Description
polygon | (Mandatory) | An array of integers representing the coordinates the polygon vertices. See Shape Specification on how the custom shape is defined.
size | 11 | The nominal width and height of the symbol in pixels.
fillColor | -1 | The color used to fill the symbol. -1 means the color of the data set will be used.
edgeColor | -1 | The edge color used to draw the edge of the symbol. -1 means the edge color of the data set will be used.

Return Value

None


DataSet.setLineWidth

DataSet.setLineWidth

Usage

setLineWidth(w)

Description

Sets the line width of lines when drawing the data set.

This method only applies to layers that employ lines to represent data (e.g. line layer).

If this method is not called, the default line width for the layer will be used (set using Layer.setLineWidth).

Arguments

Argument | Default | Description
w | (Mandatory) | The width of the line in pixels.

Return Value

None


DataSet.setDataLabelStyle

DataSet.setDataLabelStyle

Usage

setDataLabelStyle([ font [, fontSize [, fontColor [, fontAngle ]]]])

Description

Enables data labels and sets their styles.

To set the data label styles for all data sets in a layer, use Layer.setDataLabelStyle.

For details description of data labels, please refer to :Layer.setDataLabelStyle.

Arguments

Argument | Default | Description
font | "" | The font used to draw the labels.
fontSize | 8 | The font size used to draw the labels.
fontColor | TextColor | The color used to draw the labels.
fontAngle | 0 | The rotation angle of the labels.

Return Value

A TextBox object representing the prototype of the obj. This may be used to fine-tune the appearance of the obj.


DataSet.setDataLabelFormat

DataSet.setDataLabelFormat

Usage

setDataLabelFormat(formatString)

Description

Sets the data label format for the data set.

To set the label format for all data sets in a layer, use Layer.setDataLabelFormat.

For details description of data label format, please refer to Layer.setDataLabelFormat.

Arguments

Argument | Default | Description
formatString | (Mandatory) | The format string.

Return Value

None


DataSet.setUseYAxis

DataSet.setUseYAxis

Usage

setUseYAxis(a)

Description

Determine the y-axis to use when drawing the data set.

To set the y-axis to use for all data sets within a layer, use Layer.setUseYAxis.

Arguments

Argument | Default | Description
a | (Mandatory) | The y-axis to use when drawing the data set.

Return Value

None


DataSet.setUseYAxis2

DataSet.setUseYAxis2

Usage

setUseYAxis2([ b ])

Description

Determine if the primary or secondary y-axis should be used when drawing the data set.

To set the y-axis to use for all data sets within a layer, use Layer.setUseYAxis2.

Note: DataSet.setUseYAxis is a more general method that can support more than 2 y-axes.

Arguments

Argument | Default | Description
b | true (non-zero) | A true (non-zero) value means the secondary y-axis will be used. A false (zero) value means the primary y-axis will be used.

Return Value

None


PolarChart

PolarChart

The PolarChart class represents polar charts (including radar charts). The PolarChart class is a subclass of BaseChart.

Method | Inherited | Description
PolarChart | (Self) | Creates a new PolarChart object.
setPlotArea | (Self) | Sets the position, background colors, border color and border width of the polar plot area.
setPlotAreaBg | (Self) | Sets alternating background colors for the polar plot area.
setGridColor | (Self) | Sets the grid colors and widths of the polar plot area.
setGridStyle | (Self) | Configure whether to use circular grids or polygon grids, and whether the grid lines are on top of the polar plot area or are at the back.
setStartAngle | (Self) | Sets the angle of the radial axis, and the layout direction of radial grid lines.
angularAxis | (Self) | Gets the AngularAxis object representing the angular axis of the polar chart.
radialAxis | (Self) | Gets the RadialAxis object representing the radial axis of the polar chart.
getXCoor | (Self) | Gets the x pixel coordinate of a point given its radial and angular coordinates.
getYCoor | (Self) | Gets the y pixel coordinate of a point given its radial and angular coordinates.
addLineLayer | (Self) | Adds a polar line layer to the polar chart.
addAreaLayer | (Self) | Adds a polar area layer to the polar chart.
addSplineLineLayer | (Self) | Adds a polar spline line layer to the polar chart.
addSplineAreaLayer | (Self) | Adds a polar spline area layer to the polar chart.
addVectorLayer | (Self) | Adds a vector layer to the chart.
setSize | BaseChart | Sets the size of the chart.
setBackground | BaseChart | Sets the background color, border color and 3D border effect of the chart.
setRoundedFrame | BaseChart | Sets the border style of the chart to rounded corners.
setBorder | BaseChart | Sets the border color of the chart.
setWallpaper | BaseChart | Uses the image from the specified file as the wallpaper to repetitively fill the background of the chart.
setBgImage | BaseChart | Uses the image from the specified file as the background image of the chart.
setSearchPath | BaseChart | Sets the search path for loading image files.
setTransparentColor | BaseChart | Specifies a certain color to mean transparent when creating the image output, or to include alpha transparency channel in the output.
setAntiAlias | BaseChart | Controls whether anti-alias is used when drawing lines, shapes and text.
addTitle | BaseChart | Adds a title at the top center of the chart.
addTitle2 | BaseChart | Adds a title to the chart.
addLegend | BaseChart | Adds a legend box to the chart.
addLegend2 | BaseChart | Adds a legend box to the chart with grid layout.
getLegend | BaseChart | Gets the LegendBox object representing the legend box in the chart.
layoutLegend | BaseChart | Lays out and gets the LegendBox object representing the legend box in the chart.
getDrawArea | BaseChart | Retrieves the internal DrawArea object that is used to draw the chart.
addText | BaseChart | Adds a text box to the chart.
addLine | BaseChart | Adds a line to the chart.
addExtraField | BaseChart | Adds an array of text to be used as an extra field in various places.
addExtraField2 | BaseChart | Adds an array of numbers/dates to be used as an extra field in various places.
setColor | BaseChart | Change the color at the specified position in the palette.
setColors | BaseChart | Change the colors in the palette.
setColors2 | BaseChart | Change the colors in the palette, starting from the specified position in the palette.
getColor | BaseChart | Gets the color at the specified position of the palette.
halfColor | BaseChart | Creates a color that is half the intensity of the given color.
dashLineColor | BaseChart | Creates a dash line color.
patternColor | BaseChart | Creates a pattern color using an array of colors as the bitmap pattern.
patternColor2 | BaseChart | Creates a pattern color by loading the pattern from an image file.
linearGradientColor | BaseChart | Creates a two-point linear gradient color.
linearGradientColor2 | BaseChart | Creates a multi-point linear gradient color.
radialGradientColor | BaseChart | Creates a two-point radial gradient color.
radialGradientColor2 | BaseChart | Creates a multi-point radial gradient color.
gradientColor | BaseChart | Creates a two-point linear gradient color.
gradientColor2 | BaseChart | Creates a multi-point linear gradient color.
setDefaultFonts | BaseChart | Sets the defaults for normal, bold, italic and bold-italic fonts.
setFontTable | BaseChart | Sets an entry in the font table to the specified font name.
formatValue | BaseChart | Formats a number/date using the ChartDirector formatting syntax as is in Parameter Substitution and Formatting.
setNumberFormat | BaseChart | Sets the characters used for thousand separator, decimal point, and negative sign.
setMonthNames | BaseChart | Sets the names of the months for date/time formatting purposes.
setWeekDayNames | BaseChart | Sets the names of the week days for date/time formatting purposes.
setAMPM | BaseChart | Sets the names to be used to denote morning and afternoon.
layout | BaseChart | Perform auto-scaling of the axis and compute the positions of the various objects in the chart.
makeChart | BaseChart | Generates the chart image and save it into a file.
makeChart2 | BaseChart | Generates the chart as an image in memory.
makeChart3 | BaseChart | Generates the chart in internal format and return a DrawArea object to allow adding custom drawings on top of the chart.
makeSession | BaseChart | Generates the chart as an image and save it to a session variable.
makeTmpFile | BaseChart | Generates the chart as an image and save it to a temporary file, and automatically remove old files.
getHTMLImageMap | BaseChart | Generates an HTML image map for the chart.
getChartMetrics | BaseChart | Gets the chart metrics for passing to WebChartViewer.setChartMetrics to support view ports.


PolarChart.PolarChart

PolarChart.PolarChart

Usage

PolarChart(width, height [, bgColor [, edgeColor [, raisedEffect ]]])

Description

Creates a new PolarChart object.

Note: In the ColdFusion edition of ChartDirector, the PolarChart constructor is implemented as a method of the ChartDirector.CFChart object called ChartDirector.CFChart.PolarChart.

Arguments

Argument | Default | Description
width | (Mandatory) | The width of the chart in pixels.
height | (Mandatory) | The height of the chart in pixels.
bgColor | BackgroundColor | The background color of the chart.
edgeColor | Transparent | The edge color of the chart.
raisedEffect | 0 | The 3D border width. For positive values, the border will appear raised. For negative values, the border will appear depressed. A zero value means the border will appear flat.

Return Value

The PolarChart object created.


PolarChart.setPlotArea

PolarChart.setPlotArea

Usage

setPlotArea(x, y, r [, bgColor [, edgeColor [, edgeWidth ]]])

Description

Sets the position, background colors, border color and border width of the polar plot area.

Arguments

Argument | Default | Description
x | (Mandatory) | The x coordinate of the center of the polar plot area.
y | (Mandatory) | The y coordinate of the center of the polar plot area.
r | (Mandatory) | The radius of the polar plot area in pixels.
bgColor | Transparent | The background color of the polar plot area.
edgeColor | Transparent | The border color of the polar plot area.
edgeWidth | 1 | The border width of the polar plot area. The border width is only used if the polar plot area is using a polygon grid (see PolarChart.setGridStyle). If circular grid is used, the border width is always 1.

Return Value

None


PolarChart.setPlotAreaBg

PolarChart.setPlotAreaBg

Usage

setPlotAreaBg(bgColor1 [, bgColor2 [, altRings ]])

Description

Sets alternating background colors for the polar plot area.

ChartDirector supports using two alternating background colors for the polar plot area. The colors can change on the radial direction, resulting in concentric circles, on an the angular direction, resulting in alternating sectors.

Arguments

Argument | Default | Description
bgColor1 | (Mandatory) | The first background color.
bgColor2 | -1 | The second background color. The default value of -1 means it is the same as the first background color.
altRings | true (non-zero) | A true (non-zero) value means the background colors alternate in the radial direction, resulting in concentric circles. A false (zero) value means the background colors alternates in the angular direction, resulting in alternating sectors.

Return Value

None


PolarChart.setGridColor

PolarChart.setGridColor

Usage

setGridColor([ rGridColor [, rGridWidth [, aGridColor [, aGridWidth ]]]])

Description

Sets the grid colors and widths of the polar plot area.

Arguments

Argument | Default | Description
rGridColor | 80000000 | The color of grid lines in the radial direction (from the center outwards).
rGridWidth | 1 | The line width for grid lines in the radial direction (from the center outwards).
aGridColor | 80000000 | The color of grid lines in the angular direction (concentric circles around the center).
aGridWidth | 1 | The line width of grid lines in the angular direction (concentric circles around the center) The line width is only used if the polar plot area is using a polygon grid (see PolarChart.setGridStyle). If circular grid is used, the line width is always 1.

Return Value

None


PolarChart.setGridStyle

PolarChart.setGridStyle

Usage

setGridStyle(polygonGrid [, gridOnTop ])

Description

Configure whether to use circular grids or polygon grids, and whether the grid lines are on top of the polar plot area or are at the back.

Arguments

Argument | Default | Description
polygonGrid | (Mandatory) | A true (non-zero) value means polygonal grid will be used. A false (zero) value means circular grid will be used.
gridOnTop | true (non-zero) | A true (non-zero) value means the grid lines will be on top of the polar plot area. A false (zero) value means the grid lines will be at the bottom of the polar plot area.

Return Value

None


PolarChart.setStartAngle

PolarChart.setStartAngle

Usage

setStartAngle(startAngle [, clockwise ])

Description

Sets the angle of the radial axis, and the layout direction of radial grid lines.

The default radial axis angle is 0 degree, which means the radial axis is upward pointing.

Arguments

Argument | Default | Description
startAngle | (Mandatory) | The angle of the radial axis in degrees. The upward pointing direction is 0 degree, with angle measured in the clockwise direction.
clockwise | true (non-zero) | A true (non-zero) value means the radial grid line will be laid out in the clockwise direction. A false (zero) value means the radial grid lines will be laid out in the counter-clockwise direction.

Return Value

None


PolarChart.angularAxis

PolarChart.angularAxis

Usage

angularAxis()

Description

Gets the AngularAxis object representing the angular axis of the polar chart.

Arguments

None

Return Value

The AngularAxis object representing the angular axis of the polar chart.


PolarChart.radialAxis

PolarChart.radialAxis

Usage

radialAxis()

Description

Gets the RadialAxis object representing the radial axis of the polar chart.

Arguments

None

Return Value

The RadialAxis object representing the radial axis of the polar chart.


PolarChart.getXCoor

PolarChart.getXCoor

Usage

getXCoor(r, a)

Description

Gets the x pixel coordinate of a point given its radial and angular coordinates.

The radial and angular coordinates are measured using the scale of the radial and angular axes. In particular, the scale of the angular axis may not be in degrees or radians. See AngularAxis.setLabels and AngularAxis.setLinearScale on how the angular axis scale is defined.

Note: You must call BaseChart.layout first before calling this method. It is because ChartDirector needs to perform auto-scaling and determine the axis scale first before it can compute the coordinates.

Arguments

Argument | Default | Description
r | (Mandatory) | The radial coordinate of the point.
a | (Mandatory) | The angular coordinate of the point.

Return Value

The x pixel coordinate of the point.


PolarChart.getYCoor

PolarChart.getYCoor

Usage

getYCoor(r, a)

Description

Gets the y pixel coordinate of a point given its radial and angular coordinates.

The radial and angular coordinates are measured using the scale of the radial and angular axes. In particular, the scale of the angular axis may not be in degrees or radians. See AngularAxis.setLabels and AngularAxis.setLinearScale on how the angular axis scale is defined.

Note: You must call BaseChart.layout first before calling this method. It is because ChartDirector needs to perform auto-scaling and determine the axis scale first before it can compute the coordinates.

Arguments

Argument | Default | Description
r | (Mandatory) | The radial coordinate of the point.
a | (Mandatory) | The angular coordinate of the point.

Return Value

The y pixel coordinate of the point.


PolarChart.addLineLayer

PolarChart.addLineLayer

Usage

addLineLayer(data [, color [, name ]])

Description

Adds a polar line layer to the polar chart.

Arguments

Argument | Default | Description
data | (Mandatory) | An array of numbers representing the data points in the layer.
color | -1 | The color to draw the line. -1 means that the color is automatically selected from the palette.
name | "" | The name of the layer. The name will be used in the legend box, if one is available. An empty string means the layer has no name.

Return Value

A PolarLineLayer object representing the chart layer created.


PolarChart.addAreaLayer

PolarChart.addAreaLayer

Usage

addAreaLayer(data [, color [, name ]])

Description

Adds a polar area layer to the polar chart.

Arguments

Argument | Default | Description
data | (Mandatory) | An array of numbers representing the data points in the layer.
color | -1 | The color to draw the area. -1 means that the color is automatically selected from the palette.
name | "" | The name of the layer. The name will be used in the legend box, if one is available. An empty string means the layer has no name.

Return Value

A PolarAreaLayer object representing the chart layer created.


PolarChart.addSplineLineLayer

PolarChart.addSplineLineLayer

Usage

addSplineLineLayer(data [, color [, name ]])

Description

Adds a polar spline line layer to the polar chart.

Arguments

Argument | Default | Description
data | (Mandatory) | An array of numbers representing the data points in the layer.
color | -1 | The color to draw the spline line. -1 means that the color is automatically selected from the palette.
name | "" | The name of the layer. The name will be used in the legend box, if one is available. An empty string means the layer has no name.

Return Value

A PolarSplineLineLayer object representing the chart layer created.


PolarChart.addSplineAreaLayer

PolarChart.addSplineAreaLayer

Usage

addSplineAreaLayer(data [, color [, name ]])

Description

Adds a polar spline area layer to the polar chart.

Arguments

Argument | Default | Description
data | (Mandatory) | An array of numbers representing the data points in the layer.
color | -1 | The color to draw the spline area. -1 means that the color is automatically selected from the palette.
name | "" | The name of the layer. The name will be used in the legend box, if one is available. An empty string means the layer has no name.

Return Value

A PolarSplineAreaLayer object representing the chart layer created.


PolarChart.addVectorLayer

PolarChart.addVectorLayer

Usage

addVectorLayer(rData, aData, lengths, directions [, lengthScale [, color [, name ]]])

Description

Adds a vector layer to the chart.

The vectors are specified as 4 data series, representing the radial and angular coordinates of the reference points to put the vectors, and the lengths and directions of the vectors.

By default, the vector starts from the reference point and points away from it. You may use PolarVectorLayer.setArrowAlignment to specify other options, such as for the vectors to point into the reference point, or to have the reference as a pivot at the mid-point of the vector.

ChartDirector supports specifying vectors lengths as pixels or in axis scale. The unit is specified by using the following predefined constants.

Constant | Value | Description
PixelScale | 0 | The unit is measured in pixels.
RadialAxisScale | 2 | The unit is measured in the radial axis scale.

Arguments

Argument | Default | Description
rData | (Mandatory) | An array of numbers representing the radial coordinates for the reference points of the vectors.
aData | (Mandatory) | An array of numbers representing the angular coordinates for the reference points of the vectors.
lengths | (Mandatory) | An array of numbers representing the lengths of the vectors, in unit as specified in the lengthScale argument.
directions | (Mandatory) | An array of numbers representing the direction of the vectors as a clockwise angle in degrees, where 0 is upward pointing direction.
lengthScale | PixelScale | The unit for the lengths, which must be one of the predefined constants in the table above.
color | -1 | The color to draw the data points. -1 means that the color is automatically selected from the palette.
name | "" | The name of the layer. The name will be used in the legend box, if one is available. An empty string means the layer has no name.

Return Value

A PolarVectorLayer object representing the vector layer created.


RadialAxis

RadialAxis

The RadialAxis class represents radial axes in polar charts. The radial axis is the axis representing the radius component of a polar coordinate.

In the current version of ChartDirector, RadialAxis is implemented as a special configuration of Axis.

The RadialAxis is obtained by using PolarChart.radialAxis.

Method | Inherited | Description
setLabelStyle | Axis | Sets the font style used to for the axis labels.
setLabelFormat | Axis | Sets the format for numeric or date/time axis labels.
setMultiFormat | Axis | Sets multiple formats for numeric or date/time axis labels.
setMultiFormat2 | Axis | Adds one filter and format string to the multi-format lists.
setFormatCondition | Axis | Specifies the condition that subsequent Axis.setLabelFormat and Axis.setMultiFormat will become applicable.
setLabelGap | Axis | Sets the distance between the axis labels and the ticks on the axis.
setLabelOffset | Axis | Shifts the axis labels from its default position along the axis.
setTitle | Axis | Adds a title to the axis.
setTitlePos | Axis | Sets the position of the axis title relative to the axis.
setColors | Axis | Sets the colors of the axis itself, axis label, axis title and axis ticks.
setTickLength | Axis | Sets the length of the axis ticks.
setTickLength2 | Axis | Sets the length of the major and minor axis ticks.
setTickWidth | Axis | Sets the width of the axis ticks.
setTickColor | Axis | Sets the colors of the axis ticks.
setTickOffset | Axis | Shifts the position of the ticks along the axis.
setMinTickInc | Axis | Sets the minimum distance between two ticks on the axis for auto-scaled axis.
setWidth | Axis | Sets the line width of the axis.
setMargin | Axis | Reserve margins at the ends of the axis.
setIndent | Axis | Specifies if the axis should be "indented" or not.
setAutoScale | Axis | Sets the margins at the two ends of the axis during auto-scaling, and whether to start the axis from zero.
setRounding | Axis | Controls whether to round the ends of the axis to align with tick positions.
setTickDensity | Axis | Sets the density of the axis ticks.
setReverse | Axis | Reverse the axis.
setLabels | Axis | Sets the text labels to be used on the axis.
setLabels2 | Axis | Sets the numeric/date/time labels to be used on the axis.
setLabelStep | Axis | Shows a regularly spaced subset of the axis labels on the axis.
setLinearScale | Axis | Sets the axis to use the given linear scale.
setLinearScale2 | Axis | Sets the axis to use the given linear scale and the given labels.
setLinearScale3 | Axis | Sets the axis to use linear auto-scale.
setLogScale | Axis | Sets the axis to use the given logarithmic scale.
setLogScale2 | Axis | Sets the axis to use the given logarithmic scale and the given labels.
setLogScale3 | Axis | Sets the axis to use logarithmic auto-scale.
setDateScale | Axis | Sets the axis to use the given date scale.
setDateScale2 | Axis | Sets the axis to use the given date scale and the given labels.
setDateScale3 | Axis | Sets the axis to use date auto-scale.
syncAxis | Axis | Synchronizes this axis with another axis using a linear formula.
copyAxis | Axis | Copies the scale and labels from another axis.
addLabel | Axis | Adds an extra label on the axis.
addMark | Axis | Adds a mark line to the chart.
addZone | Axis | Adds a zone to the chart.
getMinValue | Axis | Gets the lower bound of the axis.
getMaxValue | Axis | Gets the upper bound of the axis.
getTicks | Axis | Gets the values of the ticks.
getLabel | Axis | Gets the label at the specified position on the axis.
getHTMLImageMap | Axis | Generates an HTML image map for the axis labels.
getAxisImageMap | Axis | Generates an HTML image map for the axis itself.


AngularAxis

AngularAxis

The AngularAxis class represents angular axes in polar charts. The angular axis is the axis representing the angular component of a polar coordinate.

Method | Inherited | Description
setLabelStyle | (Self) | Sets the font style used to for the axis labels.
setLabelGap | (Self) | Sets the distance between the axis labels and the axis.
setLabels | (Self) | Sets the text labels to be used on the axis.
setLabels2 | (Self) | Sets the numeric labels to be used on the axis.
addLabel | (Self) | Adds an extra label on the axis.
setLinearScale | (Self) | Sets the axis to use the given linear scale.
setLinearScale2 | (Self) | Sets the axis to use the given linear scale and the given labels.
addZone | (Self) | Adds an angular zone to the polar chart.
addZone2 | (Self) | Adds an angular zone to the polar chart.
getHTMLImageMap | (Self) | Generates an HTML image map for the axis labels.
getAxisImageMap | (Self) | Generates an HTML image map for the axis itself.


AngularAxis.setLabelStyle

AngularAxis.setLabelStyle

Usage

setLabelStyle([ font [, fontSize [, fontColor [, fontAngle ]]]])

Description

Sets the font style used to for the axis labels.

See Font Specification for details on various font attributes.

Arguments

Argument | Default | Description
font | "bold" | The font used to draw the labels.
fontSize | 10 | The font size used to draw the labels in points.
fontColor | TextColor | The color used to draw the labels.
fontAngle | 0 | The rotation angle of the labels.

Return Value

A TextBox object representing the prototype of the obj. This may be used to fine-tune the appearance of the obj.


AngularAxis.setLabelGap

AngularAxis.setLabelGap

Usage

setLabelGap(d)

Description

Sets the distance between the axis labels and the axis.

Arguments

Argument | Default | Description
d | (Mandatory) | The distance between the axis label and axis in pixels.

Return Value

None


AngularAxis.setLabels

AngularAxis.setLabels

Usage

setLabels(text)

Description

Sets the text labels to be used on the axis.

This method is typically used in radar charts to set the angular axis to enumerated scale.

In enumerated scale, the labels are laid out evenly on the perimeter of the polar plot area. It is like the labels are at on the vertices of an n-side polygon, where n is the number of labels. Radial grid lines are drawn from the center to the vertices.

The angular coordinates of the data points are determined based on their position in the data array. The first data point will be at the same angular coordinate as the first vertex, the second data point at the second vertex, and so on.

Internally, ChartDirector will assign a value of 0 to the first axis label, 1 to the second axis label, and so on. These values are not visible. Only the axis labels are visible. However, these values may be useful for some ChartDirector features that need to reference the axis position by value, such as adding extra labels using AngularAxis.addLabel.

Arguments

Argument | Default | Description
text | (Mandatory) | An array of strings containing the text of the labels.

Return Value

A TextBox object representing the prototype of the obj. This may be used to fine-tune the appearance of the obj.


AngularAxis.setLabels2

AngularAxis.setLabels2

Usage

setLabels2(labels [, formatString ])

Description

Sets the numeric labels to be used on the axis.

This method is typically used to set the angular axis to enumerated scale. For more details on what is enumerated axis scale, please refer to AngularAxis.setLabels.

In some cases, it may be desirable to skip some labels. If you want to leave a label position empty, use NoValue as the axis label.

Arguments

Argument | Default | Description
labels | (Mandatory) | An array of numbers to be used as the axis labels.
formatString | "" | A format string to specified how to format the labels into human readable form. Please refer to Axis.setLabelFormat for the syntax of the format string. An empty string means the format will be automatically determined.

Return Value

A TextBox object representing the prototype of the obj. This may be used to fine-tune the appearance of the obj.


AngularAxis.addLabel

AngularAxis.addLabel

Usage

addLabel(pos, label)

Description

Adds an extra label on the axis.

Arguments

Argument | Default | Description
pos | (Mandatory) | The position on the axis to add the label.
label | (Mandatory) | The text label to add.

Return Value

None


AngularAxis.setLinearScale

AngularAxis.setLinearScale

Usage

setLinearScale(lowerLimit, upperLimit [, majorTickInc [, minorTickInc ]])

Description

Sets the axis to use the given linear scale.

Arguments

Argument | Default | Description
lowerLimit | (Mandatory) | The lower bound of the axis.
upperLimit | (Mandatory) | The upper bound of the axis.
majorTickInc | 0 | Adds major ticks to the axis, where the major ticks are separated by majorTickInc in value. Each major tick will have an associated text label for the value if the axis at the tick. The default value of 0 means no major tick is used.
minorTickInc | 0 | Adds minor ticks to the axis, where the minor ticks are separated by minorTickInc in value. The default value of 0 means no minor tick is used.

Return Value

None


AngularAxis.setLinearScale2

AngularAxis.setLinearScale2

Usage

setLinearScale2(lowerLimit, upperLimit, labels)

Description

Sets the axis to use the given linear scale and the given labels.

Arguments

Argument | Default | Description
lowerLimit | (Mandatory) | The lower bound of the axis.
upperLimit | (Mandatory) | The upper bound of the axis.
labels | (Mandatory) | An array of text strings to be used as the labels on the axis. ChartDirector will distribute the labels evenly on the axis.

Return Value

None


AngularAxis.addZone

AngularAxis.addZone

Usage

addZone(startValue, endValue, startRadius, endRadius, fillColor [, edgeColor ])

Description

Adds an angular zone to the polar chart.

An angular zone marks an angular region that spans from a start angle to an end angle, where the angles are specified as data values on the angular axis scale. The addZone method allows you to specify a starting and ending radius in pixels for drawing the zone.

Arguments

Argument | Default | Description
startValue | (Mandatory) | The data value that marks the start angular position of the zone.
endValue | (Mandatory) | The data value that marks the end angular position of the zone.
startRadius | (Mandatory) | The starting radius of the zone in pixels.
endRadius | (Mandatory) | The ending radius of the zone in pixels.
fillColor | (Mandatory) | The fill color of the zone.
edgeColor | -1 | The edge color of the zone. The default is the same as the fill color.

Return Value

None


AngularAxis.addZone2

AngularAxis.addZone2

Usage

addZone2(startValue, endValue, fillColor [, edgeColor ])

Description

Adds an angular zone to the polar chart.

This method is just a short cut to AngularAxis.addZone, in which the starting radius is always 0, and ending radius is the radius of the polar plot region. In other words, the angular zone is a sector on the polar chart.

Arguments

Argument | Default | Description
startValue | (Mandatory) | The data value that marks the start angular position of the zone.
endValue | (Mandatory) | The data value that marks the end angular position of the zone.
fillColor | (Mandatory) | The fill color of the zone.
edgeColor | -1 | The edge color of the zone. The default is the same as the fill color.

Return Value

None


AngularAxis.getHTMLImageMap

AngularAxis.getHTMLImageMap

Usage

getHTMLImageMap(url [, queryFormat [, extraAttr [, offsetX, offsetY ]]])

Description

Generates an HTML image map for the axis labels.

This method should be called only after creating the chart image (eg. using BaseChart.makeSession, BaseChart.makeChart or BaseChart.makeChart2). The image map cannot be determined without creating the chart image first.

This method accepts a URL as its argument. When generating an image map, it appends query parameters to the URL to indicate which legend entry the user has clicked.

The following is an example image map generated for an axis with 3 labels.

<area shape="rect" coords="30,220,70,239" href="handler.asp?value=0&label=John">
<area shape="rect" coords="70,220,110,239" href="handler.asp?value=1&label=Mary">
<area shape="rect" coords="110,220,150,239" href="handler.asp?value=2&label=Peter">

The image map consists of multiple <area> tags, one for each label. In the "href" attributes, query parameters are appended to the URL to provide information on the label clicked.

The image map produces by ChartDirector does not include the <map> and </map> tag. This is intentional so that you can add additional custom <area> tags to the image map, or append multiple image maps together.

The format of the appended URL parameters is determined using the queryFormat argument, which by default is:

value={value}&label={label}

The texts in curly brackets (i.e. {value}, {label}) will be replaced by the actual values when generating the image map. For example, {label} will be replaced by the label text.

Please refer to Parameter Substitution and Formatting on all available parameters and how to format them.

In addition to customizing the query parameters, ChartDirector supports additional HTML attributes in the <area> tags using the extraAttr argument.

For example, the following extraAttr will add a "title" HTML attribute to every <area> tag. The "title" attribute will be displayed as "tool tip" when the mouse moves over the image map.

title='Click me for details on {label}'

Another common usage of the extraAttr argument is to add "onmouseover" and "onmouseout" HTML attributes to handle user interaction using Javascript on the browser.

Arguments

Argument | Default | Description
url | (Mandatory) | The URL to be used in the "href" attribute of the image map. Parameter Substitution and Formatting is supported. Use an empty string if no href attribute is needed.
queryFormat | "" | A text string representing the template of the query parameters to be appended to the URL. Parameter Substitution and Formatting is supported. The special keyword "{default}" represents the default query parameters. This is useful for specifying appending to the default. Note that an empty string means to use the default query query parameters. To specify no query parameter, use a space character.
extraAttr | "" | A text string to specify additional attributes to add to the <area> tag. Parameter Substitution and Formatting is supported.
offsetX | 0 | An offset to be added to all x coordinates in the image map. This is useful if the current image will be shifted and inserted into another image. In this case, the image map will need to be shifted by the same offset.
offsetY | 0 | An offset to be added to all y coordinates in the image map. See offsetX above for description.

Return Value

A text string containing the image map generated.


AngularAxis.getAxisImageMap

AngularAxis.getAxisImageMap

Usage

getAxisImageMap(noOfSegments, mapWidth, url [, queryFormat [, extraAttr [, offsetX, offsetY ]]])

Description

Generates an HTML image map for the axis itself.

This method is similar to AngularAxis.getHTMLImageMap. The difference is instead of generating an image map for the labels, it generates an image map for the axis itself. The axis will be divided into a number of segments, with an image map entry created for each segment.

Arguments

Argument | Default | Description
noOfSegments | (Mandatory) | The number of segments to divide the axis into.
mapWidth | (Mandatory) | The width of the axis used for the purpose of generating the image map.
url | (Mandatory) | The URL to be used in the "href" attribute of the image map. Parameter Substitution and Formatting is supported. Use an empty string if no href attribute is needed.
queryFormat | "" | A text string representing the template of the query parameters to be appended to the URL. Parameter Substitution and Formatting is supported. The special keyword "{default}" represents the default query parameters. This is useful for specifying appending to the default. Note that an empty string means to use the default query query parameters. To specify no query parameter, use a space character.
extraAttr | "" | A text string to specify additional attributes to add to the <area> tag. Parameter Substitution and Formatting is supported.
offsetX | 0 | An offset to be added to all x coordinates in the image map. This is useful if the current image will be shifted and inserted into another image. In this case, the image map will need to be shifted by the same offset.
offsetY | 0 | An offset to be added to all y coordinates in the image map. See offsetX above for description.

Return Value

A text string containing the image map generated.


PolarLayer

PolarLayer

The PolarLayer class is the base class for all PolarChart layer classes.

Method | Inherited | Description
setAngles | (Self) | Sets the angular coordinates of the data points.
setBorderColor | (Self) | Sets the border color for drawing the data on the layer.
setLineWidth | (Self) | Sets the line width of lines when drawing the data on the layer.
setDataSymbol | (Self) | Uses one of the built-in symbols as the graphics symbol to plot the data points.
setDataSymbol2 | (Self) | Load an image from a file and use it as the graphics symbol to plot the data points.
setDataSymbol3 | (Self) | Uses a DrawArea object as the graphics symbol to plot the data points.
setDataSymbol4 | (Self) | Uses a custom polygon as the graphics symbol to plot the data points.
setSymbolScale | (Self) | Sets the size of the symbol for each data point (for creating bubble charts).
setDataLabelStyle | (Self) | Enables data labels and sets their styles.
setDataLabelFormat | (Self) | Sets the data label format.
addCustomDataLabel | (Self) | Adds a custom data label to a data point.
setImageMapWidth | (Self) | Sets the effective size of a data point for producing image maps.
getImageCoor | (Self) | Gets the image map coordinates of a data point.
getHTMLImageMap | (Self) | Generates an HTML image map for all data points on the layer.
setHTMLImageMap | (Self) | Override the default arguments used when generating HTML image map for the layer.


PolarLayer.setAngles

PolarLayer.setAngles

Usage

setAngles(angles)

Description

Sets the angular coordinates of the data points.

Note that the angular coordinates are measured using the scale of the angular axis, which may not be in degrees or radians. See AngularAxis.setLabels and AngularAxis.setLinearScale on how the angular axis scale is defined.

If this method is not called, the first data point is assumed to have an angular coordinate of 0, and the nth data point is assumed to have an angular coordinate of (n - 1). This is common for radar charts, in which enumerated scale is used for the angular axis (see AngularAxis.setLabels).

Arguments

Argument | Default | Description
angles | (Mandatory) | An array of numbers representing the angular coordinates of the data points.

Return Value

None


PolarLayer.setBorderColor

PolarLayer.setBorderColor

Usage

setBorderColor(edgeColor)

Description

Sets the border color for drawing the data on the layer.

This method only applies to layers that represents data with elements that have borders (e.g. polar area layer and polar spline area layer).

Arguments

Argument | Default | Description
edgeColor | (Mandatory) | The border color.

Return Value

None


PolarLayer.setLineWidth

PolarLayer.setLineWidth

Usage

setLineWidth(w)

Description

Sets the line width of lines when drawing the data on the layer.

Arguments

Argument | Default | Description
w | (Mandatory) | The width of the line in pixels.

Return Value

None


PolarLayer.setDataSymbol

PolarLayer.setDataSymbol

Usage

setDataSymbol(symbol [, size [, fillColor [, edgeColor [, lineWidth ]]]])

Description

Uses one of the built-in symbols as the graphics symbol to plot the data points.

Arguments

Argument | Default | Description
symbol | (Mandatory) | One of the predefined shape constants representing the symbol shape. See Shape Specification for the available built-in shapes.
size | 7 | The width and height of the symbol in pixels.
fillColor | -1 | The color used to fill the symbol. -1 means the color of the data set will be used.
edgeColor | -1 | The edge color used to draw the edge of the symbol. -1 means the edge color of the data set will be used.
lineWidth | 1 | The line width used for drawing the symbols.

Return Value

None


PolarLayer.setDataSymbol2

PolarLayer.setDataSymbol2

Usage

setDataSymbol2(image)

Description

Load an image from a file and use it as the graphics symbol to plot the data points.

ChartDirector will automatically detect the image file format using the file extension, which must either png, jpg, jpeg, gif, wbmp or wmp (case insensitive).

Please refer to BaseChart.setSearchPath on the directory that ChartDirector will search for the file.

Arguments

Argument | Default | Description
image | (Mandatory) | The filename of the image file. The image type is determined based on file extension, which must be png, jpg/jpeg, gif or wbmp/wmp.

Return Value

None


PolarLayer.setDataSymbol3

PolarLayer.setDataSymbol3

Usage

setDataSymbol3(obj)

Description

Uses a DrawArea object as the graphics symbol to plot the data points.

Arguments

Argument | Default | Description
obj | (Mandatory) | A DrawArea object to be used as the symbol.

Return Value

None


PolarLayer.setDataSymbol4

PolarLayer.setDataSymbol4

Usage

setDataSymbol4(polygon [, size [, fillColor [, edgeColor ]]])

Description

Uses a custom polygon as the graphics symbol to plot the data points.

Arguments

Argument | Default | Description
polygon | (Mandatory) | An array of integers representing the coordinates the polygon vertices. See Shape Specification on how the custom shape is defined.
size | 11 | The nominal width and height of the symbol in pixels.
fillColor | -1 | The color used to fill the symbol. -1 means the color of the data set will be used.
edgeColor | -1 | The edge color used to draw the edge of the symbol. -1 means the edge color of the data set will be used.

Return Value

None


PolarLayer.setSymbolScale

PolarLayer.setSymbolScale

Usage

setSymbolScale(zData [, scaleType ])

Description

Sets the size of the symbol for each data point (for creating bubble charts).

One common usage for this method is to draw circle symbols of different sizes at each data points, creating a bubble chart.

This method supports any valid data symbols. You can create bubble charts with square bubbles, or even custom data symbols.

ChartDirector supports specifying sizes as pixels or in axis scale. The unit is specified by using the following predefined constants.

Constant | Value | Description
PixelScale | 0 | The unit is measured in pixels.
RadialAxisScale | 2 | The unit is measured in the radial axis scale.

Arguments

Argument | Default | Description
zData | (Mandatory) | The sizes of the symbols, expressed using the unit defined by the scaleType argument.
scaleType | PixelScale | The unit for zData, which must be one of the predefined constants in the table above.

Return Value

None


PolarLayer.setDataLabelStyle

PolarLayer.setDataLabelStyle

Usage

setDataLabelStyle([ font [, fontSize [, fontColor [, fontAngle ]]]])

Description

Enables data labels and sets their styles.

Arguments

Argument | Default | Description
font | "" | The font used to draw the labels.
fontSize | 8 | The font size used to draw the labels.
fontColor | TextColor | The color used to draw the labels.
fontAngle | 0 | The rotation angle of the labels.

Return Value

A TextBox object representing the prototype of the obj. This may be used to fine-tune the appearance of the obj.


PolarLayer.setDataLabelFormat

PolarLayer.setDataLabelFormat

Usage

setDataLabelFormat(formatString)

Description

Sets the data label format.

By default, the data label format is "{value}". Please refer to Parameter Substitution and Formatting on available parameters and how to format them.

Arguments

Argument | Default | Description
formatString | (Mandatory) | The format string.

Return Value

None


PolarLayer.addCustomDataLabel

PolarLayer.addCustomDataLabel

Usage

addCustomDataLabel(i, label [, font [, fontSize [, fontColor [, fontAngle ]]]])

Description

Adds a custom data label to a data point.

See Font Specification for details on various font attributes.

Arguments

Argument | Default | Description
i | (Mandatory) | The data point number for the data point. The first data point is 0, while the nth data point is (n - 1).
label | (Mandatory) | A text string representing the data label. Parameter Substitution and Formatting is supported.
font | "" | The font used to draw the label.
fontSize | 8 | The font size used to draw the label.
fontColor | TextColor | The color used to draw the label.
fontAngle | 0 | The rotation angle of the label.

Return Value

A TextBox object representing the prototype of the obj. This may be used to fine-tune the appearance of the obj.


PolarLayer.setImageMapWidth

PolarLayer.setImageMapWidth

Usage

setImageMapWidth(width)

Description

Sets the effective size of a data point for producing image maps.

For the purpose of producing image maps for the data points, the sizes of the data points are assumed to be the size of the data symbols. If no data symbol is used, an effective size is assumed. The default is 10 pixels in width and height.

Arguments

Argument | Default | Description
width | (Mandatory) | The effective width and height of the data point for the purpose of producing image maps.

Return Value

None


PolarLayer.getImageCoor

PolarLayer.getImageCoor

Usage

getImageCoor(dataItem [, offsetX, offsetY ])

Description

Gets the image map coordinates of a data point.

The image map coordinates will be in the following format:

shape="rect" cords="[x1],[y1],[x2],[y2]"

This format is specially designed so that it can easily be included into HTML image maps.

This method should be called only after creating the chart image (eg. using BaseChart.makeSession, BaseChart.makeChart or BaseChart.makeChart2). The image map cannot be determined without creating the chart image first.

Arguments

Argument | Default | Description
dataItem | (Mandatory) | The data point number for the data point. The first data point is 0, while the nth data point is (n - 1).
offsetX | 0 | An offset to be added to all x coordinates in the image map. This is useful if the current image will be shifted and inserted into another image. In this case, the image map will need to be shifted by the same offset.
offsetY | 0 | An offset to be added to all y coordinates in the image map. See offsetX above for description.

Return Value

A text string representing the image map coordinates of the data points as HTML image map attributes.


PolarLayer.getHTMLImageMap

PolarLayer.getHTMLImageMap

Usage

getHTMLImageMap(url [, queryFormat [, extraAttr [, offsetX, offsetY ]]])

Description

Generates an HTML image map for all data points on the layer.

Please refer to BaseChart.getHTMLImageMap for the detail description of this method.

This method should be called only after creating the chart image (eg. using BaseChart.makeSession, BaseChart.makeChart or BaseChart.makeChart2). The image map cannot be determined without creating the chart image first.

Arguments

Argument | Default | Description
url | (Mandatory) | The URL to be used in the "href" attribute of the image map. Parameter Substitution and Formatting is supported. Use an empty string if no href attribute is needed.
queryFormat | "" | A text string representing the template of the query parameters to be appended to the URL. Parameter Substitution and Formatting is supported. The special keyword "{default}" represents the default query parameters. This is useful for specifying appending to the default. Note that an empty string means to use the default query query parameters. To specify no query parameter, use a space character.
extraAttr | "" | A text string to specify additional attributes to add to the <area> tag. Parameter Substitution and Formatting is supported.
offsetX | 0 | An offset to be added to all x coordinates in the image map. This is useful if the current image will be shifted and inserted into another image. In this case, the image map will need to be shifted by the same offset.
offsetY | 0 | An offset to be added to all y coordinates in the image map. See offsetX above for description.

Return Value

A text string containing the image map generated.


PolarLayer.setHTMLImageMap

PolarLayer.setHTMLImageMap

Usage

setHTMLImageMap(url [, queryFormat [, extraAttr ]])

Description

Override the default arguments used when generating HTML image map for the layer.

BaseChart.getHTMLImageMap can be used to generate HTML image map for the whole chart. When BaseChart.getHTMLImageMap is used, the image map for all layers will be generated based on the arguments supplied to BaseChart.getHTMLImageMap.

The setHTMLImageMap method can be used to override those arguments for a chart layer, so the image map for that layer can be different.

For a detail description of image maps, please refer to BaseChart.getHTMLImageMap.

Arguments

Argument | Default | Description
url | (Mandatory) | The URL to be used in the "href" attribute of the image map. Parameter Substitution and Formatting is supported. The special keyword "{default}" represents the global URL as specified in BaseChart.getHTMLImageMap. This field is useful for specifying appending to the global URL. Note that an empty string also means to use the global URL. To specify no URL, use the special keyword "{none}". To disable the entire image map, use the special keyword "{disable}".
queryFormat | "" | A text string representing the template of the query parameters to be appended to the URL. Parameter Substitution and Formatting is supported. The special keyword "{default}" represents the global query parameters as specified in BaseChart.getHTMLImageMap. This field is useful for specifying appending to the global query parameters. Note that an empty string also means to use the global query parameters. To specify no query parameters, use the special keyword "{none}".
extraAttr | "" | A text string to specify additional attributes to add to the <area> tag. Parameter Substitution and Formatting is supported. The special keyword "{default}" represents the global additional attributes as specified in BaseChart.getHTMLImageMap. This field is useful for specifying appending to the global additional attributes. Note that an empty string also means to use the global additional attributes. To specify no additional attributes, use the special keyword "{none}".

Return Value

None


PolarLineLayer

PolarLineLayer

The PolarLineLayer class represents polar area layers. PolarLineLayer is a subclass of PolarLayer.

PolarLineLayer objects are created by using PolarChart.addLineLayer.

Method | Inherited | Description
setCloseLoop | (Self) | Specifies whether the polar line should form a close loop (joining the last point to the first point) or not.
setGapColor | (Self) | Sets the color and style of the line used for jumping across NoValue data points.
setAngles | PolarLayer | Sets the angular coordinates of the data points.
setBorderColor | PolarLayer | Sets the border color for drawing the data on the layer.
setLineWidth | PolarLayer | Sets the line width of lines when drawing the data on the layer.
setDataSymbol | PolarLayer | Uses one of the built-in symbols as the graphics symbol to plot the data points.
setDataSymbol2 | PolarLayer | Load an image from a file and use it as the graphics symbol to plot the data points.
setDataSymbol3 | PolarLayer | Uses a DrawArea object as the graphics symbol to plot the data points.
setDataSymbol4 | PolarLayer | Uses a custom polygon as the graphics symbol to plot the data points.
setSymbolScale | PolarLayer | Sets the size of the symbol for each data point (for creating bubble charts).
setDataLabelStyle | PolarLayer | Enables data labels and sets their styles.
setDataLabelFormat | PolarLayer | Sets the data label format.
addCustomDataLabel | PolarLayer | Adds a custom data label to a data point.
setImageMapWidth | PolarLayer | Sets the effective size of a data point for producing image maps.
getImageCoor | PolarLayer | Gets the image map coordinates of a data point.
getHTMLImageMap | PolarLayer | Generates an HTML image map for all data points on the layer.
setHTMLImageMap | PolarLayer | Override the default arguments used when generating HTML image map for the layer.


PolarLineLayer.setCloseLoop

PolarLineLayer.setCloseLoop

Usage

setCloseLoop(b)

Description

Specifies whether the polar line should form a close loop (joining the last point to the first point) or not.

Arguments

Argument | Default | Description
b | (Mandatory) | A true (non-zero) value means the polar line should form a close loop. A false (zero) value means the polar line should not form a close loop.

Return Value

None


PolarLineLayer.setGapColor

PolarLineLayer.setGapColor

Usage

setGapColor(lineColor [, lineWidth ])

Description

Sets the color and style of the line used for jumping across NoValue data points.

By default, the color of the line for jumping across NoValue data points is Transparent, which means the line will become discontinuous

Arguments

Argument | Default | Description
lineColor | (Mandatory) | The line color of the line used for jumping across NoValue data points
lineWidth | -1 | The line width of the line used for jumping across NoValue data points. -1 means the width will be the same as the line width of the line for drawing normal data points.

Return Value

None


PolarAreaLayer

PolarAreaLayer

The PolarAreaLayer class represents polar area layers. PolarAreaLayer is a subclass of PolarLayer.

PolarAreaLayer objects are created by using PolarChart.addAreaLayer.

Method | Inherited | Description
setAngles | PolarLayer | Sets the angular coordinates of the data points.
setBorderColor | PolarLayer | Sets the border color for drawing the data on the layer.
setLineWidth | PolarLayer | Sets the line width of lines when drawing the data on the layer.
setDataSymbol | PolarLayer | Uses one of the built-in symbols as the graphics symbol to plot the data points.
setDataSymbol2 | PolarLayer | Load an image from a file and use it as the graphics symbol to plot the data points.
setDataSymbol3 | PolarLayer | Uses a DrawArea object as the graphics symbol to plot the data points.
setDataSymbol4 | PolarLayer | Uses a custom polygon as the graphics symbol to plot the data points.
setSymbolScale | PolarLayer | Sets the size of the symbol for each data point (for creating bubble charts).
setDataLabelStyle | PolarLayer | Enables data labels and sets their styles.
setDataLabelFormat | PolarLayer | Sets the data label format.
addCustomDataLabel | PolarLayer | Adds a custom data label to a data point.
setImageMapWidth | PolarLayer | Sets the effective size of a data point for producing image maps.
getImageCoor | PolarLayer | Gets the image map coordinates of a data point.
getHTMLImageMap | PolarLayer | Generates an HTML image map for all data points on the layer.
setHTMLImageMap | PolarLayer | Override the default arguments used when generating HTML image map for the layer.


PolarSplineLineLayer

PolarSplineLineLayer

The PolarSplineLineLayer class represents polar spline line layers. PolarSplineLineLayer is a subclass of PolarLineLayer.

PolarSplineAreaLayer objects are created by using PolarChart.addSplineLineLayer.

Method | Inherited | Description
setTension | (Self) | Sets the tension to use when computing the spline curve.
setAngles | PolarLayer | Sets the angular coordinates of the data points.
setBorderColor | PolarLayer | Sets the border color for drawing the data on the layer.
setLineWidth | PolarLayer | Sets the line width of lines when drawing the data on the layer.
setDataSymbol | PolarLayer | Uses one of the built-in symbols as the graphics symbol to plot the data points.
setDataSymbol2 | PolarLayer | Load an image from a file and use it as the graphics symbol to plot the data points.
setDataSymbol3 | PolarLayer | Uses a DrawArea object as the graphics symbol to plot the data points.
setDataSymbol4 | PolarLayer | Uses a custom polygon as the graphics symbol to plot the data points.
setSymbolScale | PolarLayer | Sets the size of the symbol for each data point (for creating bubble charts).
setDataLabelStyle | PolarLayer | Enables data labels and sets their styles.
setDataLabelFormat | PolarLayer | Sets the data label format.
addCustomDataLabel | PolarLayer | Adds a custom data label to a data point.
setImageMapWidth | PolarLayer | Sets the effective size of a data point for producing image maps.
getImageCoor | PolarLayer | Gets the image map coordinates of a data point.
getHTMLImageMap | PolarLayer | Generates an HTML image map for all data points on the layer.
setHTMLImageMap | PolarLayer | Override the default arguments used when generating HTML image map for the layer.


PolarSplineLineLayer.setTension

PolarSplineLineLayer.setTension

Usage

setTension(tension)

Description

Sets the tension to use when computing the spline curve.

The tension parameter should be between -1 and 1. A positive tension will make the spline tighter. The spline curve will become straight line segments when tension is 1. A negative tension will make the spline looser.

Arguments

Argument | Default | Description
tension | (Mandatory) | The tension of the spline, which should be between -1 and 1.

Return Value

None


PolarSplineAreaLayer

PolarSplineAreaLayer

The PolarSplineAreaLayer class represents polar spline area layers. PolarSplineAreaLayer is a subclass of PolarAreaLayer.

PolarSplineAreaLayer objects are created by using PolarChart.addSplineAreaLayer.

Method | Inherited | Description
setTension | (Self) | Sets the tension to use when computing the spline curve.
setAngles | PolarLayer | Sets the angular coordinates of the data points.
setBorderColor | PolarLayer | Sets the border color for drawing the data on the layer.
setLineWidth | PolarLayer | Sets the line width of lines when drawing the data on the layer.
setDataSymbol | PolarLayer | Uses one of the built-in symbols as the graphics symbol to plot the data points.
setDataSymbol2 | PolarLayer | Load an image from a file and use it as the graphics symbol to plot the data points.
setDataSymbol3 | PolarLayer | Uses a DrawArea object as the graphics symbol to plot the data points.
setDataSymbol4 | PolarLayer | Uses a custom polygon as the graphics symbol to plot the data points.
setSymbolScale | PolarLayer | Sets the size of the symbol for each data point (for creating bubble charts).
setDataLabelStyle | PolarLayer | Enables data labels and sets their styles.
setDataLabelFormat | PolarLayer | Sets the data label format.
addCustomDataLabel | PolarLayer | Adds a custom data label to a data point.
setImageMapWidth | PolarLayer | Sets the effective size of a data point for producing image maps.
getImageCoor | PolarLayer | Gets the image map coordinates of a data point.
getHTMLImageMap | PolarLayer | Generates an HTML image map for all data points on the layer.
setHTMLImageMap | PolarLayer | Override the default arguments used when generating HTML image map for the layer.


PolarSplineAreaLayer.setTension

PolarSplineAreaLayer.setTension

Usage

setTension(tension)

Description

Sets the tension to use when computing the spline curve.

The tension parameter should be between -1 and 1. A positive tension will make the spline tighter. The spline curve will become straight line segments when tension is 1. A negative tension will make the spline looser.

Arguments

Argument | Default | Description
tension | (Mandatory) | The tension of the spline, which should be between -1 and 1.

Return Value

None


PolarVectorLayer

PolarVectorLayer

The PolarVectorLayer class represents polar vector layers. PolarVectorLayer is a subclass of PolarLayer.

VectorLayer objects are created by using PolarChart.addVectorLayer.

Method | Inherited | Description
setVector | (Self) | Sets the lengths and directions for the vectors.
setArrowHead | (Self) | Sets the size of the arrow head.
setArrowHead2 | (Self) | Sets a custom shape to be used as the arrow head.
setArrowStem | (Self) | Sets a custom shape to be used as the arrow stem.
setArrowAlignment | (Self) | Sets the alignment of the vector relative to the data point.
setIconSize | (Self) | Sets the size of the icon to be used in legend box.
setAngles | PolarLayer | Sets the angular coordinates of the data points.
setBorderColor | PolarLayer | Sets the border color for drawing the data on the layer.
setLineWidth | PolarLayer | Sets the line width of lines when drawing the data on the layer.
setDataSymbol | PolarLayer | Uses one of the built-in symbols as the graphics symbol to plot the data points.
setDataSymbol2 | PolarLayer | Load an image from a file and use it as the graphics symbol to plot the data points.
setDataSymbol3 | PolarLayer | Uses a DrawArea object as the graphics symbol to plot the data points.
setDataSymbol4 | PolarLayer | Uses a custom polygon as the graphics symbol to plot the data points.
setSymbolScale | PolarLayer | Sets the size of the symbol for each data point (for creating bubble charts).
setDataLabelStyle | PolarLayer | Enables data labels and sets their styles.
setDataLabelFormat | PolarLayer | Sets the data label format.
addCustomDataLabel | PolarLayer | Adds a custom data label to a data point.
setImageMapWidth | PolarLayer | Sets the effective size of a data point for producing image maps.
getImageCoor | PolarLayer | Gets the image map coordinates of a data point.
getHTMLImageMap | PolarLayer | Generates an HTML image map for all data points on the layer.
setHTMLImageMap | PolarLayer | Override the default arguments used when generating HTML image map for the layer.


PolarVectorLayer.setVector

PolarVectorLayer.setVector

Usage

setVector(lengths, directions [, lengthScale ])

Description

Sets the lengths and directions for the vectors.

ChartDirector supports specifying lengths as pixels or in axis scale. The unit is specified by using the following predefined constants.

Constant | Value | Description
PixelScale | 0 | The unit is measured in pixels.
RadialAxisScale | 2 | The unit is measured in the radial axis scale.

Arguments

Argument | Default | Description
lengths | (Mandatory) | An array of numbers representing the lengths of the vectors, in unit as specified in the lengthScale argument.
directions | (Mandatory) | An array of numbers representing the direction of the vectors as a clockwise angle in degrees, where 0 is upward pointing direction.
lengthScale | PixelScale | The unit for the lengths, which must be one of the predefined constants in the table above.

Return Value

None


PolarVectorLayer.setArrowHead

PolarVectorLayer.setArrowHead

Usage

setArrowHead(width [, height ])

Description

Sets the size of the arrow head.

Arguments

Argument | Default | Description
width | (Mandatory) | The width of the arrow head in pixels. The default width is 8 pixels.
height | 0 | The height of the arrow head in pixels. The default value of 0 means the height is the same as the width.

Return Value

None


PolarVectorLayer.setArrowHead2

PolarVectorLayer.setArrowHead2

Usage

setArrowHead2(polygon)

Description

Sets a custom shape to be used as the arrow head.

The custom shape is specified as an array of integers x0, y0, x1, y1, x2, y2 ... representing the coordinates of the vertices of the custom polygonal shape.

The polygon should be defined with a bounding square of 10 x 10 units, in which the x-axis is from left to right, and the y-axis from bottom to top. The origin is assumed to be the bottom center of the arrow (the point where the arrow head joins the arrow stem). The shape is assumed to represent an arrow pointing upwards.

As an example, the followings are the integer array that represents the standard ChartDirector vector arrow head:

-5, -5, 0, 0, 5, -5, 0, 5

ChartDirector will automatically scale the shape to the actual width and height as specified in PolarVectorLayer.setArrowHead.

Arguments

Argument | Default | Description
polygon | (Mandatory) | An array of integers x0, y0, x1, y1, x2, y2 ... representing the coordinates the polygon vertices on a 10 x 10 units grid.

Return Value

None


PolarVectorLayer.setArrowStem

PolarVectorLayer.setArrowStem

Usage

setArrowStem(polygon)

Description

Sets a custom shape to be used as the arrow stem.

By default, the arrow stem is just a straight line, with the line width controlled using PolarLayer.setLineWidth. The setArrowStem method can specify a custom shape for the arrow stem.

The custom shape is specified as an array of integers x0, y0, x1, y1, x2, y2 ... representing the coordinates of the vertices of the custom polygonal shape.

The polygon should be defined with a bounding square of 10 x 100 units, in which the x-axis is from left to right, and the y-axis from bottom to top. The origin is assumed to be the starting point of the arrow stem, and the shape is assumed to represent an arrow stem pointing upwards.

ChartDirector will automatically scale the shape so that the total arrow length (head + stem) is the required length of the arrow as according to actual data, and the stem width is as specified in PolarLayer.setLineWidth.

Arguments

Argument | Default | Description
polygon | (Mandatory) | An array of integers x0, y0, x1, y1, x2, y2 ... representing the coordinates the polygon vertices on a 10 x 100 units grid.

Return Value

None


PolarVectorLayer.setArrowAlignment

PolarVectorLayer.setArrowAlignment

Usage

setArrowAlignment(alignment)

Description

Sets the alignment of the vector relative to the data point.

Arguments

Argument | Default | Description
alignment | (Mandatory) | A BottomCenter value means the vector will point away from the data point (the default). A TopCenter value means the vector will point into the data point. A Center value means the center of the vector will be at the data point.

Return Value

None


PolarVectorLayer.setIconSize

PolarVectorLayer.setIconSize

Usage

setIconSize(height [, width ])

Description

Sets the size of the icon to be used in legend box.

By default, if a legend box is available on the chart, ChartDirector will insert an legend entry if the PolarVectorLayer is named. The size of the icon will be the size of the vectors used on the chart, using a short vector length to fit the legend box.

This method can be used to override the legend box settings to specify a custom width/height for the icons of the current PolarVectorLayer.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the icon in pixels.
width | 0 | The width of the icon in pixels. The default value of 0 means the width is automatically determined.

Return Value

None


BaseMeter

BaseMeter

The BaseMeter class represents a generic meter. It is the base class for AngularMeter and LinearMeter.

Method | Inherited | Description
setScale | (Self) | Sets the meter to use the given scale.
setScale2 | (Self) | Sets the meter to use the given scale with the given text labels and tick positions.
setScale3 | (Self) | Sets the meter to use the given scale with the given numeric labels and tick positions.
addPointer | (Self) | Adds a pointer to the meter.
setLabelStyle | (Self) | Sets the font style used to for the meter labels.
setLabelFormat | (Self) | Sets the format of the labels computed by ChartDirector.
setLabelPos | (Self) | Sets the positions of the meter scale labels.
setMeterColors | (Self) | Sets the colors of the meter scale line, scale label and tick.
setLineWidth | (Self) | Sets the line widths of the scale line and the ticks on the meter.
setTickLength | (Self) | Set the lengths of the ticks.
addLabel | (Self) | Adds a label to a specific position on the meter scale.
getLabel | (Self) | Gets the label at the specified position on the meter scale.
getCoor | (Self) | Gets the geometric coordinates given the data value.
getTicks | (Self) | Returns the positions of all ticks as values on the meter scale.
setSize | BaseChart | Sets the size of the chart.
setBackground | BaseChart | Sets the background color, border color and 3D border effect of the chart.
setRoundedFrame | BaseChart | Sets the border style of the chart to rounded corners.
setBorder | BaseChart | Sets the border color of the chart.
setWallpaper | BaseChart | Uses the image from the specified file as the wallpaper to repetitively fill the background of the chart.
setBgImage | BaseChart | Uses the image from the specified file as the background image of the chart.
setSearchPath | BaseChart | Sets the search path for loading image files.
setTransparentColor | BaseChart | Specifies a certain color to mean transparent when creating the image output, or to include alpha transparency channel in the output.
setAntiAlias | BaseChart | Controls whether anti-alias is used when drawing lines, shapes and text.
addTitle | BaseChart | Adds a title at the top center of the chart.
addTitle2 | BaseChart | Adds a title to the chart.
addLegend | BaseChart | Adds a legend box to the chart.
addLegend2 | BaseChart | Adds a legend box to the chart with grid layout.
getLegend | BaseChart | Gets the LegendBox object representing the legend box in the chart.
layoutLegend | BaseChart | Lays out and gets the LegendBox object representing the legend box in the chart.
getDrawArea | BaseChart | Retrieves the internal DrawArea object that is used to draw the chart.
addText | BaseChart | Adds a text box to the chart.
addLine | BaseChart | Adds a line to the chart.
addExtraField | BaseChart | Adds an array of text to be used as an extra field in various places.
addExtraField2 | BaseChart | Adds an array of numbers/dates to be used as an extra field in various places.
setColor | BaseChart | Change the color at the specified position in the palette.
setColors | BaseChart | Change the colors in the palette.
setColors2 | BaseChart | Change the colors in the palette, starting from the specified position in the palette.
getColor | BaseChart | Gets the color at the specified position of the palette.
halfColor | BaseChart | Creates a color that is half the intensity of the given color.
dashLineColor | BaseChart | Creates a dash line color.
patternColor | BaseChart | Creates a pattern color using an array of colors as the bitmap pattern.
patternColor2 | BaseChart | Creates a pattern color by loading the pattern from an image file.
linearGradientColor | BaseChart | Creates a two-point linear gradient color.
linearGradientColor2 | BaseChart | Creates a multi-point linear gradient color.
radialGradientColor | BaseChart | Creates a two-point radial gradient color.
radialGradientColor2 | BaseChart | Creates a multi-point radial gradient color.
gradientColor | BaseChart | Creates a two-point linear gradient color.
gradientColor2 | BaseChart | Creates a multi-point linear gradient color.
setDefaultFonts | BaseChart | Sets the defaults for normal, bold, italic and bold-italic fonts.
setFontTable | BaseChart | Sets an entry in the font table to the specified font name.
formatValue | BaseChart | Formats a number/date using the ChartDirector formatting syntax as is in Parameter Substitution and Formatting.
setNumberFormat | BaseChart | Sets the characters used for thousand separator, decimal point, and negative sign.
setMonthNames | BaseChart | Sets the names of the months for date/time formatting purposes.
setWeekDayNames | BaseChart | Sets the names of the week days for date/time formatting purposes.
setAMPM | BaseChart | Sets the names to be used to denote morning and afternoon.
layout | BaseChart | Perform auto-scaling of the axis and compute the positions of the various objects in the chart.
makeChart | BaseChart | Generates the chart image and save it into a file.
makeChart2 | BaseChart | Generates the chart as an image in memory.
makeChart3 | BaseChart | Generates the chart in internal format and return a DrawArea object to allow adding custom drawings on top of the chart.
makeSession | BaseChart | Generates the chart as an image and save it to a session variable.
makeTmpFile | BaseChart | Generates the chart as an image and save it to a temporary file, and automatically remove old files.
getHTMLImageMap | BaseChart | Generates an HTML image map for the chart.
getChartMetrics | BaseChart | Gets the chart metrics for passing to WebChartViewer.setChartMetrics to support view ports.


BaseMeter.setScale

BaseMeter.setScale

Usage

setScale(lowerLimit, upperLimit [, majorTickInc [, minorTickInc [, microTickInc ]]])

Description

Sets the meter to use the given scale.

Arguments

Argument | Default | Description
lowerLimit | (Mandatory) | The lower limit of the meter scale.
upperLimit | (Mandatory) | The upper limit of the meter scale.
majorTickInc | 0 | The interval between major ticks. For example, a value of 10 means a major tick every 10 units in the meter scale. Each major tick will have an associated label for the value at the tick. A value of 0 disables major ticks.
minorTickInc | 0 | The interval between minor ticks. For example, a value of 5 means a minor tick every 5 units in the meter scale. A value of 0 disables minor ticks.
microTickInc | 0 | The interval between minor ticks. For example, a value of 1 means a minor tick every 1 units in the meter scale. A value of 0 disables micro ticks.

Return Value

None


BaseMeter.setScale2

BaseMeter.setScale2

Usage

setScale2(lowerLimit, upperLimit, labels)

Description

Sets the meter to use the given scale with the given text labels and tick positions.

ChartDirector will distribute the labels evenly on the scale. By default, all labels are associated with major ticks. These can be modified by using '-', '~' or ':' as the first character. Please refer to BaseMeter.addLabel for details.

Arguments

Argument | Default | Description
lowerLimit | (Mandatory) | The lower limit of the meter scale.
upperLimit | (Mandatory) | The upper limit of the meter scale.
labels | (Mandatory) | An array of text strings to be used as the labels on the meter scale.

Return Value

None


BaseMeter.setScale3

BaseMeter.setScale3

Usage

setScale3(lowerLimit, upperLimit, labels [, formatString ])

Description

Sets the meter to use the given scale with the given numeric labels and tick positions.

ChartDirector will distribute the labels evenly on the scale. By default, all labels are associated with major ticks. If you want certain positions to show a minor or micro ticks only, use MinorTickOnly or MicroTickOnly as the label values for those positions.

Arguments

Argument | Default | Description
lowerLimit | (Mandatory) | The lower limit of the meter scale.
upperLimit | (Mandatory) | The upper limit of the meter scale.
labels | (Mandatory) | An array of numbers to be used as the labels on the meter scale.
formatString | "" | The format string for formatting the numbers. An empty string means the format will be automatically determined.

Return Value

None


BaseMeter.addPointer

BaseMeter.addPointer

Usage

addPointer(value [, fillColor [, edgeColor ]])

Description

Adds a pointer to the meter.

Arguments

Argument | Default | Description
value | (Mandatory) | The value that the pointer will point to.
fillColor | LineColor | The fill color of the pointer.
edgeColor | -1 | The edge color of the pointer. The default value of -1 means the edge color is the same as the fill color.

Return Value

None


BaseMeter.setLabelStyle

BaseMeter.setLabelStyle

Usage

setLabelStyle([ font [, fontSize [, fontColor [, fontAngle ]]]])

Description

Sets the font style used to for the meter labels.

See Font Specification for details on various font attributes.

Arguments

Argument | Default | Description
font | "bold" | The font used to draw the labels.
fontSize | -1 | The font size used to draw the labels in points. A value of -1 means the font size is not changed. The default font size is 10 points for angular meters, and 8 points for linear meters.
fontColor | TextColor | The color used to draw the labels.
fontAngle | 0 | The rotation angle of the labels.

Return Value

A TextBox object representing the prototype of the obj. This may be used to fine-tune the appearance of the obj.


BaseMeter.setLabelFormat

BaseMeter.setLabelFormat

Usage

setLabelFormat(formatString)

Description

Sets the format of the labels computed by ChartDirector.

The method is mainly used when BaseMeter.setScale is used, in which case the label values are not directly specified but are computed by ChartDirector. For example, a format string of "{value|2}" will format the values with 2 decimal places.

Please refer to Parameter Substitution and Formatting on all available format parameters.

Arguments

Argument | Default | Description
formatString | (Mandatory) | The format string.

Return Value

None


BaseMeter.setLabelPos

BaseMeter.setLabelPos

Usage

setLabelPos(labelInside [, labelOffset ])

Description

Sets the positions of the meter scale labels.

Arguments

Argument | Default | Description
labelInside | (Mandatory) | A true (non-zero) value means that the labels are on the 'inward' side of the meter scale. A false (zero) value means the labels are on the 'outward' side of the meter scale. For an angular meter, the default is for the labels on the 'inward' side. For a linear meter, the default is for the labels on the 'outward' side.
labelOffset | 0 | The offset, in pixels, of the labels position relative to the standard position. If the major tick is at the same side as the label, the standard starting position of the label is at the end point of the major tick. Otherwise, the standard starting position is on the meter scale. A positive labelOffset means the labels should move more towards the 'inward' or 'outward' side, depending on the first parameter. A negative labelOffset means moving the labels towards the opposite direction.

Return Value

None


BaseMeter.setMeterColors

BaseMeter.setMeterColors

Usage

setMeterColors(axisColor [, labelColor [, tickColor ]])

Description

Sets the colors of the meter scale line, scale label and tick.

Arguments

Argument | Default | Description
axisColor | (Mandatory) | The color for drawing the meter scale line. The default is LineColor.
labelColor | -1 | The color for drawing the scale labels. Passing -1 in this argument means the label color is not changed. The default label color is TextColor.
tickColor | -1 | The color for drawing the ticks. Passing -1 in this argument means the tick color is not changed. The default tick color is LineColor.

Return Value

None


BaseMeter.setLineWidth

BaseMeter.setLineWidth

Usage

setLineWidth(axisWidth [, majorTickWidth [, minorTickWidth [, microTickWidth ]]])

Description

Sets the line widths of the scale line and the ticks on the meter.

Arguments

Argument | Default | Description
axisWidth | (Mandatory) | The line width for drawing the meter scale line in pixels. For an angular meter, the default is 1 pixel. For a linear meter, the default is 2 pixels.
majorTickWidth | 1 | The line width of the major ticks in pixels. For a linear meter, if this method is not called, the initial major tick width is set to 2 pixels.
minorTickWidth | 1 | The line width of the minor ticks in pixels.
microTickWidth | 1 | The line width of the micro ticks in pixels.

Return Value

None


BaseMeter.setTickLength

BaseMeter.setTickLength

Usage

setTickLength(majorLen [, minorLen [, microLen ]])

Description

Set the lengths of the ticks.

Arguments

Argument | Default | Description
majorLen | (Mandatory) | The length of the major ticks in pixels. A positive value means the tick is at the 'outward' direction of the meter. A negative value means the tick is at the 'inward' direction. For an angular meter, the default is -10 (10 pixels at the inward direction). For a horizontal linear meter, the default is the same height as the meter scale region in the inward direction. For a vertical linear meter, the default is the same width as the meter scale region in the inward direction.
minorLen | -7fffffff | The length of the minor ticks in pixels. The default is 60% of the length of the major ticks.
microLen | -7fffffff | The length of the micro ticks in pixels. The default is 50% of the length of the minor ticks.

Return Value

None


BaseMeter.addLabel

BaseMeter.addLabel

Usage

addLabel(pos, label)

Description

Adds a label to a specific position on the meter scale.

By default, all labels will be associated major ticks on the scale. To associate a label with a minor tick instead , use '-' as the first character of the label. To associate a label with a micro tick instead, use ':' as the first character of the label. To draw the label without any tick at all, use '~' as the first character of the label.

Leading '-', '~' or ':' characters are tick specification characters and will not appear on the labels. They just specify the the tick style to be associated with the labels. If you want have a label that actually begins these characters, add '\' as the first character as the escape character.

In some cases, it may be desirable to skip some labels. If you want to draw a major, minor or micro tick without any label, use ' ' (a space character), '-' or ':' as the only character in the label text. If you want leave a label position empty without a tick or a label, use an empty string.

Arguments

Argument | Default | Description
pos | (Mandatory) | The position to add the label to in meter scale unit.
label | (Mandatory) | The label to add to the meter scale.

Return Value

None


BaseMeter.getLabel

BaseMeter.getLabel

Usage

getLabel(i)

Description

Gets the label at the specified position on the meter scale.

Arguments

Argument | Default | Description
i | (Mandatory) | The position specified as a value on the meter scale.

Return Value

Returns the label at the specified position, or a null string if there is no label at that position.


BaseMeter.getCoor

BaseMeter.getCoor

Usage

getCoor(v)

Description

Gets the geometric coordinates given the data value.

For an angular meter, this method returns the angular position of the pointer for the given data value in degrees. The angle is measure in the clockwise direction, with 0 being the upward pointing direction.

For a linear meter, this method returns the linear pixel offset of the pointer for the given data value.

Arguments

Argument | Default | Description
v | (Mandatory) | The input data value.

Return Value

The geometric representation of the data value, which is an angle in degrees for an angular meter, and a linear pixel offset for a linear meter.


BaseMeter.getTicks

BaseMeter.getTicks

Usage

getTicks()

Description

Returns the positions of all ticks as values on the meter scale.

Arguments

None

Return Value

All array of numbers representing the positions of the ticks as values on the meter scale.


AngularMeter

AngularMeter

The AngularMeter class represents angular meters. The AngularMeter class is a subclass of BaseMeter.

Method | Inherited | Description
AngularMeter | (Self) | Creates a new AngularMeter object.
setMeter | (Self) | Sets the position and angle range of the meter.
addZone | (Self) | Adds a colored zone to the meter.
addZone2 | (Self) | Adds a colored zone to the meter.
addRing | (Self) | Adds a circular ring or a circle to the meter.
addRingSector | (Self) | Adds a ring sector or a sector to the meter.
setCap | (Self) | Set the radius and color of the pointer cap.
setScale | BaseMeter | Sets the meter to use the given scale.
setScale2 | BaseMeter | Sets the meter to use the given scale with the given text labels and tick positions.
setScale3 | BaseMeter | Sets the meter to use the given scale with the given numeric labels and tick positions.
addPointer | BaseMeter | Adds a pointer to the meter.
setLabelStyle | BaseMeter | Sets the font style used to for the meter labels.
setLabelFormat | BaseMeter | Sets the format of the labels computed by ChartDirector.
setLabelPos | BaseMeter | Sets the positions of the meter scale labels.
setMeterColors | BaseMeter | Sets the colors of the meter scale line, scale label and tick.
setLineWidth | BaseMeter | Sets the line widths of the scale line and the ticks on the meter.
setTickLength | BaseMeter | Set the lengths of the ticks.
addLabel | BaseMeter | Adds a label to a specific position on the meter scale.
getLabel | BaseMeter | Gets the label at the specified position on the meter scale.
getCoor | BaseMeter | Gets the geometric coordinates given the data value.
getTicks | BaseMeter | Returns the positions of all ticks as values on the meter scale.
setSize | BaseChart | Sets the size of the chart.
setBackground | BaseChart | Sets the background color, border color and 3D border effect of the chart.
setRoundedFrame | BaseChart | Sets the border style of the chart to rounded corners.
setBorder | BaseChart | Sets the border color of the chart.
setWallpaper | BaseChart | Uses the image from the specified file as the wallpaper to repetitively fill the background of the chart.
setBgImage | BaseChart | Uses the image from the specified file as the background image of the chart.
setSearchPath | BaseChart | Sets the search path for loading image files.
setTransparentColor | BaseChart | Specifies a certain color to mean transparent when creating the image output, or to include alpha transparency channel in the output.
setAntiAlias | BaseChart | Controls whether anti-alias is used when drawing lines, shapes and text.
addTitle | BaseChart | Adds a title at the top center of the chart.
addTitle2 | BaseChart | Adds a title to the chart.
addLegend | BaseChart | Adds a legend box to the chart.
addLegend2 | BaseChart | Adds a legend box to the chart with grid layout.
getLegend | BaseChart | Gets the LegendBox object representing the legend box in the chart.
layoutLegend | BaseChart | Lays out and gets the LegendBox object representing the legend box in the chart.
getDrawArea | BaseChart | Retrieves the internal DrawArea object that is used to draw the chart.
addText | BaseChart | Adds a text box to the chart.
addLine | BaseChart | Adds a line to the chart.
addExtraField | BaseChart | Adds an array of text to be used as an extra field in various places.
addExtraField2 | BaseChart | Adds an array of numbers/dates to be used as an extra field in various places.
setColor | BaseChart | Change the color at the specified position in the palette.
setColors | BaseChart | Change the colors in the palette.
setColors2 | BaseChart | Change the colors in the palette, starting from the specified position in the palette.
getColor | BaseChart | Gets the color at the specified position of the palette.
halfColor | BaseChart | Creates a color that is half the intensity of the given color.
dashLineColor | BaseChart | Creates a dash line color.
patternColor | BaseChart | Creates a pattern color using an array of colors as the bitmap pattern.
patternColor2 | BaseChart | Creates a pattern color by loading the pattern from an image file.
linearGradientColor | BaseChart | Creates a two-point linear gradient color.
linearGradientColor2 | BaseChart | Creates a multi-point linear gradient color.
radialGradientColor | BaseChart | Creates a two-point radial gradient color.
radialGradientColor2 | BaseChart | Creates a multi-point radial gradient color.
gradientColor | BaseChart | Creates a two-point linear gradient color.
gradientColor2 | BaseChart | Creates a multi-point linear gradient color.
setDefaultFonts | BaseChart | Sets the defaults for normal, bold, italic and bold-italic fonts.
setFontTable | BaseChart | Sets an entry in the font table to the specified font name.
formatValue | BaseChart | Formats a number/date using the ChartDirector formatting syntax as is in Parameter Substitution and Formatting.
setNumberFormat | BaseChart | Sets the characters used for thousand separator, decimal point, and negative sign.
setMonthNames | BaseChart | Sets the names of the months for date/time formatting purposes.
setWeekDayNames | BaseChart | Sets the names of the week days for date/time formatting purposes.
setAMPM | BaseChart | Sets the names to be used to denote morning and afternoon.
layout | BaseChart | Perform auto-scaling of the axis and compute the positions of the various objects in the chart.
makeChart | BaseChart | Generates the chart image and save it into a file.
makeChart2 | BaseChart | Generates the chart as an image in memory.
makeChart3 | BaseChart | Generates the chart in internal format and return a DrawArea object to allow adding custom drawings on top of the chart.
makeSession | BaseChart | Generates the chart as an image and save it to a session variable.
makeTmpFile | BaseChart | Generates the chart as an image and save it to a temporary file, and automatically remove old files.
getHTMLImageMap | BaseChart | Generates an HTML image map for the chart.
getChartMetrics | BaseChart | Gets the chart metrics for passing to WebChartViewer.setChartMetrics to support view ports.


AngularMeter.AngularMeter

AngularMeter.AngularMeter

Usage

AngularMeter(width, height [, bgColor [, edgeColor [, raisedEffect ]]])

Description

Creates a new AngularMeter object.

Note: In the ColdFusion edition of ChartDirector, the AngularMeter constructor is implemented as a method of the ChartDirector.CFChart object called ChartDirector.CFChart.AngularMeter.

Arguments

Argument | Default | Description
width | (Mandatory) | The width of the chart in pixels.
height | (Mandatory) | The height of the chart in pixels.
bgColor | BackgroundColor | The background color of the chart.
edgeColor | Transparent | The edge color of the chart.
raisedEffect | 0 | The 3D border width. For positive values, the border will appear raised. For negative values, the border will appear depressed. A zero value means the border will appear flat.

Return Value

The AngularMeter object created.


AngularMeter.setMeter

AngularMeter.setMeter

Usage

setMeter(cx, cy, radius, startAngle, endAngle)

Description

Sets the position and angle range of the meter.

Arguments

Argument | Default | Description
cx | (Mandatory) | The x-coordinate of the center of the meter.
cy | (Mandatory) | The y-coordinate of the center of the meter.
radius | (Mandatory) | The radius of the meter.
startAngle | (Mandatory) | The start angle of the meter. The angle is measured in degrees clockwise, with 0 being the upward pointing direction.
endAngle | (Mandatory) | The end angle of the meter. The angle is measured in degrees clockwise, with 0 being the upward pointing direction.

Return Value

None


AngularMeter.addZone

AngularMeter.addZone

Usage

addZone(startValue, endValue, startRadius, endRadius, fillColor [, edgeColor ])

Description

Adds a colored zone to the meter.

Arguments

Argument | Default | Description
startValue | (Mandatory) | The data value that marks the start position of the zone.
endValue | (Mandatory) | The data value that marks the end position of the zone.
startRadius | (Mandatory) | The starting radius of the zone in pixels.
endRadius | (Mandatory) | The ending radius of the zone in pixels.
fillColor | (Mandatory) | The fill color of the zone.
edgeColor | -1 | The edge color of the zone. The default is the same as the fill color.

Return Value

None


AngularMeter.addZone2

AngularMeter.addZone2

Usage

addZone2(startValue, endValue, fillColor [, edgeColor ])

Description

Adds a colored zone to the meter.

This method is just a short cut to AngularMeter.addZone, in which the starting radius is always 0, and ending radius is the radius of the meter scale. In other words, the zone is a sector on the meter.

Arguments

Argument | Default | Description
startValue | (Mandatory) | The data value that marks the start position of the zone.
endValue | (Mandatory) | The data value that marks the end position of the zone.
fillColor | (Mandatory) | The fill color of the zone.
edgeColor | -1 | The edge color of the zone. The default is the same as the fill color.

Return Value

None


AngularMeter.addRing

AngularMeter.addRing

Usage

addRing(startRadius, endRadius, fillColor [, edgeColor ])

Description

Adds a circular ring or a circle to the meter.

A ring is the region between two concentric circles. This method is most often used for adding circular borders and backgrounds for the meter, and for some other decorative purposes. For example, one can add a circle with a metallic background color as the 'face' of the meter meter using this method.

Arguments

Argument | Default | Description
startRadius | (Mandatory) | The starting radius of the ring in pixels. To add a circle, set the start radius to 0.
endRadius | (Mandatory) | The ending radius of the ring in pixels.
fillColor | (Mandatory) | The fill color of the ring.
edgeColor | -1 | The edge color of the ring. The default is the same as the fill color.

Return Value

None


AngularMeter.addRingSector

AngularMeter.addRingSector

Usage

addRingSector(startRadius, endRadius, a1, a2, fillColor [, edgeColor ])

Description

Adds a ring sector or a sector to the meter.

This method is similar to the AngularMeter.addRing method, except that the ring it adds does not span the complete circle, but just part of the circle.

Arguments

Argument | Default | Description
startRadius | (Mandatory) | The starting radius of the ring sector in pixels. To add a sector, set the starting radius to 0.
endRadius | (Mandatory) | The ending radius of the ring sector in pixels.
a1 | (Mandatory) | The starting angle of the ring sector in degrees. The angle is measured in degrees clockwise, with 0 being the upward pointing direction.
a2 | (Mandatory) | The ending angle of the ring sector in degrees. The angle is measured in degrees clockwise, with 0 being the upward pointing direction.
fillColor | (Mandatory) | The fill color of the ring sector.
edgeColor | -1 | The edge color of the ring sector. The default is the same as the fill color.

Return Value

None


AngularMeter.setCap

AngularMeter.setCap

Usage

setCap(radius, fillColor [, edgeColor ])

Description

Set the radius and color of the pointer cap.

The pointer cap is a circle at the center of the meter above the meter pointer. By default, it is a small circle 3 pixels in radius, so it looks like a "pivot" for the pointer for it to rotate about the center.

You may change the radius and colors of this circle using this method to achieve other visual effects.

Arguments

Argument | Default | Description
radius | (Mandatory) | The radius of pointer cap circle in pixels.
fillColor | (Mandatory) | The fill color of the pointer cap circle.
edgeColor | LineColor | The edge color of the pointer cap circle.

Return Value

None


LinearMeter

LinearMeter

The LinearMeter class represents linear meters. The LinearMeter class is a subclass of BaseMeter.

Method | Inherited | Description
LinearMeter | (Self) | Creates a new LinearMeter object.
setMeter | (Self) | Sets the orientation and position of the meter plot area.
setRail | (Self) | Sets the position, width and color of the pointer rail.
addZone | (Self) | Adds a zone to the meter.
setScale | BaseMeter | Sets the meter to use the given scale.
setScale2 | BaseMeter | Sets the meter to use the given scale with the given text labels and tick positions.
setScale3 | BaseMeter | Sets the meter to use the given scale with the given numeric labels and tick positions.
addPointer | BaseMeter | Adds a pointer to the meter.
setLabelStyle | BaseMeter | Sets the font style used to for the meter labels.
setLabelFormat | BaseMeter | Sets the format of the labels computed by ChartDirector.
setLabelPos | BaseMeter | Sets the positions of the meter scale labels.
setMeterColors | BaseMeter | Sets the colors of the meter scale line, scale label and tick.
setLineWidth | BaseMeter | Sets the line widths of the scale line and the ticks on the meter.
setTickLength | BaseMeter | Set the lengths of the ticks.
addLabel | BaseMeter | Adds a label to a specific position on the meter scale.
getLabel | BaseMeter | Gets the label at the specified position on the meter scale.
getCoor | BaseMeter | Gets the geometric coordinates given the data value.
getTicks | BaseMeter | Returns the positions of all ticks as values on the meter scale.
setSize | BaseChart | Sets the size of the chart.
setBackground | BaseChart | Sets the background color, border color and 3D border effect of the chart.
setRoundedFrame | BaseChart | Sets the border style of the chart to rounded corners.
setBorder | BaseChart | Sets the border color of the chart.
setWallpaper | BaseChart | Uses the image from the specified file as the wallpaper to repetitively fill the background of the chart.
setBgImage | BaseChart | Uses the image from the specified file as the background image of the chart.
setSearchPath | BaseChart | Sets the search path for loading image files.
setTransparentColor | BaseChart | Specifies a certain color to mean transparent when creating the image output, or to include alpha transparency channel in the output.
setAntiAlias | BaseChart | Controls whether anti-alias is used when drawing lines, shapes and text.
addTitle | BaseChart | Adds a title at the top center of the chart.
addTitle2 | BaseChart | Adds a title to the chart.
addLegend | BaseChart | Adds a legend box to the chart.
addLegend2 | BaseChart | Adds a legend box to the chart with grid layout.
getLegend | BaseChart | Gets the LegendBox object representing the legend box in the chart.
layoutLegend | BaseChart | Lays out and gets the LegendBox object representing the legend box in the chart.
getDrawArea | BaseChart | Retrieves the internal DrawArea object that is used to draw the chart.
addText | BaseChart | Adds a text box to the chart.
addLine | BaseChart | Adds a line to the chart.
addExtraField | BaseChart | Adds an array of text to be used as an extra field in various places.
addExtraField2 | BaseChart | Adds an array of numbers/dates to be used as an extra field in various places.
setColor | BaseChart | Change the color at the specified position in the palette.
setColors | BaseChart | Change the colors in the palette.
setColors2 | BaseChart | Change the colors in the palette, starting from the specified position in the palette.
getColor | BaseChart | Gets the color at the specified position of the palette.
halfColor | BaseChart | Creates a color that is half the intensity of the given color.
dashLineColor | BaseChart | Creates a dash line color.
patternColor | BaseChart | Creates a pattern color using an array of colors as the bitmap pattern.
patternColor2 | BaseChart | Creates a pattern color by loading the pattern from an image file.
linearGradientColor | BaseChart | Creates a two-point linear gradient color.
linearGradientColor2 | BaseChart | Creates a multi-point linear gradient color.
radialGradientColor | BaseChart | Creates a two-point radial gradient color.
radialGradientColor2 | BaseChart | Creates a multi-point radial gradient color.
gradientColor | BaseChart | Creates a two-point linear gradient color.
gradientColor2 | BaseChart | Creates a multi-point linear gradient color.
setDefaultFonts | BaseChart | Sets the defaults for normal, bold, italic and bold-italic fonts.
setFontTable | BaseChart | Sets an entry in the font table to the specified font name.
formatValue | BaseChart | Formats a number/date using the ChartDirector formatting syntax as is in Parameter Substitution and Formatting.
setNumberFormat | BaseChart | Sets the characters used for thousand separator, decimal point, and negative sign.
setMonthNames | BaseChart | Sets the names of the months for date/time formatting purposes.
setWeekDayNames | BaseChart | Sets the names of the week days for date/time formatting purposes.
setAMPM | BaseChart | Sets the names to be used to denote morning and afternoon.
layout | BaseChart | Perform auto-scaling of the axis and compute the positions of the various objects in the chart.
makeChart | BaseChart | Generates the chart image and save it into a file.
makeChart2 | BaseChart | Generates the chart as an image in memory.
makeChart3 | BaseChart | Generates the chart in internal format and return a DrawArea object to allow adding custom drawings on top of the chart.
makeSession | BaseChart | Generates the chart as an image and save it to a session variable.
makeTmpFile | BaseChart | Generates the chart as an image and save it to a temporary file, and automatically remove old files.
getHTMLImageMap | BaseChart | Generates an HTML image map for the chart.
getChartMetrics | BaseChart | Gets the chart metrics for passing to WebChartViewer.setChartMetrics to support view ports.


LinearMeter.LinearMeter

LinearMeter.LinearMeter

Usage

LinearMeter(width, height [, bgColor [, edgeColor [, raisedEffect ]]])

Description

Creates a new LinearMeter object.

Note: In the ColdFusion edition of ChartDirector, the LinearMeter constructor is implemented as a method of the ChartDirector.CFChart object called ChartDirector.CFChart.LinearMeter.

Arguments

Argument | Default | Description
width | (Mandatory) | The width of the chart in pixels.
height | (Mandatory) | The height of the chart in pixels.
bgColor | BackgroundColor | The background color of the chart.
edgeColor | Transparent | The edge color of the chart.
raisedEffect | 0 | The 3D border width. For positive values, the border will appear raised. For negative values, the border will appear depressed. A zero value means the border will appear flat.

Return Value

The LinearMeter object created.


LinearMeter.setMeter

LinearMeter.setMeter

Usage

setMeter(leftX, topY, width, height [, axisPos [, isReversed ]])

Description

Sets the orientation and position of the meter plot area.

The plot area is a rectangular region of the linear meter. The meter scale (the labels showing the values) will be on one external side of the plot area (say on the left side). The pointer start on the opposite side and points towards the meter scale.

This method defines the position and size of the rectangular region, as well as which side the meter scale is on. If the scale is on the left or right side, the meter is assumed to be a horizontal linear meter. If the scale is on the top or bottom side, the meter is assumed to be a vertical linear meter.

Arguments

Argument | Default | Description
leftX | (Mandatory) | The x-coordinate of the top-left corner of the meter plot area.
topY | (Mandatory) | The y-coordinate of the top-left corner of the meter plot area.
width | (Mandatory) | The horizontal width of the meter plot area.
height | (Mandatory) | The vertical height of the meter plot area.
axisPos | Left | The position of the meter scale. The scale should be on one of the 4 sides of the plot area border, specified by Left, Top, Right and Bottom.
isReversed | false (zero) | By default, if the meter is horizontal, the meter scale will run from left to right. If the meter is vertical, the meter scale will run from bottom to top. If this argument is set to true (non-zero), the meter scale will be reversed.

Return Value

None


LinearMeter.setRail

LinearMeter.setRail

Usage

setRail(railColor [, railWidth [, railOffset ]])

Description

Sets the position, width and color of the pointer rail.

The pointer rail is the locus traced out by the starting point of the meter pointer as the pointer slides on the meter. The pointer rail is on the opposite side of the meter scale.

Arguments

Argument | Default | Description
railColor | (Mandatory) | The color of the pointer rail.
railWidth | 2 | The line width of the the pointer rail in pixels.
railOffset | 6 | The gap between the pointer rail and the plot area in pixels. A negative value will mean the pointer rail may move within the plot area.

Return Value

None


LinearMeter.addZone

LinearMeter.addZone

Usage

addZone(startValue, endValue, color [, label ])

Description

Adds a zone to the meter.

Arguments

Argument | Default | Description
startValue | (Mandatory) | The start value (the lower bound) for the zone.
endValue | (Mandatory) | The end value (the upper bound) for the zone.
color | (Mandatory) | The color of the zone.
label | "" | The text to be put at the center of the zone.

Return Value

A TextBox object representing the label. This may be used to fine-tune the appearance of the label.


MeterPointer

MeterPointer

The MeterPointer class represents meter pointers. It is created by using BaseMeter.addPointer.

Method | Inherited | Description
setPos | (Self) | Sets the value the pointer points to on the meter scale.
setColor | (Self) | Sets the fill and border colors of the meter pointer.
setShape | (Self) | Sets the shape of the meter pointer to one of the built-in shapes.
setShape2 | (Self) | Sets the shape of the meter pointer to a custom polygon.
setZOrder | (Self) | Sets the z-order (drawing order) of the meter pointer.


MeterPointer.setPos

MeterPointer.setPos

Usage

setPos(value)

Description

Sets the value the pointer points to on the meter scale.

Arguments

Argument | Default | Description
value | (Mandatory) | The value the pointer points to.

Return Value

None


MeterPointer.setColor

MeterPointer.setColor

Usage

setColor(fillColor [, edgeColor ])

Description

Sets the fill and border colors of the meter pointer.

Arguments

Argument | Default | Description
fillColor | (Mandatory) | The fill color of the meter pointer.
edgeColor | -1 | The border color of the meter pointer. The default value of -1 means it is the same as the fill color.

Return Value

None


MeterPointer.setShape

MeterPointer.setShape

Usage

setShape(pointerType [, lengthRatio [, widthRatio ]])

Description

Sets the shape of the meter pointer to one of the built-in shapes.

The built-in symbols are specified by using the following predefined constants as the pointerType argument.

Constant | Value | Description
DiamondPointer | 0 | The blue pointers in the meters above.
TriangularPointer | 1 | The purple pointers in the meters above.
ArrowPointer | 2 | The red pointers in the meters above.
ArrowPointer2 | 3 | The yellow pointers in the meters above.
LinePointer | 4 | The green pointers in the meters above.
PencilPointer | 5 | The grey pointers in the meters above.

The length and width of the pointer can be scaled by using the lengthRatio and widthRatio arguments. The meters above are using default length and width ratios, which are both 1 for angular meters, and 0.75 and 1 for linear meters.

Arguments

Argument | Default | Description
pointerType | (Mandatory) | One of the predefined pointer shape constants to specify the pointer shape to use.
lengthRatio | NoValue | The length ratio applies to the pointer. NoValue means the lengthRatio is not modified. The default is 1.0 for angular meters and 0.75 for linear meters.
widthRatio | NoValue | The width ratio applies to the pointer. NoValue means the widthRatio is not modified. The default is 1.0.

Return Value

None


MeterPointer.setShape2

MeterPointer.setShape2

Usage

setShape2(pointerCoor [, lengthRatio [, widthRatio ]])

Description

Sets the shape of the meter pointer to a custom polygon.

The custom polygon is specified as a list of numbers representing the (x, y) coordinates of polygon vertices.

For an angular meter, the polygon should be defined with a nominal dimension of 1000 units. ChartDirector will scale the polygon so that 1000 units will become the radius of the meter.

For a linear meter, the length of the pointer should be defined with a nominal dimension of 1000 units. ChartDirector will scale the polygon so that 1000 units will be the length required for the pointer to reach the meter scale. The width of the pointer will be in 0.1 pixel units (that is, 10 units = 1 pixel).

The coordinate system for defining the polygon is that the x-axis points from left to right, and the y-axis points from bottom to top. The polygon will be defined as a pointer with the pivot at the origin, pointing to the upward direction.

As an example, the coordinates of the standard diamond pointer for an angular meter are:

0, -100, -50, -50, 0, 1000, 50, -50

The coordinates for the standard pencil pointer for a linear meter are:

-30, 0, 30, 0, 30, 768, 0, 1000, -30, 768

After scaling the pointers based on the nominal units, ChartDirector will in addition applies the lengthRatio and widthRatio scaling factor to the pointer. These ratios allow you to change the pointer sizes without changing the polygon definition. For example, if you want the meter pointer to be only 80% of the radius in the angular meter, you can set the lengthRatio to 0.80.

Arguments

Argument | Default | Description
pointerCoor | (Mandatory) | An array of numbers x0, y0, x1, y1, x2, y2, ..., representing the coordinates the polygon vertices.
lengthRatio | NoValue | The length ratio applies to the pointer. NoValue means the lengthRatio is not modified. The default is 1.0 for angular meters and 0.75 for linear meters.
widthRatio | NoValue | The width ratio applies to the pointer. NoValue means the widthRatio is not modified. The default is 1.0.

Return Value

None


MeterPointer.setZOrder

MeterPointer.setZOrder

Usage

setZOrder(z)

Description

Sets the z-order (drawing order) of the meter pointer.

Please refer to Box.setZOrder on an explanation of z-order and the z-order of various standard ChartDirector objects.

Arguments

Argument | Default | Description
z | (Mandatory) | The z-order of the meter pointer.

Return Value

None


FinanceChart

FinanceChart

FinanceChart is a financial charting library built on top of the main ChartDirector library. It extends MultiChart by implementing many financial indicators, and allowing complex financial charts to be composed easily.

Key Features

  • Arbitrary Financial Chart Composition: Allows a complex financial chart to be constructed by stacking a main financial chart with arbitrary number of indicator charts in any order.

  • Main Chart Layers: The main chart can show information in Candlestick or OHLC, and/or various price lines, such as closing price line, weighted close line, typical price line or median price line.

  • Moving Averages: Chart can include arbitrary number of moving average lines of configurable types and periods. Supports simple, exponential, triangular and weighted moving averages.

  • Bands and Envelops: Built-in Bollinger Band layer, Donchian Channel layer, and moving average envelops. Also supports custom-defined bands.

  • Volume Bars: Volume Bars can be displayed as part of the main chart, or as a separate indicator chart.

  • Axis Styles: Axis can be log or linear scale, and can display on left or right side of the chart.

  • Built-In Indicators: Accumulation/Distribution, Aroon Up/Down, Aroon Oscillator, Average Directional Index, Average True Range (including raw True Range), Bollinger Band Width, Commodity Channel Index, Chaikin Money Flow, Chaikin Oscillator, Chaikin Volatility, Close Location Value, Detrended Price Oscillator, Donchian Channel Width, Ease of Movement, Fast Stochastic, MACD, Mass Index, Money Flow Index, Momentum, Negative Volume Index, On Balance Volume, Performance, Percentage Price Oscillator, Positive Volume Index, Percentage Volume Oscillator, Price Volume Trend, Rate of Change, Relative Strength Index, Slow Stochastic, Standard Deviation, Stochastic RSI, TRIX, Ultimate Oscillator, Volume, William %R.

  • Custom Lines and Indicators: Extensible design allows developers to implement additional lines and indicator types.

  • Customizable Look and Feel: Preserves the flexibility and power of the ChartDirector API. Background images, custom text boxes, logos, fonts and colors, etc., are all customizable.

Using FinanceChart

To use FinanceChart, the first step is to create an instance of FinanceChart. Next, you may add data to it using setData. After that, you may add the main chart (addMainChart) and other indicator charts to display the data graphically. These charts may be added in any order.

For the main chart, you may:

  • Display price information using Candlesticks (addCandleStick) or HLOC (addHLOC) symbols

  • Add various price lines (addCloseLine, addWeightedClose, addTypicalPrice, addMedianPrice)

  • Add moving average lines of different types and periods (addSimpleMovingAvg, addExpMovingAvg, addTriMovingAvg, addWeightedMovingAvg)

  • Add price bands or envelops: (addBollingerBand, addDonchianChannel, addEnvelop)

  • Add custom lines or bands (addLineIndicator2, addBand)

  • Add volume bars (addVolBars)
For indicator charts, FinanceChart includes a wide variety of indicators. Please refer to the table below for details. You may also add your own custom indicator chart using addLineIndicator and addBarIndicator.

In addition to chart building methods, FinanceChart also has a number of chart formatting methods, such as addPlotAreaTitle to add chart title, setPlotAreaStyle to control background color and grid lines, setDateLabelFormat to control date/time formatting, etc.

Furthermore, as FinanceChart is a subclass of MultiChart, and the main and indicator charts are implemented as XYChart objects, they can use the powerful ChartDirector API for formatting (eg. background images, custom logos, custom text boxes, metallic colors, etc).

FinanceChart Methods

Method | Inherited | Description
FinanceChart | (Self) | Creates a new FinanceChart object.
enableAntiAlias | (Self) | Enables/Disables anti-alias.
setMargins | (Self) | Sets the margins around the plot area.
addPlotAreaTitle | (Self) | Adds a text title above the plot area. You may add multiple title above the plot area by calling this method multiple times.
setPlotAreaStyle | (Self) | Sets the plot area style. The default is to use very pale yellow FFFFF0 as background, and light grey DDDDDD for the grid lines.
setLegendStyle | (Self) | Sets legend style. The default is using Arial 8 pt black color as font on a semi-transparent pale blue 80CCCCFF background.
setXAxisStyle | (Self) | Sets x-axis label style. The default is Arial 8 pt black color as font with no text rotation.
setYAxisStyle | (Self) | Sets y-axis label style. The default is Arial 8 pt black color, with 13 pixels margin.
setAxisOnRight | (Self) | Sets whether the main y-axis is on right of left side of the plot area. The default is on right.
setLogScale | (Self) | Determines if log scale should be used for the main chart. The default is to use linear scale.
setDateLabelFormat | (Self) | Sets the date/time formats to use for the x-axis labels under various cases.
setDateLabelSpacing | (Self) | Sets the minimum label spacing between two labels on the time axis.
setToolTipDateFormat | (Self) | Sets the date/time formats to use for the tool tips under various cases.
getToolTipDateFormat | (Self) | Gets the date/time format string to use for tool tips.
setNumberLabelFormat | (Self) | Sets the number format to use.
setData | (Self) | Sets the data to be used in the chart.
addMainChart | (Self) | Adds the main chart - the chart that shows the data for the prices.
addCandleStick | (Self) | Adds a candlestick layer to the main chart.
addHLOC | (Self) | Adds a HLOC layer to the main chart.
addCloseLine | (Self) | Adds a closing price line on the main chart.
addWeightedClose | (Self) | Adds a weighted close line on the main chart.
addTypicalPrice | (Self) | Adds a typical price line on the main chart.
addMedianPrice | (Self) | Adds a median price line on the main chart.
addSimpleMovingAvg | (Self) | Adds a simple moving average line on the main chart.
addExpMovingAvg | (Self) | Adds an exponential moving average line on the main chart.
addTriMovingAvg | (Self) | Adds a triangular moving average line on the main chart.
addWeightedMovingAvg | (Self) | Adds a weighted moving average line on the main chart.
addBand | (Self) | Adds a generic band to the main finance chart. This method is used internally by other methods to add various bands (eg. Bollinger band, Donchian channels, etc).
addBollingerBand | (Self) | Adds a Bollinger band on the main chart.
addDonchianChannel | (Self) | Adds a Donchian channel on the main chart.
addEnvelop | (Self) | Adds a price envelop on the main chart. The price envelop is a defined as a ratio around a moving average. For example, a ratio of 0.2 means 20% above and below the moving average.
addVolBars | (Self) | Adds a volume bar chart layer on the main chart.
addIndicator | (Self) | Adds a blank indicator chart to the finance chart. Used internally to add other indicators. Override to change the default formatting (eg. axis fonts, etc.) of the various indicators.
addLineIndicator | (Self) | Adds a generic line indicator chart.
addLineIndicator2 | (Self) | Adds a line to an existing indicator chart.
addBarIndicator | (Self) | Adds a generic bar indicator chart.
addBarIndicator2 | (Self) | Adds a bar layer to an existing indicator chart.
addThreshold | (Self) | Adds an upper/lower threshold range to an existing indicator chart.
addAccDist | (Self) | Adds an Accumulation/Distribution indicator chart.
addAroon | (Self) | Adds an Aroon Up/Down indicators chart.
addAroonOsc | (Self) | Adds an Aroon Oscillator indicator chart.
addADX | (Self) | Adds an Average Directional Index indicators chart.
addATR | (Self) | Adds an Average True Range indicators chart.
addBollingerWidth | (Self) | Adds a Bollinger Band Width indicator chart.
addCCI | (Self) | Adds a Community Channel Index indicator chart.
addChaikinMoneyFlow | (Self) | Adds a Chaikin Money Flow indicator chart.
addChaikinOscillator | (Self) | Adds a Chaikin Oscillator indicator chart.
addChaikinVolatility | (Self) | Adds a Chaikin Volatility indicator chart.
addCLV | (Self) | Adds a Close Location Value indicator chart.
addDPO | (Self) | Adds a Detrended Price Oscillator indicator chart.
addDonchianWidth | (Self) | Adds a Donchian Channel Width indicator chart.
addEaseOfMovement | (Self) | Adds a Ease of Movement indicator chart.
addFastStochastic | (Self) | Adds a Fast Stochastic indicator chart.
addMACD | (Self) | Adds a MACD indicator chart.
addMassIndex | (Self) | Adds a Mass Index indicator chart.
addMFI | (Self) | Adds a Money Flow Index indicator chart.
addMomentum | (Self) | Adds a Momentum indicator chart.
addNVI | (Self) | Adds a Negative Volume Index indicator chart.
addOBV | (Self) | Adds an On Balance Volume indicator chart.
addPerformance | (Self) | Adds a Performance indicator chart.
addPPO | (Self) | Adds a Percentage Price Oscillator indicator chart.
addPVI | (Self) | Adds a Positive Volume Index indicator chart.
addPVO | (Self) | Adds a Percentage Volume Oscillator indicator chart.
addPVT | (Self) | Adds a Price Volume Trend indicator chart.
addROC | (Self) | Adds a Rate of Change indicator chart.
addRSI | (Self) | Adds a Relative Strength Index indicator chart.
addSlowStochastic | (Self) | Adds a Slow Stochastic indicator chart.
addStdDev | (Self) | Adds a Moving Standard Deviation indicator chart.
addStochRSI | (Self) | Adds a Stochastic RSI indicator chart.
addTRIX | (Self) | Adds a TRIX indicator chart.
addUltimateOscillator | (Self) | Adds an Ultimate Oscillator indicator chart.
addVolIndicator | (Self) | Adds a Volume indicator chart.
addWilliamR | (Self) | Adds a William %R indicator chart.
MultiChart | MultiChart | Creates a new MultiChart object.
addChart | MultiChart | Adds a BaseChart object (or its subclass such as PieChart, XYChart, PolarChart, AngularMeter or LinearMeter) into the multi-chart.
setMainChart | MultiChart | Sets the chart that receives view port mouse actions (for zooming and scrolling support).
setSize | BaseChart | Sets the size of the chart.
setBackground | BaseChart | Sets the background color, border color and 3D border effect of the chart.
setRoundedFrame | BaseChart | Sets the border style of the chart to rounded corners.
setBorder | BaseChart | Sets the border color of the chart.
setWallpaper | BaseChart | Uses the image from the specified file as the wallpaper to repetitively fill the background of the chart.
setBgImage | BaseChart | Uses the image from the specified file as the background image of the chart.
setSearchPath | BaseChart | Sets the search path for loading image files.
setTransparentColor | BaseChart | Specifies a certain color to mean transparent when creating the image output, or to include alpha transparency channel in the output.
setAntiAlias | BaseChart | Controls whether anti-alias is used when drawing lines, shapes and text.
addTitle | BaseChart | Adds a title at the top center of the chart.
addTitle2 | BaseChart | Adds a title to the chart.
addLegend | BaseChart | Adds a legend box to the chart.
addLegend2 | BaseChart | Adds a legend box to the chart with grid layout.
getLegend | BaseChart | Gets the LegendBox object representing the legend box in the chart.
layoutLegend | BaseChart | Lays out and gets the LegendBox object representing the legend box in the chart.
getDrawArea | BaseChart | Retrieves the internal DrawArea object that is used to draw the chart.
addText | BaseChart | Adds a text box to the chart.
addLine | BaseChart | Adds a line to the chart.
addExtraField | BaseChart | Adds an array of text to be used as an extra field in various places.
addExtraField2 | BaseChart | Adds an array of numbers/dates to be used as an extra field in various places.
setColor | BaseChart | Change the color at the specified position in the palette.
setColors | BaseChart | Change the colors in the palette.
setColors2 | BaseChart | Change the colors in the palette, starting from the specified position in the palette.
getColor | BaseChart | Gets the color at the specified position of the palette.
halfColor | BaseChart | Creates a color that is half the intensity of the given color.
dashLineColor | BaseChart | Creates a dash line color.
patternColor | BaseChart | Creates a pattern color using an array of colors as the bitmap pattern.
patternColor2 | BaseChart | Creates a pattern color by loading the pattern from an image file.
linearGradientColor | BaseChart | Creates a two-point linear gradient color.
linearGradientColor2 | BaseChart | Creates a multi-point linear gradient color.
radialGradientColor | BaseChart | Creates a two-point radial gradient color.
radialGradientColor2 | BaseChart | Creates a multi-point radial gradient color.
gradientColor | BaseChart | Creates a two-point linear gradient color.
gradientColor2 | BaseChart | Creates a multi-point linear gradient color.
setDefaultFonts | BaseChart | Sets the defaults for normal, bold, italic and bold-italic fonts.
setFontTable | BaseChart | Sets an entry in the font table to the specified font name.
formatValue | BaseChart | Formats a number/date using the ChartDirector formatting syntax as is in Parameter Substitution and Formatting.
setNumberFormat | BaseChart | Sets the characters used for thousand separator, decimal point, and negative sign.
setMonthNames | BaseChart | Sets the names of the months for date/time formatting purposes.
setWeekDayNames | BaseChart | Sets the names of the week days for date/time formatting purposes.
setAMPM | BaseChart | Sets the names to be used to denote morning and afternoon.
layout | BaseChart | Perform auto-scaling of the axis and compute the positions of the various objects in the chart.
makeChart | BaseChart | Generates the chart image and save it into a file.
makeChart2 | BaseChart | Generates the chart as an image in memory.
makeChart3 | BaseChart | Generates the chart in internal format and return a DrawArea object to allow adding custom drawings on top of the chart.
makeSession | BaseChart | Generates the chart as an image and save it to a session variable.
makeTmpFile | BaseChart | Generates the chart as an image and save it to a temporary file, and automatically remove old files.
getHTMLImageMap | BaseChart | Generates an HTML image map for the chart.
getChartMetrics | BaseChart | Gets the chart metrics for passing to WebChartViewer.setChartMetrics to support view ports.


FinanceChart.FinanceChart

FinanceChart.FinanceChart

Usage

FinanceChart(width)

Description

Creates a new FinanceChart object.

Note: In the ColdFusion edition of ChartDirector, the FinanceChart constructor is implemented as a method of the ChartDirector.CFChart object called ChartDirector.CFChart.FinanceChart.

Arguments

Argument | Default | Description
width | (Mandatory) | The width of the chart in pixels. The height will be automatically determined as the chart is built.

Return Value

The FinanceChart object created.


FinanceChart.enableAntiAlias

FinanceChart.enableAntiAlias

Usage

enableAntiAlias(antiAlias)

Description

Enables/Disables anti-alias.

Enabling anti-alias makes the line smoother. Disabling anti-alias make the chart file size smaller, and so can be downloaded faster through the Internet. The default is to enable anti-alias.

Arguments

Argument | Default | Description
antiAlias | (Mandatory) | True to enable anti-alias. False to disable anti-alias.

Return Value

None


FinanceChart.setMargins

FinanceChart.setMargins

Usage

setMargins(leftMargin, topMargin, rightMargin, bottomMargin)

Description

Sets the margins around the plot area.

Arguments

Argument | Default | Description
leftMargin | (Mandatory) | The distance from the left side of the plot area to the left side of the chart.
topMargin | (Mandatory) | The distance from the top of the plot area to the top of the chart.
rightMargin | (Mandatory) | The distance from the right side of the plot area to the right side of the chart.
bottomMargin | (Mandatory) | The distance from the bottom of the plot area to the bottom of the chart.

Return Value

None


FinanceChart.addPlotAreaTitle

FinanceChart.addPlotAreaTitle

Usage

addPlotAreaTitle(alignment, text)

Description

Adds a text title above the plot area. You may add multiple title above the plot area by calling this method multiple times.

Arguments

Argument | Default | Description
alignment | (Mandatory) | The alignment with respect to the region that is on top of the plot area. See Alignment Specification for supported alignment types.
text | (Mandatory) | The text to add.

Return Value

The TextBox object representing the text box above the plot area, which may be used to fine-tune the appearance of the text.


FinanceChart.setPlotAreaStyle

FinanceChart.setPlotAreaStyle

Usage

setPlotAreaStyle(bgColor, majorHGridColor, majorVGridColor, minorHGridColor, minorVGridColor)

Description

Sets the plot area style. The default is to use very pale yellow FFFFF0 as background, and light grey DDDDDD for the grid lines.

Arguments

Argument | Default | Description
bgColor | (Mandatory) | The plot area background color.
majorHGridColor | (Mandatory) | Major horizontal grid color.
majorVGridColor | (Mandatory) | Major vertical grid color.
minorHGridColor | (Mandatory) | Minor horizontal grid color. In current version, minor horizontal grid is not used.
minorVGridColor | (Mandatory) | Minor vertical grid color.

Return Value

None


FinanceChart.setLegendStyle

FinanceChart.setLegendStyle

Usage

setLegendStyle(font, fontSize, fontColor, bgColor)

Description

Sets legend style. The default is using Arial 8 pt black color as font on a semi-transparent pale blue 80CCCCFF background.

Arguments

Argument | Default | Description
font | (Mandatory) | The font of the legend text.
fontSize | (Mandatory) | The font size of the legend text in points.
fontColor | (Mandatory) | The color of the legend text.
bgColor | (Mandatory) | The background color of the legend box.

Return Value

None


FinanceChart.setXAxisStyle

FinanceChart.setXAxisStyle

Usage

setXAxisStyle(font, fontSize, fontColor, fontAngle)

Description

Sets x-axis label style. The default is Arial 8 pt black color as font with no text rotation.

Arguments

Argument | Default | Description
font | (Mandatory) | The font of the axis labels.
fontSize | (Mandatory) | The font size of the axis labels in points.
fontColor | (Mandatory) | The color of the axis labels.
fontAngle | (Mandatory) | The rotation of the axis labels.

Return Value

None


FinanceChart.setYAxisStyle

FinanceChart.setYAxisStyle

Usage

setYAxisStyle(font, fontSize, fontColor, axisMargin)

Description

Sets y-axis label style. The default is Arial 8 pt black color, with 13 pixels margin.

Arguments

Argument | Default | Description
font | (Mandatory) | The font of the axis labels.
fontSize | (Mandatory) | The font size of the axis labels in points.
fontColor | (Mandatory) | The color of the axis labels.
axisMargin | (Mandatory) | The margin at the top of the y-axis in pixels (to leave space for the legend box).

Return Value

None


FinanceChart.setAxisOnRight

FinanceChart.setAxisOnRight

Usage

setAxisOnRight(b)

Description

Sets whether the main y-axis is on right of left side of the plot area. The default is on right.

Arguments

Argument | Default | Description
b | (Mandatory) | A true (non-zero) value means the y-axis is on right. A false (zero) value means the y-axis is on left.

Return Value

None


FinanceChart.setLogScale

FinanceChart.setLogScale

Usage

setLogScale(b)

Description

Determines if log scale should be used for the main chart. The default is to use linear scale.

Arguments

Argument | Default | Description
b | (Mandatory) | A true (non-zero) value means using log scale. A false (zero) value means using linear scale.

Return Value

None


FinanceChart.setDateLabelFormat

FinanceChart.setDateLabelFormat

Usage

setDateLabelFormat(yearFormat, firstMonthFormat, otherMonthFormat, firstDayFormat, otherDayFormat, firstHourFormat, otherHourFormat)

Description

Sets the date/time formats to use for the x-axis labels under various cases.

See Parameter Substitution and Formatting on the syntax of ChartDirector format strings.

Arguments

Argument | Default | Description
yearFormat | (Mandatory) | The format for displaying labels on an axis with yearly ticks. The default is "{value|yyyy}".
firstMonthFormat | (Mandatory) | The format for displaying labels on an axis with monthly ticks. This parameter applies to the first available month of a year (usually January) only, so it can be formatted differently from the other labels. The default is "<*font=bold*>{value|mmm yy}".
otherMonthFormat | (Mandatory) | The format for displaying labels on an axis with monthly ticks. This parameter applies to months other than the first available month of a year. The default is "{value|mmm}".
firstDayFormat | (Mandatory) | The format for displaying labels on an axis with daily ticks. This parameter applies to the first available day of a month only, so it can be formatted differently from the other labels. The default is "<*font=bold*>{value|d mmm}".
otherDayFormat | (Mandatory) | The format for displaying labels on an axis with daily ticks. This parameter applies to days other than the first available day of a month. The default is "{value|d}".
firstHourFormat | (Mandatory) | The format for displaying labels on an axis with hourly resolution. This parameter applies to the first tick of a day only, so it can be formatted differently from the other labels. The default is "<*font=bold*>{value|d mmm<*br*>h:nna}".
otherHourFormat | (Mandatory) | The format for displaying labels on an axis with hourly. resolution. This parameter applies to ticks at hourly boundaries, except the first tick of a day. The default is "{value|h:nna}".

Return Value

None


FinanceChart.setDateLabelSpacing

FinanceChart.setDateLabelSpacing

Usage

setDateLabelSpacing(labelSpacing)

Description

Sets the minimum label spacing between two labels on the time axis.

Arguments

Argument | Default | Description
labelSpacing | (Mandatory) | The label spacing in pixels. The default is 50 pixels.

Return Value

None


FinanceChart.setToolTipDateFormat

FinanceChart.setToolTipDateFormat

Usage

setToolTipDateFormat(monthFormat, dayFormat, hourFormat)

Description

Sets the date/time formats to use for the tool tips under various cases.

See Parameter Substitution and Formatting on the syntax of ChartDirector format strings.

Arguments

Argument | Default | Description
monthFormat | (Mandatory) | The tool tip format to use if the data point spacing is one or more months (more than 30 days). The default is "[{xLabel|mmm yyyy}]".
dayFormat | (Mandatory) | The tool tip format to use if the data point spacing is 1 day to less than 30 days. The default is "[{xLabel|mmm d, yyyy}]".
hourFormat | (Mandatory) | The tool tip format to use if the data point spacing is less than 1 day. The default is "[{xLabel|mmm d, yyyy hh:nn:ss}]".

Return Value

None


FinanceChart.getToolTipDateFormat

FinanceChart.getToolTipDateFormat

Usage

getToolTipDateFormat()

Description

Gets the date/time format string to use for tool tips.

The format string returned will be one of the format strings specified when calling FinanceChart.setToolTipDateFormat based on data point spacing, or the equivalent default value. The format string may then be used in other ChartDirector functions such as BaseChart.getHTMLImageMap for producing image maps.

Arguments

None

Return Value

The date/time format string to use for tool tips.


FinanceChart.setNumberLabelFormat

FinanceChart.setNumberLabelFormat

Usage

setNumberLabelFormat(formatString)

Description

Sets the number format to use.

The default number format in FinanceChart is "G". See Parameter Substitution and Formatting on the syntax of ChartDirector format strings.

Arguments

Argument | Default | Description
formatString | (Mandatory) | The format for displaying numbers.

Return Value

None


FinanceChart.setData

FinanceChart.setData

Usage

setData(timeStamps, highData, lowData, openData, closeData, volData, extraPoints)

Description

Sets the data to be used in the chart.

If some of the data are not available, some artificial values should be used. For example, if the high and low values are not available, you may use closeData as highData and lowData.

Arguments

Argument | Default | Description
timeStamps | (Mandatory) | An array of dates/times for the time intervals.
highData | (Mandatory) | The high values in the time intervals.
lowData | (Mandatory) | The low values in the time intervals.
openData | (Mandatory) | The open values in the time intervals.
closeData | (Mandatory) | The close values in the time intervals.
volData | (Mandatory) | The volume values in the time intervals.
extraPoints | (Mandatory) | The number of leading time intervals that are not displayed in the chart. These intervals are typically used for computing indicators that require extra leading data, such as moving averages.

Return Value

None


FinanceChart.addMainChart

FinanceChart.addMainChart

Usage

addMainChart(height)

Description

Adds the main chart - the chart that shows the data for the prices.

The chart added is initially empty. Other methods, such as FinanceChart.addCandleStick and FinanceChart.addSimpleMovingAvg, may be used to add various layers to the chart.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the main chart in pixels.

Return Value

A XYChart object representing the main chart created.


FinanceChart.addCandleStick

FinanceChart.addCandleStick

Usage

addCandleStick(upColor, downColor)

Description

Adds a candlestick layer to the main chart.

Arguments

Argument | Default | Description
upColor | (Mandatory) | The candle color for a up day.
downColor | (Mandatory) | The candle color for a down day.

Return Value

A CandleStickLayer object representing the candlestick layer created.


FinanceChart.addHLOC

FinanceChart.addHLOC

Usage

addHLOC(upColor, downColor)

Description

Adds a HLOC layer to the main chart.

Arguments

Argument | Default | Description
upColor | (Mandatory) | The candle color for a up day.
downColor | (Mandatory) | The candle color for a down day.

Return Value

A HLOCLayer object representing the HLOC layer created.


FinanceChart.addCloseLine

FinanceChart.addCloseLine

Usage

addCloseLine(color)

Description

Adds a closing price line on the main chart.

Arguments

Argument | Default | Description
color | (Mandatory) | The color of the line.

Return Value

A LineLayer object representing the line created.


FinanceChart.addWeightedClose

FinanceChart.addWeightedClose

Usage

addWeightedClose(color)

Description

Adds a weighted close line on the main chart.

Arguments

Argument | Default | Description
color | (Mandatory) | The color of the line.

Return Value

A LineLayer object representing the line created.


FinanceChart.addTypicalPrice

FinanceChart.addTypicalPrice

Usage

addTypicalPrice(color)

Description

Adds a typical price line on the main chart.

Arguments

Argument | Default | Description
color | (Mandatory) | The color of the line.

Return Value

A LineLayer object representing the line created.


FinanceChart.addMedianPrice

FinanceChart.addMedianPrice

Usage

addMedianPrice(color)

Description

Adds a median price line on the main chart.

Arguments

Argument | Default | Description
color | (Mandatory) | The color of the line.

Return Value

A LineLayer object representing the line created.


FinanceChart.addSimpleMovingAvg

FinanceChart.addSimpleMovingAvg

Usage

addSimpleMovingAvg(period, color)

Description

Adds a simple moving average line on the main chart.

Arguments

Argument | Default | Description
period | (Mandatory) | The moving average period
color | (Mandatory) | The color of the line.

Return Value

A LineLayer object representing the line created.


FinanceChart.addExpMovingAvg

FinanceChart.addExpMovingAvg

Usage

addExpMovingAvg(period, color)

Description

Adds an exponential moving average line on the main chart.

Arguments

Argument | Default | Description
period | (Mandatory) | The moving average period
color | (Mandatory) | The color of the line.

Return Value

A LineLayer object representing the line created.


FinanceChart.addTriMovingAvg

FinanceChart.addTriMovingAvg

Usage

addTriMovingAvg(period, color)

Description

Adds a triangular moving average line on the main chart.

Arguments

Argument | Default | Description
period | (Mandatory) | The moving average period
color | (Mandatory) | The color of the line.

Return Value

A LineLayer object representing the line created.


FinanceChart.addWeightedMovingAvg

FinanceChart.addWeightedMovingAvg

Usage

addWeightedMovingAvg(period, color)

Description

Adds a weighted moving average line on the main chart.

Arguments

Argument | Default | Description
period | (Mandatory) | The moving average period
color | (Mandatory) | The color of the line.

Return Value

A LineLayer object representing the line created.


FinanceChart.addBand

FinanceChart.addBand

Usage

addBand(upperLine, lowerLine, lineColor, fillColor, name)

Description

Adds a generic band to the main finance chart. This method is used internally by other methods to add various bands (eg. Bollinger band, Donchian channels, etc).

Arguments

Argument | Default | Description
upperLine | (Mandatory) | The data series for the upper band line.
lowerLine | (Mandatory) | The data series for the lower band line.
lineColor | (Mandatory) | The color of the upper and lower band line.
fillColor | (Mandatory) | The color to fill the region between the upper and lower band lines.
name | (Mandatory) | The name of the band.

Return Value

An InterLineLayer object representing the filled region.


FinanceChart.addBollingerBand

FinanceChart.addBollingerBand

Usage

addBollingerBand(period, bandWidth, lineColor, fillColor)

Description

Adds a Bollinger band on the main chart.

Arguments

Argument | Default | Description
period | (Mandatory) | The period to compute the band.
bandWidth | (Mandatory) | The half-width of the band in terms multiples of standard deviation. Typically 2 is used.
lineColor | (Mandatory) | The color of the lines defining the upper and lower limits.
fillColor | (Mandatory) | The color to fill the regional within the band.

Return Value

An InterLineLayer object representing the band created.


FinanceChart.addDonchianChannel

FinanceChart.addDonchianChannel

Usage

addDonchianChannel(period, lineColor, fillColor)

Description

Adds a Donchian channel on the main chart.

Arguments

Argument | Default | Description
period | (Mandatory) | The period to compute the band.
lineColor | (Mandatory) | The color of the lines defining the upper and lower limits.
fillColor | (Mandatory) | The color to fill the regional within the band.

Return Value

An InterLineLayer object representing the band created.


FinanceChart.addEnvelop

FinanceChart.addEnvelop

Usage

addEnvelop(period, range, lineColor, fillColor)

Description

Adds a price envelop on the main chart. The price envelop is a defined as a ratio around a moving average. For example, a ratio of 0.2 means 20% above and below the moving average.

Arguments

Argument | Default | Description
period | (Mandatory) | The period for the moving average.
range | (Mandatory) | The ratio above and below the moving average.
lineColor | (Mandatory) | The color of the lines defining the upper and lower limits.
fillColor | (Mandatory) | The color to fill the regional within the band.

Return Value

An InterLineLayer object representing the band created.


FinanceChart.addVolBars

FinanceChart.addVolBars

Usage

addVolBars(height, upColor, downColor, flatColor)

Description

Adds a volume bar chart layer on the main chart.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the bar chart layer in pixels.
upColor | (Mandatory) | The color to used on an 'up' day. An 'up' day is a day where the closing price is higher than that of the previous day.
downColor | (Mandatory) | The color to used on a 'down' day. A 'down' day is a day where the closing price is lower than that of the previous day.
flatColor | (Mandatory) | The color to used on a 'flat' day. A 'flat' day is a day where the closing price is the same as that of the previous day.

Return Value

A BarLayer object representing the bar layer created.


FinanceChart.addIndicator

FinanceChart.addIndicator

Usage

addIndicator(height)

Description

Adds a blank indicator chart to the finance chart. Used internally to add other indicators. Override to change the default formatting (eg. axis fonts, etc.) of the various indicators.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the chart in pixels.

Return Value

A XYChart object representing the chart created.


FinanceChart.addLineIndicator

FinanceChart.addLineIndicator

Usage

addLineIndicator(height, data, color, name)

Description

Adds a generic line indicator chart.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the indicator chart in pixels.
data | (Mandatory) | The data series of the indicator line.
color | (Mandatory) | The color of the indicator line.
name | (Mandatory) | The name of the indicator.

Return Value

A XYChart object representing the chart created.


FinanceChart.addLineIndicator2

FinanceChart.addLineIndicator2

Usage

addLineIndicator2(c, data, color, name)

Description

Adds a line to an existing indicator chart.

Arguments

Argument | Default | Description
c | (Mandatory) | The indicator chart to add the line to.
data | (Mandatory) | The data series of the indicator line.
color | (Mandatory) | The color of the indicator line.
name | (Mandatory) | The name of the indicator.

Return Value

A LineLayer object representing the line created.


FinanceChart.addBarIndicator

FinanceChart.addBarIndicator

Usage

addBarIndicator(height, data, color, name)

Description

Adds a generic bar indicator chart.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the indicator chart in pixels.
data | (Mandatory) | The data series of the indicator bars.
color | (Mandatory) | The color of the indicator bars.
name | (Mandatory) | The name of the indicator.

Return Value

A XYChart object representing the chart created.


FinanceChart.addBarIndicator2

FinanceChart.addBarIndicator2

Usage

addBarIndicator2(c, data, color, name)

Description

Adds a bar layer to an existing indicator chart.

Arguments

Argument | Default | Description
c | (Mandatory) | The indicator chart to add the bar layer to.
data | (Mandatory) | The data series of the indicator bars.
color | (Mandatory) | The color of the indicator bars.
name | (Mandatory) | The name of the indicator.

Return Value

A BarLayer object representing the bar layer created.


FinanceChart.addThreshold

FinanceChart.addThreshold

Usage

addThreshold(c, layer, topRange, topColor, bottomRange, bottomColor)

Description

Adds an upper/lower threshold range to an existing indicator chart.

Arguments

Argument | Default | Description
c | (Mandatory) | The indicator chart to add the threshold range to.
layer | (Mandatory) | The line layer that the threshold range applies to.
topRange | (Mandatory) | The upper threshold.
topColor | (Mandatory) | The color to fill the region of the line that is above the upper threshold.
bottomRange | (Mandatory) | The lower threshold.
bottomColor | (Mandatory) | The color to fill the region of the line that is below the lower threshold.

Return Value

None


FinanceChart.addAccDist

FinanceChart.addAccDist

Usage

addAccDist(height, color)

Description

Adds an Accumulation/Distribution indicator chart.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the indicator chart in pixels.
color | (Mandatory) | The color of the indicator line.

Return Value

A XYChart object representing the chart created.


FinanceChart.addAroon

FinanceChart.addAroon

Usage

addAroon(height, period, upColor, downColor)

Description

Adds an Aroon Up/Down indicators chart.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the indicator chart in pixels.
period | (Mandatory) | The period to compute the indicators.
upColor | (Mandatory) | The color of the Aroon Up indicator line.
downColor | (Mandatory) | The color of the Aroon Down indicator line.

Return Value

A XYChart object representing the chart created.


FinanceChart.addAroonOsc

FinanceChart.addAroonOsc

Usage

addAroonOsc(height, period, color)

Description

Adds an Aroon Oscillator indicator chart.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the indicator chart in pixels.
period | (Mandatory) | The period to compute the indicator.
color | (Mandatory) | The color of the indicator line.

Return Value

A XYChart object representing the chart created.


FinanceChart.addADX

FinanceChart.addADX

Usage

addADX(height, period, posColor, negColor, color)

Description

Adds an Average Directional Index indicators chart.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the indicator chart in pixels.
period | (Mandatory) | The period to compute the indicator.
posColor | (Mandatory) | The color of the Positive Directional Index line.
negColor | (Mandatory) | The color of the Negative Directional Index line.
color | (Mandatory) | The color of the Average Directional Index line.

Return Value

A XYChart object representing the chart created.


FinanceChart.addATR

FinanceChart.addATR

Usage

addATR(height, period, color1, color2)

Description

Adds an Average True Range indicators chart.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the indicator chart in pixels.
period | (Mandatory) | The period to compute the indicator.
color1 | (Mandatory) | The color of the True Range line.
color2 | (Mandatory) | The color of the Average True Range line.

Return Value

A XYChart object representing the chart created.


FinanceChart.addBollingerWidth

FinanceChart.addBollingerWidth

Usage

addBollingerWidth(height, period, width, color)

Description

Adds a Bollinger Band Width indicator chart.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the indicator chart in pixels.
period | (Mandatory) | The period to compute the indicator.
width | (Mandatory) | The band width to compute the indicator.
color | (Mandatory) | The color of the indicator line.

Return Value

A XYChart object representing the chart created.


FinanceChart.addCCI

FinanceChart.addCCI

Usage

addCCI(height, period, color, range, upColor, downColor)

Description

Adds a Community Channel Index indicator chart.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the indicator chart in pixels.
period | (Mandatory) | The period to compute the indicator.
color | (Mandatory) | The color of the indicator line.
range | (Mandatory) | The distance between the middle line and the upper and lower threshold lines.
upColor | (Mandatory) | The fill color when the indicator exceeds the upper threshold line.
downColor | (Mandatory) | The fill color when the indicator falls below the lower threshold line.

Return Value

A XYChart object representing the chart created.


FinanceChart.addChaikinMoneyFlow

FinanceChart.addChaikinMoneyFlow

Usage

addChaikinMoneyFlow(height, period, color)

Description

Adds a Chaikin Money Flow indicator chart.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the indicator chart in pixels.
period | (Mandatory) | The period to compute the indicator.
color | (Mandatory) | The color of the indicator line.

Return Value

A XYChart object representing the chart created.


FinanceChart.addChaikinOscillator

FinanceChart.addChaikinOscillator

Usage

addChaikinOscillator(height, color)

Description

Adds a Chaikin Oscillator indicator chart.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the indicator chart in pixels.
color | (Mandatory) | The color of the indicator line.

Return Value

A XYChart object representing the chart created.


FinanceChart.addChaikinVolatility

FinanceChart.addChaikinVolatility

Usage

addChaikinVolatility(height, period1, period2, color)

Description

Adds a Chaikin Volatility indicator chart.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the indicator chart in pixels.
period1 | (Mandatory) | The period to smooth the range.
period2 | (Mandatory) | The period to compute the rate of change of the smoothed range.
color | (Mandatory) | The color of the indicator line.

Return Value

A XYChart object representing the chart created.


FinanceChart.addCLV

FinanceChart.addCLV

Usage

addCLV(height, color)

Description

Adds a Close Location Value indicator chart.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the indicator chart in pixels.
color | (Mandatory) | The color of the indicator line.

Return Value

A XYChart object representing the chart created.


FinanceChart.addDPO

FinanceChart.addDPO

Usage

addDPO(height, period, color)

Description

Adds a Detrended Price Oscillator indicator chart.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the indicator chart in pixels.
period | (Mandatory) | The period to compute the indicator.
color | (Mandatory) | The color of the indicator line.

Return Value

A XYChart object representing the chart created.


FinanceChart.addDonchianWidth

FinanceChart.addDonchianWidth

Usage

addDonchianWidth(height, period, color)

Description

Adds a Donchian Channel Width indicator chart.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the indicator chart in pixels.
period | (Mandatory) | The period to compute the indicator.
color | (Mandatory) | The color of the indicator line.

Return Value

A XYChart object representing the chart created.


FinanceChart.addEaseOfMovement

FinanceChart.addEaseOfMovement

Usage

addEaseOfMovement(height, period, color1, color2)

Description

Adds a Ease of Movement indicator chart.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the indicator chart in pixels.
period | (Mandatory) | The period to smooth the indicator.
color1 | (Mandatory) | The color of the indicator line.
color2 | (Mandatory) | The color of the smoothed indicator line.

Return Value

A XYChart object representing the chart created.


FinanceChart.addFastStochastic

FinanceChart.addFastStochastic

Usage

addFastStochastic(height, period1, period2, color1, color2)

Description

Adds a Fast Stochastic indicator chart.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the indicator chart in pixels.
period1 | (Mandatory) | The period to compute the %K line.
period2 | (Mandatory) | The period to compute the %D line.
color1 | (Mandatory) | The color of the %K line.
color2 | (Mandatory) | The color of the %D line.

Return Value

A XYChart object representing the chart created.


FinanceChart.addMACD

FinanceChart.addMACD

Usage

addMACD(height, period1, period2, period3, color, signalColor, divColor)

Description

Adds a MACD indicator chart.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the indicator chart in pixels.
period1 | (Mandatory) | The first moving average period to compute the indicator.
period2 | (Mandatory) | The second moving average period to compute the indicator.
period3 | (Mandatory) | The moving average period of the signal line.
color | (Mandatory) | The color of the indicator line.
signalColor | (Mandatory) | The color of the signal line.
divColor | (Mandatory) | The color of the divergent bars.

Return Value

A XYChart object representing the chart created.


FinanceChart.addMassIndex

FinanceChart.addMassIndex

Usage

addMassIndex(height, color, upColor, downColor)

Description

Adds a Mass Index indicator chart.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the indicator chart in pixels.
color | (Mandatory) | The color of the indicator line.
upColor | (Mandatory) | The fill color when the indicator exceeds the upper threshold line.
downColor | (Mandatory) | The fill color when the indicator falls below the lower threshold line.

Return Value

A XYChart object representing the chart created.


FinanceChart.addMFI

FinanceChart.addMFI

Usage

addMFI(height, period, color, range, upColor, downColor)

Description

Adds a Money Flow Index indicator chart.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the indicator chart in pixels.
period | (Mandatory) | The period to compute the indicator.
color | (Mandatory) | The color of the indicator line.
range | (Mandatory) | The distance between the middle line and the upper and lower threshold lines.
upColor | (Mandatory) | The fill color when the indicator exceeds the upper threshold line.
downColor | (Mandatory) | The fill color when the indicator falls below the lower threshold line.

Return Value

A XYChart object representing the chart created.


FinanceChart.addMomentum

FinanceChart.addMomentum

Usage

addMomentum(height, period, color)

Description

Adds a Momentum indicator chart.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the indicator chart in pixels.
period | (Mandatory) | The period to compute the indicator.
color | (Mandatory) | The color of the indicator line.

Return Value

A XYChart object representing the chart created.


FinanceChart.addNVI

FinanceChart.addNVI

Usage

addNVI(height, period, color, signalColor)

Description

Adds a Negative Volume Index indicator chart.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the indicator chart in pixels.
period | (Mandatory) | The period to compute the signal line.
color | (Mandatory) | The color of the indicator line.
signalColor | (Mandatory) | The color of the signal line.

Return Value

A XYChart object representing the chart created.


FinanceChart.addOBV

FinanceChart.addOBV

Usage

addOBV(height, color)

Description

Adds an On Balance Volume indicator chart.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the indicator chart in pixels.
color | (Mandatory) | The color of the indicator line.

Return Value

A XYChart object representing the chart created.


FinanceChart.addPerformance

FinanceChart.addPerformance

Usage

addPerformance(height, color)

Description

Adds a Performance indicator chart.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the indicator chart in pixels.
color | (Mandatory) | The color of the indicator line.

Return Value

A XYChart object representing the chart created.


FinanceChart.addPPO

FinanceChart.addPPO

Usage

addPPO(height, period1, period2, period3, color, signalColor, divColor)

Description

Adds a Percentage Price Oscillator indicator chart.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the indicator chart in pixels.
period1 | (Mandatory) | The first moving average period to compute the indicator.
period2 | (Mandatory) | The second moving average period to compute the indicator.
period3 | (Mandatory) | The moving average period of the signal line.
color | (Mandatory) | The color of the indicator line.
signalColor | (Mandatory) | The color of the signal line.
divColor | (Mandatory) | The color of the divergent bars.

Return Value

A XYChart object representing the chart created.


FinanceChart.addPVI

FinanceChart.addPVI

Usage

addPVI(height, period, color, signalColor)

Description

Adds a Positive Volume Index indicator chart.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the indicator chart in pixels.
period | (Mandatory) | The period to compute the signal line.
color | (Mandatory) | The color of the indicator line.
signalColor | (Mandatory) | The color of the signal line.

Return Value

A XYChart object representing the chart created.


FinanceChart.addPVO

FinanceChart.addPVO

Usage

addPVO(height, period1, period2, period3, color, signalColor, divColor)

Description

Adds a Percentage Volume Oscillator indicator chart.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the indicator chart in pixels.
period1 | (Mandatory) | The first moving average period to compute the indicator.
period2 | (Mandatory) | The second moving average period to compute the indicator.
period3 | (Mandatory) | The moving average period of the signal line.
color | (Mandatory) | The color of the indicator line.
signalColor | (Mandatory) | The color of the signal line.
divColor | (Mandatory) | The color of the divergent bars.

Return Value

A XYChart object representing the chart created.


FinanceChart.addPVT

FinanceChart.addPVT

Usage

addPVT(height, color)

Description

Adds a Price Volume Trend indicator chart.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the indicator chart in pixels.
color | (Mandatory) | The color of the indicator line.

Return Value

A XYChart object representing the chart created.


FinanceChart.addROC

FinanceChart.addROC

Usage

addROC(height, period, color)

Description

Adds a Rate of Change indicator chart.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the indicator chart in pixels.
period | (Mandatory) | The period to compute the indicator.
color | (Mandatory) | The color of the indicator line.

Return Value

A XYChart object representing the chart created.


FinanceChart.addRSI

FinanceChart.addRSI

Usage

addRSI(height, period, color, range, upColor, downColor)

Description

Adds a Relative Strength Index indicator chart.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the indicator chart in pixels.
period | (Mandatory) | The period to compute the indicator.
color | (Mandatory) | The color of the indicator line.
range | (Mandatory) | The distance between the middle line and the upper and lower threshold lines.
upColor | (Mandatory) | The fill color when the indicator exceeds the upper threshold line.
downColor | (Mandatory) | The fill color when the indicator falls below the lower threshold line.

Return Value

A XYChart object representing the chart created.


FinanceChart.addSlowStochastic

FinanceChart.addSlowStochastic

Usage

addSlowStochastic(height, period1, period2, color1, color2)

Description

Adds a Slow Stochastic indicator chart.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the indicator chart in pixels.
period1 | (Mandatory) | The period to compute the %K line.
period2 | (Mandatory) | The period to compute the %D line.
color1 | (Mandatory) | The color of the %K line.
color2 | (Mandatory) | The color of the %D line.

Return Value

A XYChart object representing the chart created.


FinanceChart.addStdDev

FinanceChart.addStdDev

Usage

addStdDev(height, period, color)

Description

Adds a Moving Standard Deviation indicator chart.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the indicator chart in pixels.
period | (Mandatory) | The period to compute the indicator.
color | (Mandatory) | The color of the indicator line.

Return Value

A XYChart object representing the chart created.


FinanceChart.addStochRSI

FinanceChart.addStochRSI

Usage

addStochRSI(height, period, color, range, upColor, downColor)

Description

Adds a Stochastic RSI indicator chart.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the indicator chart in pixels.
period | (Mandatory) | The period to compute the indicator.
color | (Mandatory) | The color of the indicator line.
range | (Mandatory) | The distance between the middle line and the upper and lower threshold lines.
upColor | (Mandatory) | The fill color when the indicator exceeds the upper threshold line.
downColor | (Mandatory) | The fill color when the indicator falls below the lower threshold line.

Return Value

A XYChart object representing the chart created.


FinanceChart.addTRIX

FinanceChart.addTRIX

Usage

addTRIX(height, period, color)

Description

Adds a TRIX indicator chart.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the indicator chart in pixels.
period | (Mandatory) | The period to compute the indicator.
color | (Mandatory) | The color of the indicator line.

Return Value

A XYChart object representing the chart created.


FinanceChart.addUltimateOscillator

FinanceChart.addUltimateOscillator

Usage

addUltimateOscillator(height, period1, period2, period3, color, range, upColor, downColor)

Description

Adds an Ultimate Oscillator indicator chart.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the indicator chart in pixels.
period1 | (Mandatory) | The first moving average period to compute the indicator.
period2 | (Mandatory) | The second moving average period to compute the indicator.
period3 | (Mandatory) | The third moving average period to compute the indicator.
color | (Mandatory) | The color of the indicator line.
range | (Mandatory) | The distance between the middle line and the upper and lower threshold lines.
upColor | (Mandatory) | The fill color when the indicator exceeds the upper threshold line.
downColor | (Mandatory) | The fill color when the indicator falls below the lower threshold line.

Return Value

A XYChart object representing the chart created.


FinanceChart.addVolIndicator

FinanceChart.addVolIndicator

Usage

addVolIndicator(height, upColor, downColor, flatColor)

Description

Adds a Volume indicator chart.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the indicator chart in pixels.
upColor | (Mandatory) | The color to used on an 'up' day. An 'up' day is a day where the closing price is higher than that of the previous day.
downColor | (Mandatory) | The color to used on a 'down' day. A 'down' day is a day where the closing price is lower than that of the previous day.
flatColor | (Mandatory) | The color to used on a 'flat' day. A 'flat' day is a day where the closing price is the same as that of the previous day.

Return Value

A XYChart object representing the chart created.


FinanceChart.addWilliamR

FinanceChart.addWilliamR

Usage

addWilliamR(height, period, color, range, upColor, downColor)

Description

Adds a William %R indicator chart.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the indicator chart in pixels.
period | (Mandatory) | The period to compute the indicator.
color | (Mandatory) | The color of the indicator line.
range | (Mandatory) | The distance between the middle line and the upper and lower threshold lines.
upColor | (Mandatory) | The fill color when the indicator exceeds the upper threshold line.
downColor | (Mandatory) | The fill color when the indicator falls below the lower threshold line.

Return Value

A XYChart object representing the chart created.


DrawArea

DrawArea

The DrawArea class represents drawing surfaces, with methods for performing graphics primitives (such as drawing lines, shapes and texts) and the surfaces.

All ChartDirector chart objects contains an internal DrawArea object for drawing the charts. This DrawArea object is accessible via BaseChart.getDrawArea or BaseChart.makeChart3. This allows developers to apply custom graphics operations on the charts.

ChartDirector also supports creating standalone DrawArea objects by calling the DrawArea.DrawArea constructor. One common application is to use ChartDirector as a general purpose graphics library (e.g. adding text annotations to existing images, creating GIF buttons on the fly, etc).

Method | Inherited | Description
DrawArea | (Self) | Creates a DrawArea object.
setSize | (Self) | Sets the size and background color of the drawing surface.
resize | (Self) | Resize the drawing surface.
getWidth | (Self) | Gets the width of the drawing surface.
getHeight | (Self) | Gets the height of the drawing surface.
setClipRect | (Self) | Sets the clip rectangle.
setBgColor | (Self) | Sets the background color of the image.
move | (Self) | Moves the drawing surface.
rotate | (Self) | Rotate the drawing surface.
hFlip | (Self) | Flip the drawing surface along the central horizontal line.
vFlip | (Self) | Flip the drawing surface along the central vertical line.
clone | (Self) | Copy the current DrawArea object to another DrawArea object, with optional resizing.
pixel | (Self) | Draw a pixel.
getPixel | (Self) | Gets the color of a pixel.
line | (Self) | Draw a straight line.
hline | (Self) | Draws a horizontal line.
vline | (Self) | Draws a vertical line.
arc | (Self) | Draws a circular or elliptical arc.
rect | (Self) | Draws a rectangle.
polygon | (Self) | Draws a polygon.
surface | (Self) | Draws a parallelogram.
sector | (Self) | Draws a circular or elliptical sector.
cylinder | (Self) | Draws a cylinder surface as the area spanned by moving an arc.
circle | (Self) | Draws a circle or an ellipse.
fill | (Self) | Flood fill a region using the specified color.
fill2 | (Self) | Fill a region using the specified color, where the region is bounded by a given border color.
text | (Self) | Draws text. This method is a simplified version of the DrawArea.text2 method.
text2 | (Self) | Draws text.
text3 | (Self) | Creates a TTFText object representing a text block. This method is a simplified version of the DrawArea.text4 method.
text4 | (Self) | Creates a TTFText object representing a text block.
setDefaultFonts | (Self) | Sets the defaults for normal, bold, italic and bold-italic fonts.
setFontTable | (Self) | Sets an entry in the font table to the specified font name.
merge | (Self) | Copy another DrawArea to the current DrawArea.
tile | (Self) | Copy another DrawArea to the current DrawArea as a wallpaper.
setSearchPath | (Self) | Sets the search path for loading image files.
load | (Self) | Load an image file into the current DrawArea.
loadPNG | (Self) | Load a PNG image into the current DrawArea.
loadGIF | (Self) | Load a GIF image into the current DrawArea.
loadJPG | (Self) | Load a JPG image into the current DrawArea.
loadWMP | (Self) | Load a WAP bitmap image into the current DrawArea.
rAffineTransform | (Self) | Perform reverse affine transformation on the drawing surface.
affineTransform | (Self) | Perform affine transformation on the drawing surface.
sphereTransform | (Self) | Wraps the drawing surface onto a sphere or ellipsoid.
hCylinderTransform | (Self) | Wraps the drawing surface onto a horizontal cylinder.
vCylinderTransform | (Self) | Wraps the drawing surface onto a vertical cylinder.
hTriangleTransform | (Self) | Wraps the drawing surface onto a horizontal triangle pointing leftwards.
vTriangleTransform | (Self) | Wraps the drawing surface onto a vertical triangle pointing upwards.
shearTransform | (Self) | Shear the drawing surface.
waveTransform | (Self) | Moves the pixels on the drawing surface according to a sinusoidal function to achieve a wave effect.
out | (Self) | Writes the DrawArea to an image file.
outPNG | (Self) | Writes the DrawArea to a PNG image file.
outPNG2 | (Self) | Writes the DrawArea as a PNG image to memory.
outGIF | (Self) | Writes the DrawArea to a GIF image file.
outGIF2 | (Self) | Writes the DrawArea as a GIF image to memory.
outJPG | (Self) | Writes the DrawArea to a JPEG image file.
outJPG2 | (Self) | Writes the DrawArea as a JPEG image to memory.
outBMP | (Self) | Writes the DrawArea to a BMP image file.
outBMP2 | (Self) | Writes the DrawArea as a BMP image to memory.
outWMP | (Self) | Writes the DrawArea to a WAP bitmap image file.
outWMP2 | (Self) | Writes the DrawArea as a WAP bitmap image to memory.
setPaletteMode | (Self) | Sets the palette mode to use when writing the image in PNG format.
setDitherMethod | (Self) | Sets the dithering method in case dithering is necessary.
setTransparentColor | (Self) | Specifies a certain color to mean transparent when creating the image output, or to include alpha transparency channel in the output.
setAntiAlias | (Self) | Controls whether anti-alias is used when drawing lines, shapes and text.
setInterlace | (Self) | Sets the interlace mode when creating the image.
setColorTable | (Self) | Change the colors in the palette starting with the specified offset position.
getARGBColor | (Self) | Obtain the ARGB color given a palette color.
halfColor | (Self) | Creates a color that is half the intensity of the given color.
dashLineColor | (Self) | Creates a dash line color.
patternColor | (Self) | Creates a pattern color using an array of colors as the bitmap pattern.
patternColor2 | (Self) | Creates a pattern color by loading the pattern from an image file.
linearGradientColor | (Self) | Creates a two-point linear gradient color.
linearGradientColor2 | (Self) | Creates a multi-point linear gradient color.
radialGradientColor | (Self) | Creates a two-point radial gradient color.
radialGradientColor2 | (Self) | Creates a multi-point radial gradient color.
gradientColor | (Self) | Creates a two-point linear gradient color.
gradientColor2 | (Self) | Creates a multi-point linear gradient color.
reduceColors | (Self) | Reduces the number of colors in the image.


DrawArea.DrawArea

DrawArea.DrawArea

Usage

DrawArea()

Description

Creates a DrawArea object.

Note: In the ColdFusion edition of ChartDirector, the DrawArea constructor is implemented as a method of the ChartDirector.CFChart object called ChartDirector.CFChart.DrawArea.

Arguments

None

Return Value

The DrawArea object created.


DrawArea.setSize

DrawArea.setSize

Usage

setSize(width, height [, bgColor ])

Description

Sets the size and background color of the drawing surface.

Arguments

Argument | Default | Description
width | (Mandatory) | The width of the drawing surface in pixels.
height | (Mandatory) | The height of the drawing surface in pixels.
bgColor | FFFFFF | The background color of the drawing surface.

Return Value

None


DrawArea.resize

DrawArea.resize

Usage

resize(newWidth, newHeight [, filter [, blur ]])

Description

Resize the drawing surface.

Arguments

Argument | Default | Description
newWidth | (Mandatory) | The new width of the drawing surface in pixels.
newHeight | (Mandatory) | The new height of the drawing surface in pixels.
filter | LinearFilter | The filter to use for re-sampling.
blur | 1 | The blur factor to use for re-sampling.

Return Value

None


DrawArea.getWidth

DrawArea.getWidth

Usage

getWidth()

Description

Gets the width of the drawing surface.

Arguments

None

Return Value

The width of the drawing surface in pixels.


DrawArea.getHeight

DrawArea.getHeight

Usage

getHeight()

Description

Gets the height of the drawing surface.

Arguments

None

Return Value

The height of the drawing surface in pixels.


DrawArea.setClipRect

DrawArea.setClipRect

Usage

setClipRect(left, top, right, bottom)

Description

Sets the clip rectangle.

When performing graphics operation, only regions inside the clip rectangle will be affected. Regions outside will be unaffected.

Arguments

Argument | Default | Description
left | (Mandatory) | The x coordinate of the left side of the clip rectangle.
top | (Mandatory) | The y coordinate of the top side of the clip rectangle.
right | (Mandatory) | The x coordinate of the right side of the clip rectangle.
bottom | (Mandatory) | The y coordinate of the bottom side of the clip rectangle.

Return Value

None


DrawArea.setBgColor

DrawArea.setBgColor

Usage

setBgColor(c)

Description

Sets the background color of the image.

Arguments

Argument | Default | Description
c | (Mandatory) | The background color of the image.

Return Value

None


DrawArea.move

DrawArea.move

Usage

move(xOffset, yOffset [, bgColor [, filter [, blur ]]])

Description

Moves the drawing surface.

Arguments

Argument | Default | Description
xOffset | (Mandatory) | The pixel offset to move towards the left.
yOffset | (Mandatory) | The pixel offset to move towards the bottom.
bgColor | FFFFFF | The background color used to fill the space left after moving.
filter | LinearFilter | The filter to use for re-sampling. (Only applies for fractional pixel offsets.)
blur | 1 | The blur factor to use for re-sampling. (Only applies for fractional pixel offsets.)

Return Value

None


DrawArea.rotate

DrawArea.rotate

Usage

rotate(angle [, bgColor [, cx [, cy [, filter [, blur ]]]]])

Description

Rotate the drawing surface.

Arguments

Argument | Default | Description
angle | (Mandatory) | The rotation angle measured clockwise in degrees.
bgColor | FFFFFF | The background color used to fill the space left after rotation.
cx | -1 | The x coordinate of the center of rotation. -1 means rotating about the center of the drawing surface.
cy | -1 | The y coordinate of the center of rotation. -1 means rotating about the center of the drawing surface.
filter | LinearFilter | The filter to use for re-sampling.
blur | 1 | The blur factor to use for re-sampling.

Return Value

None


DrawArea.hFlip

DrawArea.hFlip

Usage

hFlip()

Description

Flip the drawing surface along the central horizontal line.

Arguments

None

Return Value

None


DrawArea.vFlip

DrawArea.vFlip

Usage

vFlip()

Description

Flip the drawing surface along the central vertical line.

Arguments

None

Return Value

None


DrawArea.clone

DrawArea.clone

Usage

clone(d, x, y, align [, newWidth [, newHeight [, filter [, blur ]]]])

Description

Copy the current DrawArea object to another DrawArea object, with optional resizing.

Arguments

Argument | Default | Description
d | (Mandatory) | The destination DrawArea object where the current DrawArea is copied to.
x | (Mandatory) | The x coordinate of a reference point in the destination DrawArea object.
y | (Mandatory) | The y coordinate of a reference point in the destination DrawArea object.
align | (Mandatory) | The alignment of the current DrawArea relative to the reference point. See Alignment Specification for supported alignment types.
newWidth | -1 | The new width to which the current DrawArea will be resized to before copying. The default value -1 means no resizing.
newHeight | -1 | The new height to which the current DrawArea will be resized to before copying. The default value -1 means no resizing.
filter | LinearFilter | The filter to use for re-sampling. (Only applies if there is resizing.)
blur | 1 | The blur factor to use for re-sampling. (Only applies if there is resizing.)

Return Value

None


DrawArea.pixel

DrawArea.pixel

Usage

pixel(x, y, c)

Description

Draw a pixel.

Arguments

Argument | Default | Description
x | (Mandatory) | The x coordinate of the pixel.
y | (Mandatory) | The y coordinate of the pixel.
c | (Mandatory) | The color of the pixel.

Return Value

None


DrawArea.getPixel

DrawArea.getPixel

Usage

getPixel(x, y)

Description

Gets the color of a pixel.

Arguments

Argument | Default | Description
x | (Mandatory) | The x coordinate of the pixel.
y | (Mandatory) | The y coordinate of the pixel.

Return Value

The color of the pixel.


DrawArea.line

DrawArea.line

Usage

line(x1, y1, x2, y2, c [, lineWidth ])

Description

Draw a straight line.

Arguments

Argument | Default | Description
x1 | (Mandatory) | The x coordinate of the first end-point of the line.
y1 | (Mandatory) | The y coordinate of the first end-point of the line.
x2 | (Mandatory) | The x coordinate of the second end-point of the line.
y2 | (Mandatory) | The y coordinate of the second end-point of the line.
c | (Mandatory) | The color of the line.
lineWidth | 1 | The line width (thickness).

Return Value

None


DrawArea.hline

DrawArea.hline

Usage

hline(x1, x2, y, c)

Description

Draws a horizontal line.

Arguments

Argument | Default | Description
x1 | (Mandatory) | The x coordinate of the first end-point of the line.
x2 | (Mandatory) | The x coordinate of the second end-point of the line.
y | (Mandatory) | The y coordinate of the line.
c | (Mandatory) | The color of the line.

Return Value

None


DrawArea.vline

DrawArea.vline

Usage

vline(y1, y2, x, c)

Description

Draws a vertical line.

Arguments

Argument | Default | Description
y1 | (Mandatory) | The y coordinate of the first end-point of the line.
y2 | (Mandatory) | The y coordinate of the second end-point of the line.
x | (Mandatory) | The x coordinate of the line.
c | (Mandatory) | The color of the line.

Return Value

None


DrawArea.arc

DrawArea.arc

Usage

arc(cx, cy, rx, ry, a1, a2, c)

Description

Draws a circular or elliptical arc.

Arguments

Argument | Default | Description
cx | (Mandatory) | The x coordinate of the center of the circle or ellipse.
cy | (Mandatory) | The y coordinate of the center of the circle or ellipse.
rx | (Mandatory) | The horizontal radius of the circle or ellipse.
ry | (Mandatory) | The vertical radius of the circle or ellipse.
a1 | (Mandatory) | The start angle of the arc in degrees. The angle is measured clockwise, with 0 degree being the upward pointing direction.
a2 | (Mandatory) | The end angle of the arc in degrees. The angle is measured clockwise, with 0 degree being the upward pointing direction.
c | (Mandatory) | The color of the arc.

Return Value

None


DrawArea.rect

DrawArea.rect

Usage

rect(x1, y1, x2, y2, edgeColor, fillColor [, raisedEffect ])

Description

Draws a rectangle.

Arguments

Argument | Default | Description
x1 | (Mandatory) | The x coordinate of one corner of the rectangle.
y1 | (Mandatory) | The y coordinate of one corner of the rectangle.
x2 | (Mandatory) | The x coordinate of the opposite corner of the rectangle.
y2 | (Mandatory) | The y coordinate of the opposite corner of the rectangle.
edgeColor | (Mandatory) | The border color. To disable border, set the edgeColor the same as the fillColor.
fillColor | (Mandatory) | The fill color. To disable filling, set the fillColor to Transparent.
raisedEffect | 0 | The 3D border width. For positive values, the border will appear raised. For negative values, the border will appear depressed. A zero value means the border will appear flat. This argument is also used to support ChartDirector.CFChart.glassEffect and ChartDirector.CFChart.softLighting effects.

Return Value

None


DrawArea.polygon

DrawArea.polygon

Usage

polygon(x, y, edgeColor, fillColor)

Description

Draws a polygon.

Arguments

Argument | Default | Description
x | (Mandatory) | An array of numbers representing the x coordinates of the vertices of a polygon.
y | (Mandatory) | An array of numbers representing the y coordinates of the vertices of a polygon.
edgeColor | (Mandatory) | The border color. To disable border, set the edgeColor the same as the fillColor.
fillColor | (Mandatory) | The fill color. To disable filling, set the fillColor to Transparent.

Return Value

None


DrawArea.surface

DrawArea.surface

Usage

surface(x1, y1, x2, y2, depthX, depthY, edgeColor, fillColor)

Description

Draws a parallelogram.

Arguments

Argument | Default | Description
x1 | (Mandatory) | The x coordinate of the first end-point of one line of the parallelogram.
y1 | (Mandatory) | The y coordinate of the first end-point of one line of the parallelogram.
x2 | (Mandatory) | The x coordinate of the second end-point of one line of the parallelogram.
y2 | (Mandatory) | The y coordinate of the second end-point of one line of the parallelogram.
depthX | (Mandatory) | The x displacement of the line segment that is parallel to the line segment above.
depthY | (Mandatory) | The y displacement of the line segment that is parallel to the line segment above.
edgeColor | (Mandatory) | The border color. To disable border, set the edgeColor the same as the fillColor.
fillColor | (Mandatory) | The fill color. To disable filling, set the fillColor to Transparent.

Return Value

None


DrawArea.sector

DrawArea.sector

Usage

sector(cx, cy, rx, ry, a1, a2, edgeColor, fillColor)

Description

Draws a circular or elliptical sector.

Arguments

Argument | Default | Description
cx | (Mandatory) | The x coordinate of the center of the circle or ellipse.
cy | (Mandatory) | The y coordinate of the center of the circle or ellipse.
rx | (Mandatory) | The horizontal radius of the circle or ellipse.
ry | (Mandatory) | The vertical radius of the circle or ellipse.
a1 | (Mandatory) | The start angle of the sector in degrees. The angle is measured clockwise, with 0 degree being the upward pointing direction.
a2 | (Mandatory) | The end angle of the sector in degrees. The angle is measured clockwise, with 0 degree being the upward pointing direction.
edgeColor | (Mandatory) | The border color. To disable border, set the edgeColor the same as the fillColor.
fillColor | (Mandatory) | The fill color. To disable filling, set the fillColor to Transparent.

Return Value

None


DrawArea.cylinder

DrawArea.cylinder

Usage

cylinder(cx, cy, rx, ry, a1, a2, depthX, depthY, edgeColor, fillColor)

Description

Draws a cylinder surface as the area spanned by moving an arc.

Arguments

Argument | Default | Description
cx | (Mandatory) | The x coordinate of the center of the circle or ellipse for the arc.
cy | (Mandatory) | The y coordinate of the center of the circle or ellipse for the arc.
rx | (Mandatory) | The horizontal radius of the circle or ellipse.
ry | (Mandatory) | The vertical radius of the circle or ellipse.
a1 | (Mandatory) | The start angle of the arc. The angle is measured clockwise, with 0 degree being the upward pointing direction.
a2 | (Mandatory) | The end angle of the arc. The angle is measured clockwise, with 0 degree being the upward pointing direction.
depthX | (Mandatory) | The x displacement representing the motion of the arc to span the cylinder.
depthY | (Mandatory) | The y displacement representing the motion of the arc to span the cylinder.
edgeColor | (Mandatory) | The border color. To disable border, set the edgeColor the same as the fillColor.
fillColor | (Mandatory) | The fill color. To disable filling, set the fillColor to Transparent.

Return Value

None


DrawArea.circle

DrawArea.circle

Usage

circle(cx, cy, rx, ry, edgeColor, fillColor)

Description

Draws a circle or an ellipse.

Arguments

Argument | Default | Description
cx | (Mandatory) | The x coordinate of the center of the circle or ellipse.
cy | (Mandatory) | The y coordinate of the center of the circle or ellipse.
rx | (Mandatory) | The horizontal radius of the circle or ellipse.
ry | (Mandatory) | The vertical radius of the circle or ellipse.
edgeColor | (Mandatory) | The border color. To disable border, set the edgeColor the same as the fillColor.
fillColor | (Mandatory) | The fill color. To disable filling, set the fillColor to Transparent.

Return Value

None


DrawArea.fill

DrawArea.fill

Usage

fill(x, y, color)

Description

Flood fill a region using the specified color.

Arguments

Argument | Default | Description
x | (Mandatory) | The x coordinate one pixel inside the region to be filled.
y | (Mandatory) | The y coordinate one pixel inside the region to be filled.
color | (Mandatory) | The color used to fill the region.

Return Value

None


DrawArea.fill2

DrawArea.fill2

Usage

fill2(x, y, color, borderColor)

Description

Fill a region using the specified color, where the region is bounded by a given border color.

Arguments

Argument | Default | Description
x | (Mandatory) | The x coordinate one pixel inside the region to be filled.
y | (Mandatory) | The y coordinate one pixel inside the region to be filled.
color | (Mandatory) | The color used to fill the region.
borderColor | (Mandatory) | The color of the border that bounds the region.

Return Value

None


DrawArea.text

DrawArea.text

Usage

text(str, font, fontSize, x, y, color)

Description

Draws text. This method is a simplified version of the DrawArea.text2 method.

Arguments

Argument | Default | Description
str | (Mandatory) | A string representing the text to be drawn. See ChartDirector Mark Up Language on how to embed special tags in the text for sophisticated formatting.
font | (Mandatory) | The font name. See Font Specification for details on various font attributes.
fontSize | (Mandatory) | The font size in points.
x | (Mandatory) | The x coordinate of the top-left corner of the text.
y | (Mandatory) | The y coordinate of the top-left corner of the text.
color | (Mandatory) | The color of the text.

Return Value

None


DrawArea.text2

DrawArea.text2

Usage

text2(str, font, fontIndex, fontHeight, fontWidth, angle, vertical, x, y, color [, alignment ])

Description

Draws text.

Arguments

Argument | Default | Description
str | (Mandatory) | A string representing the text to be drawn. See ChartDirector Mark Up Language on how to embed special tags in the text for sophisticated formatting.
font | (Mandatory) | The font name. See Font Specification for details on various font attributes.
fontIndex | (Mandatory) | The font index in case the font name refers to a font collection. An index of 0 means the first font.
fontHeight | (Mandatory) | The font height in points.
fontWidth | (Mandatory) | The font width in points.
angle | (Mandatory) | The rotation angle of the text. The angle is measured in degrees in clockwise direction.
vertical | (Mandatory) | A true (non-zero) value means the text is layout vertically (from top to bottom). A false (zero) value means the is layout horizontally (from left to right).
x | (Mandatory) | The x coordinate of a reference point to align the text.
y | (Mandatory) | The y coordinate of a reference point to align the text.
color | (Mandatory) | The color of the text.
alignment | TopLeft | The position of the text relative to the reference point. See Alignment Specification for supported alignment types.

Return Value

None


DrawArea.text3

DrawArea.text3

Usage

text3(str, font, fontSize)

Description

Creates a TTFText object representing a text block. This method is a simplified version of the DrawArea.text4 method.

The TTFText object contains methods to measure and draw the text. This method is useful if the size of the text is needed before deciding where the draw it.

Arguments

Argument | Default | Description
str | (Mandatory) | A string representing the text to be drawn. See ChartDirector Mark Up Language on how to embed special tags in the text for sophisticated formatting.
font | (Mandatory) | The font name. See Font Specification for details on various font attributes.
fontSize | (Mandatory) | The font size in points.

Return Value

The TTFText object created.


DrawArea.text4

DrawArea.text4

Usage

text4(text, font, fontIndex, fontHeight, fontWidth, angle, vertical)

Description

Creates a TTFText object representing a text block.

The TTFText object contains methods to measure and draw the text. This method is useful if the size of the text is needed before deciding where the draw it.

Arguments

Argument | Default | Description
text | (Mandatory) | A string representing the text to be drawn. See ChartDirector Mark Up Language on how to embed special tags in the text for sophisticated formatting.
font | (Mandatory) | The font name. See Font Specification for details on various font attributes.
fontIndex | (Mandatory) | The font index in case the font name refers to a font collection. An index of 0 means the first font.
fontHeight | (Mandatory) | The font height in points.
fontWidth | (Mandatory) | The font width in points.
angle | (Mandatory) | The rotation angle of the text.
vertical | (Mandatory) | A true (non-zero) value means the text is layout vertically (from top to bottom). A false (zero) value means the is layout horizontally (from left to right).

Return Value

The TTFText object created.


DrawArea.setDefaultFonts

DrawArea.setDefaultFonts

Usage

setDefaultFonts(normal [, bold [, italic [, boldItalic ]]])

Description

Sets the defaults for normal, bold, italic and bold-italic fonts.

See Font Specification for details on various font attributes.

Arguments

Argument | Default | Description
normal | (Mandatory) | The default normal font. This is the same as the first font in the font table.
bold | "" | The default bold font. This is the same as the second font in the font table. An empty string means the default is unchanged.
italic | "" | The default italic font. This is the same as the third font in the font table. An empty string means the default is unchanged.
boldItalic | "" | The default bold-italic font. This is the same as the fourth font in the font table. An empty string means the default is unchanged.

Return Value

None


DrawArea.setFontTable

DrawArea.setFontTable

Usage

setFontTable(index, font)

Description

Sets an entry in the font table to the specified font name.

The first 4 fonts in the font table have special significance. They are the defaults for normal, bold, italic and bold-italic fonts.

See Font Specification for details on various font attributes.

Arguments

Argument | Default | Description
index | (Mandatory) | An index to the font table, starting from 0.
font | (Mandatory) | The font name to be put into the font table.

Return Value

None


DrawArea.merge

DrawArea.merge

Usage

merge(d, x, y, align, transparency)

Description

Copy another DrawArea to the current DrawArea.

Arguments

Argument | Default | Description
d | (Mandatory) | A DrawArea object representing the source.
x | (Mandatory) | The x coordinate of a reference point in the current DrawArea.
y | (Mandatory) | The y coordinate of a reference point in the current DrawArea.
align | (Mandatory) | The alignment of the source DrawArea relative to the reference point. See Alignment Specification for supported alignment types.
transparency | (Mandatory) | Specify the transparency level when copying the other DrawArea to the current DrawArea. A value of 0 means non-transparent. A value of 255 means totally transparent.

Return Value

None


DrawArea.tile

DrawArea.tile

Usage

tile(d, transparency)

Description

Copy another DrawArea to the current DrawArea as a wallpaper.

The wallpaper image will be tiled repeatedly on the current DrawArea until the entire DrawArea is covered.

Arguments

Argument | Default | Description
d | (Mandatory) | A DrawArea object representing the source.
transparency | (Mandatory) | Specify the transparency level when copying the other DrawArea to the current DrawArea. A value of 0 means non-transparent. A value of 255 means totally transparent.

Return Value

None


DrawArea.setSearchPath

DrawArea.setSearchPath

Usage

setSearchPath(pageContext [, path ])

Description

Sets the search path for loading image files.

Several ChartDirector operations involve loading image files. Examples are wallpapers (BaseChart.setWallpaper), background images (BaseChart.setBgImage and PlotArea.setBackground2), user-defined symbols (DataSet.setDataSymbol2) or for embedding images in text using ChartDirector Mark Up Language.

By default, ChartDirector will search for the image files by interpreting the path names as file system path names. For example, the root "/" is interpreted as the root of the file system, not the root of the web document directory or the root of the servlet context. Relative paths are interpreted as relative to the "current working directory" (note that the "current working directory" is determined by the operating system and is in general different from the current URL directory.) This allows you to use image files outside of the web document directory.

In addition, ChartDirector will search for the image files by interpreting the path names as Java resource paths and search them in the Java class paths. This allows one to use images embedded in JAR files as resources.

The setSearchPath method allows you to specify using the current page context for searching the images. In this case, the root "/" is interpreted as the root of the servlet context. If a relative path is used, it is interpreted as relative to the current URL directory.

The setSearchPath allows you to optionally specify one or more directories to search for the image files. Directories should be separated with the path separator of the operating system (";" for Windows and ":" for Linux/UNIX).

Arguments

Argument | Default | Description
pageContext | (Mandatory) | The PageContext object representing the current web page. This is typically obtained by using the ColdFusion "GetPageContext" function.
path | "" | A list of directories to search for the images, separated with the path separator of the operating system (";" for Windows and ":" for Linux/UNIX). If this argument is not provided, then the current URL directory is used.

Return Value

None


DrawArea.load

DrawArea.load

Usage

load(filename)

Description

Load an image file into the current DrawArea.

This method will overwrite the current DrawArea. The image type is determined based on file extension, which must be png, jpg/jpeg, gif or wbmp/wmp.

Arguments

Argument | Default | Description
filename | (Mandatory) | The filename of the image to be loaded.

Return Value

A true (non-zero) value indicates no error. A false (zero) value indicates the operation is unsuccessful.


DrawArea.loadPNG

DrawArea.loadPNG

Usage

loadPNG(filename)

Description

Load a PNG image into the current DrawArea.

This method will overwrite the current DrawArea.

Arguments

Argument | Default | Description
filename | (Mandatory) | The filename of the image to be loaded.

Return Value

A true (non-zero) value indicates no error. A false (zero) value indicates the operation is unsuccessful.


DrawArea.loadGIF

DrawArea.loadGIF

Usage

loadGIF(filename)

Description

Load a GIF image into the current DrawArea.

This method will overwrite the current DrawArea.

Arguments

Argument | Default | Description
filename | (Mandatory) | The filename of the image to be loaded.

Return Value

A true (non-zero) value indicates no error. A false (zero) value indicates the operation is unsuccessful.


DrawArea.loadJPG

DrawArea.loadJPG

Usage

loadJPG(filename)

Description

Load a JPG image into the current DrawArea.

This method will overwrite the current DrawArea.

Arguments

Argument | Default | Description
filename | (Mandatory) | The filename of the image to be loaded.

Return Value

A true (non-zero) value indicates no error. A false (zero) value indicates the operation is unsuccessful.


DrawArea.loadWMP

DrawArea.loadWMP

Usage

loadWMP(filename)

Description

Load a WAP bitmap image into the current DrawArea.

This method will overwrite the current DrawArea.

Arguments

Argument | Default | Description
filename | (Mandatory) | The filename of the image to be loaded.

Return Value

A true (non-zero) value indicates no error. A false (zero) value indicates the operation is unsuccessful.


DrawArea.rAffineTransform

DrawArea.rAffineTransform

Usage

rAffineTransform(a, b, c, d, e, f [, bgColor [, filter [, blur ]]])

Description

Perform reverse affine transformation on the drawing surface.

A reverse affine transformation is an operation where every pixel is copied from another pixel according to the formula.

xSrc = a * xDest + b * yDest + c
ySrc = d * xDest + e * yDest + f

where (xDest, yDest) is a destination pixel, and (xSrc, ySrc) is where it should come from.

Many graphics operation, such as translation, rotation, and resizing, can be considered as a special case of reverse affine transformation.

Arguments

Argument | Default | Description
a | (Mandatory) | The parameter 'a' in the coordinate transformation formula "xSrc = a * xDest + b * yDest + c".
b | (Mandatory) | The parameter 'b' in the coordinate transformation formula "xSrc = a * xDest + b * yDest + c".
c | (Mandatory) | The parameter 'c' in the coordinate transformation formula "xSrc = a * xDest + b * yDest + c".
d | (Mandatory) | The parameter 'd' in the coordinate transformation formula "ySrc = d * xDest + e * yDest + f".
e | (Mandatory) | The parameter 'e' in the coordinate transformation formula "ySrc = d * xDest + e * yDest + f".
f | (Mandatory) | The parameter 'f' in the coordinate transformation formula "ySrc = d * xDest + e * yDest + f".
bgColor | FFFFFF | The background color used to fill destination pixels that are not mapped to any source pixels.
filter | LinearFilter | The filter to use for re-sampling.
blur | 1 | The blur factor to use for re-sampling.

Return Value

None


DrawArea.affineTransform

DrawArea.affineTransform

Usage

affineTransform(a, b, c, d, e, f [, bgColor [, filter [, blur ]]])

Description

Perform affine transformation on the drawing surface.

An affine transformation is an operation where every pixel is copied to another pixel according to the formula.

xDest = a * xSrc + b * ySrc + c
yDest = d * xSrc + e * ySrc + f

where (xSrc, ySrc) is a source pixel, and (xDest, yDest) is where it should go to.

Many graphics operation, such as translation, rotation, and resizing, can be considered as a special case of affine transformation.

Arguments

Argument | Default | Description
a | (Mandatory) | The parameter 'a' in the coordinate transformation formula "xDest = a * xSrc + b * ySrc + c".
b | (Mandatory) | The parameter 'b' in the coordinate transformation formula "xDest = a * xSrc + b * ySrc + c".
c | (Mandatory) | The parameter 'c' in the coordinate transformation formula "xDest = a * xSrc + b * ySrc + c".
d | (Mandatory) | The parameter 'd' in the coordinate transformation formula "yDest = d * xSrc + e * ySrc + f".
e | (Mandatory) | The parameter 'e' in the coordinate transformation formula "yDest = d * xSrc + e * ySrc + f".
f | (Mandatory) | The parameter 'f' in the coordinate transformation formula "yDest = d * xSrc + e * ySrc + f".
bgColor | FFFFFF | The background color used to fill destination pixels that are not mapped to any source pixels.
filter | LinearFilter | The filter to use for re-sampling.
blur | 1 | The blur factor to use for re-sampling.

Return Value

None


DrawArea.sphereTransform

DrawArea.sphereTransform

Usage

sphereTransform(xDiameter, yDiameter [, bgColor [, filter [, blur ]]])

Description

Wraps the drawing surface onto a sphere or ellipsoid.

Arguments

Argument | Default | Description
xDiameter | (Mandatory) | The horizontal diameter of the sphere or ellipsoid in pixels.
yDiameter | (Mandatory) | The vertical diameter of the sphere or ellipsoid in pixels.
bgColor | FFFFFF | The background color used to fill the space left after transformation.
filter | LinearFilter | The filter to use for re-sampling.
blur | 1 | The blur factor to use for re-sampling.

Return Value

None


DrawArea.hCylinderTransform

DrawArea.hCylinderTransform

Usage

hCylinderTransform(yDiameter [, bgColor [, filter [, blur ]]])

Description

Wraps the drawing surface onto a horizontal cylinder.

Arguments

Argument | Default | Description
yDiameter | (Mandatory) | The diameter of the cylinder in pixels.
bgColor | FFFFFF | The background color used to fill the space left after transformation.
filter | LinearFilter | The filter to use for re-sampling.
blur | 1 | The blur factor to use for re-sampling.

Return Value

None


DrawArea.vCylinderTransform

DrawArea.vCylinderTransform

Usage

vCylinderTransform(xDiameter [, bgColor [, filter [, blur ]]])

Description

Wraps the drawing surface onto a vertical cylinder.

Arguments

Argument | Default | Description
xDiameter | (Mandatory) | The diameter of the cylinder in pixels.
bgColor | FFFFFF | The background color used to fill the space left after transformation.
filter | LinearFilter | The filter to use for re-sampling.
blur | 1 | The blur factor to use for re-sampling.

Return Value

None


DrawArea.hTriangleTransform

DrawArea.hTriangleTransform

Usage

hTriangleTransform([ tWidth [, bgColor [, filter [, blur ]]]])

Description

Wraps the drawing surface onto a horizontal triangle pointing leftwards.

Arguments

Argument | Default | Description
tWidth | -1 | The width of the triangle in pixels.
bgColor | FFFFFF | The background color used to fill the space left after transformation.
filter | LinearFilter | The filter to use for re-sampling.
blur | 1 | The blur factor to use for re-sampling.

Return Value

None


DrawArea.vTriangleTransform

DrawArea.vTriangleTransform

Usage

vTriangleTransform([ tHeight [, bgColor [, filter [, blur ]]]])

Description

Wraps the drawing surface onto a vertical triangle pointing upwards.

Arguments

Argument | Default | Description
tHeight | -1 | The height of the triangle in pixels.
bgColor | FFFFFF | The background color used to fill the space left after transformation.
filter | LinearFilter | The filter to use for re-sampling.
blur | 1 | The blur factor to use for re-sampling.

Return Value

None


DrawArea.shearTransform

DrawArea.shearTransform

Usage

shearTransform(xShear [, yShear [, bgColor [, filter [, blur ]]]])

Description

Shear the drawing surface.

Shearing can be applied along the horizontal direction and/or vertical direction. A rectangle, after shearing, will become a parallelogram.

Arguments

Argument | Default | Description
xShear | (Mandatory) | The number of pixels to shear leftwards.
yShear | 0 | The number of pixels to shear downwards.
bgColor | FFFFFF | The background color used to fill the space left after transformation.
filter | LinearFilter | The filter to use for re-sampling.
blur | 1 | The blur factor to use for re-sampling.

Return Value

None


DrawArea.waveTransform

DrawArea.waveTransform

Usage

waveTransform(period, amplitude [, direction [, startAngle [, longitudinal [, bgColor [, filter [, blur ]]]]]])

Description

Moves the pixels on the drawing surface according to a sinusoidal function to achieve a wave effect.

Arguments

Argument | Default | Description
period | (Mandatory) | The period of the wave in pixels.
amplitude | (Mandatory) | The amplitude of the wave in pixels.
direction | 0 | The propagation direction of the wave. The upward pointing direction is 0 degree, and the angle is measured clockwise.
startAngle | 0 | The initial phase angle of the wave in degrees.
longitudinal | false (zero) | Determine if the wave is transversal or longitudinal. true (non-zero) means transversal. false (zero) means longitudinal.
bgColor | FFFFFF | The background color used to fill the space left after transformation.
filter | LinearFilter | The filter to use for re-sampling.
blur | 1 | The blur factor to use for re-sampling.

Return Value

None


DrawArea.out

DrawArea.out

Usage

out(filename)

Description

Writes the DrawArea to an image file.

The file format is determined based on file extension, which must be png, jpg/jpeg, gif, wbmp/wmp or bmp.

Arguments

Argument | Default | Description
filename | (Mandatory) | The filename of the output image file.

Return Value

A true (non-zero) value indicates no error. A false (zero) value indicates the operation is unsuccessful.


DrawArea.outPNG

DrawArea.outPNG

Usage

outPNG(filename)

Description

Writes the DrawArea to a PNG image file.

Arguments

Argument | Default | Description
filename | (Mandatory) | The filename of the output image file.

Return Value

A true (non-zero) value indicates no error. A false (zero) value indicates the operation is unsuccessful.


DrawArea.outPNG2

DrawArea.outPNG2

Usage

outPNG2()

Description

Writes the DrawArea as a PNG image to memory.

Arguments

None

Return Value

A byte array containing the PNG image.


DrawArea.outGIF

DrawArea.outGIF

Usage

outGIF(filename)

Description

Writes the DrawArea to a GIF image file.

Arguments

Argument | Default | Description
filename | (Mandatory) | The filename of the output image file.

Return Value

A true (non-zero) value indicates no error. A false (zero) value indicates the operation is unsuccessful.


DrawArea.outGIF2

DrawArea.outGIF2

Usage

outGIF2()

Description

Writes the DrawArea as a GIF image to memory.

Arguments

None

Return Value

A byte array containing the GIF image.


DrawArea.outJPG

DrawArea.outJPG

Usage

outJPG(filename [, quality ])

Description

Writes the DrawArea to a JPEG image file.

Arguments

Argument | Default | Description
filename | (Mandatory) | The filename of the output image file.
quality | 80 | The quality of the image.

Return Value

A true (non-zero) value indicates no error. A false (zero) value indicates the operation is unsuccessful.


DrawArea.outJPG2

DrawArea.outJPG2

Usage

outJPG2([ quality ])

Description

Writes the DrawArea as a JPEG image to memory.

Arguments

Argument | Default | Description
quality | 80 | The quality of the image.

Return Value

A byte array containing the JPEG image.


DrawArea.outBMP

DrawArea.outBMP

Usage

outBMP(filename)

Description

Writes the DrawArea to a BMP image file.

Arguments

Argument | Default | Description
filename | (Mandatory) | The filename of the output image file.

Return Value

A true (non-zero) value indicates no error. A false (zero) value indicates the operation is unsuccessful.


DrawArea.outBMP2

DrawArea.outBMP2

Usage

outBMP2()

Description

Writes the DrawArea as a BMP image to memory.

Arguments

None

Return Value

A byte array containing the BMP image.


DrawArea.outWMP

DrawArea.outWMP

Usage

outWMP(filename)

Description

Writes the DrawArea to a WAP bitmap image file.

Arguments

Argument | Default | Description
filename | (Mandatory) | The filename of the output image file.

Return Value

A true (non-zero) value indicates no error. A false (zero) value indicates the operation is unsuccessful.


DrawArea.outWMP2

DrawArea.outWMP2

Usage

outWMP2()

Description

Writes the DrawArea as a WAP bitmap image to memory.

Arguments

None

Return Value

A byte array containing the WAP bitmap image.


DrawArea.setPaletteMode

DrawArea.setPaletteMode

Usage

setPaletteMode(p)

Description

Sets the palette mode to use when writing the image in PNG format.

The PNG format supports both palette based images and true color images. Palette based images can only have 256 colors, but is smaller in size.

The palette mode must be one of the following predefined constants.

Constant | Value | Description
TryPalette | 0 | Use palette mode if the image contains less than 256 colors, otherwise use true color mode. This is the default.
ForcePalette | 1 | Use palette mode. If the image contains more than 256 colors, reduce it to 256 colors using dithering (see DrawArea.setDitherMethod).
NoPalette | 2 | Use true color mode.

Arguments

Argument | Default | Description
p | (Mandatory) | The palette mode for PNG images.

Return Value

None


DrawArea.setDitherMethod

DrawArea.setDitherMethod

Usage

setDitherMethod(m)

Description

Sets the dithering method in case dithering is necessary.

Dithering is a process of reducing the colors of an image. It is required if an image has more colors than can be supported by the image format. For example, a GIF image can only have 256 colors. If the actual image contains more than 256 colors, dithering is needed to reduce the colors to less than 256.

The dithering method must be one of the following predefined constants.

Constant | Value | Description
Quantize | 0 | ChartDirector will first compute an optimal 256-color palette based on colors on the actual image. It then replaces the color of each pixel with the nearest color in the palette. This is the default method and produces the best result in most cases.
OrderedDither | 1 | Use the ordered dithering algorithm with a 4 x 4 matrix, and with the standard web-safe palette. The web-safe palette is a palette compatible with very old browsers (e.g. Netscape 1.x and 2.x browsers) on 256-color displays. Web-safe palette is not an optimal palette. In most cases, this method is not as good as the Quantize method. Use this method only if you have to use the web-safe palette.
ErrorDiffusion | 2 | Similar to OrderedDither but use the Floyd and Steinberg error diffusion algorithm.

Arguments

Argument | Default | Description
m | (Mandatory) | The dithering method to use in case dithering is necessary.

Return Value

None


DrawArea.setTransparentColor

DrawArea.setTransparentColor

Usage

setTransparentColor(c)

Description

Specifies a certain color to mean transparent when creating the image output, or to include alpha transparency channel in the output.

There are two types of transparency:

  • Alpha transparency: In addition to red, green and blue levels, there is a transparency level associated with each pixel, which can range from completely transparent to completely opaque. The data associated with the transparency information is called the alpha channel.

  • Single color transparency: The image itself has no alpha channel, but a certain color is used to mean completely transparent.
For internal drawing, ChartDirector always use alpha transparency. However, when outputting the image as an image file, ChartDirector by default will remove the alpha channel to reduce image size. It is because many image displaying software do not support alpha transparency. For example, the IE browser only supports single color transparency but not alpha transparency.

If you want to use single color transparency in the output, you may specify the transparent color as the argument to the setTransparentColor method. Note that only GIF and PNG can support single color transparency. JPEG, BMP and WBMP cannot support transparency at all.

If you do want to keep the alpha channel in final output, you may pass -1 as the argument to setTransparentColor. Note that the only image format that can support alpha transparency is PNG.

One important thing to note is that the IE browser (and possibly many image displaying software) only supports single color transparency for palette based images with up to 256 colors, but not for true color images. For this reason, if single color transparency is used, ChartDirector will automatically reduce the image to 256 colors if it has more than 256 colors. This may result in lost of image quality, especially if the image contains gradient colors.

Therefore, due to the limitations of the current generations of image displaying software, for highest image quality, sometimes it may be beneficial to not using transparency in image output, but to set the image background color to the same color as the container background.

Arguments

Argument | Default | Description
c | (Mandatory) | The color that is designated as the transparent color. If -1 is used, the full alpha transparency channel will be included in the final output.

Return Value

None


DrawArea.setAntiAlias

DrawArea.setAntiAlias

Usage

setAntiAlias([ shapeAntiAlias [, textAntiAlias ]])

Description

Controls whether anti-alias is used when drawing lines, shapes and text.

For anti-aliasing text, ChartDirector supports the following modes.

Constant | Value | Description
NoAntiAlias | 0 | Disable anti-alias when drawing text
AntiAlias | 1 | Always use anti-alias when drawing text
AutoAntiAlias | 2 | Automatically determine if anti-alias should be used for the text. This is the default. Currently, ChartDirector will anti-alias only large or bold fonts. For small fonts, assuming it is of high quality, anti-alias is unnecessary. It is because high quality fonts are normally designed to be sharp and clear at low resolution. Anti-aliasing will blur the fonts and make them look worse. However, for complicated fonts (e.g. some fonts with oriental characters), or for lower quality fonts (e.g. some freeware fonts), anti-alias may be necessary. In this case, it may be needed to force anti-aliasing of all fonts using AntiAlias mode.

Arguments

Argument | Default | Description
shapeAntiAlias | true (non-zero) | A true (non-zero) value enables anti-alias when drawing lines and shapes. A false (zero) value disables anti-alias when drawing lines and shapes
textAntiAlias | AutoAntiAlias | The text anti-alias mode, which must be one of AutoAntiAlias, AntiAlias or NoAntiAlias.

Return Value

None


DrawArea.setInterlace

DrawArea.setInterlace

Usage

setInterlace(i)

Description

Sets the interlace mode when creating the image.

Note that in many case an interlaced image is less compressible, and may have a large image size. The default is non-interlace.

Note that this method only applies to image formats that support interlacing (GIF and PNG). It is ignored for image formats that does not support interlacing.

Arguments

Argument | Default | Description
i | (Mandatory) | A true (non-zero) value means the image is interlaced. A false (zero) value means the image is non-interlaced.

Return Value

None


DrawArea.setColorTable

DrawArea.setColorTable

Usage

setColorTable(colors, offset)

Description

Change the colors in the palette starting with the specified offset position.

See Color Specification on how colors are represented in ChartDirector.

Arguments

Argument | Default | Description
colors | (Mandatory) | An array of colors to replace the colors in the palette.
offset | (Mandatory) | The position in the palette to start the replacement.

Return Value

None


DrawArea.getARGBColor

DrawArea.getARGBColor

Usage

getARGBColor(c)

Description

Obtain the ARGB color given a palette color.

If the given color is already in ARGB format, the same value is returned.

Arguments

Argument | Default | Description
c | (Mandatory) | The color to be changed to ARGB format.

Return Value

The ARGB color converted from the given color.


DrawArea.halfColor

DrawArea.halfColor

Usage

halfColor(c)

Description

Creates a color that is half the intensity of the given color.

Arguments

Argument | Default | Description
c | (Mandatory) | The given color.

Return Value

A 32-bit integer representing the half intensity color.


DrawArea.dashLineColor

DrawArea.dashLineColor

Usage

dashLineColor(color [, patternCode ])

Description

Creates a dash line color.

A dash line color is a dynamic color that switches on and off periodically. When it is used to draw a line, the line will appear as a dash line.

The style of the dash line is defined by a pattern code, which is a 4-byte integer. A value of PPQQRRSS (in hex) means the first PP pixels are turned on, followed by QQ pixels turned off, followed by RR pixels turned on, followed by SS pixels turned off, and then restart from PP again.

ChartDirector comes from several predefined constants for common dash line patterns.

Constant | Value (in Hex) | Dash Line Style
DashLine | 00000505 |
DotLine | 00000202 |
DotDashLine | 05050205 |
AltDashLine | 0A050505 |

Arguments

Argument | Default | Description
color | (Mandatory) | The color to draw the dash line.
patternCode | DashLine | A 4-byte integer representing the style of the dash line.

Return Value

A 32-bit integer representing the dash line color.


DrawArea.patternColor

DrawArea.patternColor

Usage

patternColor(colorArray, height [, startX, startY ])

Description

Creates a pattern color using an array of colors as the bitmap pattern.

A pattern color is a dynamic color that changes according to a 2D periodic pattern. When it is used to fill an area, the area will look like being tiled with a wallpaper pattern.

Arguments

Argument | Default | Description
colorArray | (Mandatory) | An array of colors representing the colors of the bitmap pixels. The color of the pixel at (x, y) should correspond to index (x + y * width - 1) of the array.
height | (Mandatory) | The height of the bitmap in pixels. (The width is automatically computed as the size of the color array divided by the height.)
startX | 0 | The x coordinate of a reference point to align with the top-left corner the pattern.
startY | 0 | The y coordinate of a reference point to align with the top-left corner the pattern.

Return Value

A 32-bit integer representing the pattern color.


DrawArea.patternColor2

DrawArea.patternColor2

Usage

patternColor2(filename [, startX, startY ])

Description

Creates a pattern color by loading the pattern from an image file.

A pattern color is a dynamic color that changes according to a 2D periodic pattern. When it is used to fill an area, the area will look like being tiled with a wallpaper pattern.

ChartDirector will automatically detect the image file format using the file extension, which must either png, jpg, jpeg, gif, wbmp or wmp (case insensitive).

Please refer to DrawArea.setSearchPath on the directory that ChartDirector will search for the file.

Arguments

Argument | Default | Description
filename | (Mandatory) | An image file providing the pattern.
startX | 0 | The x coordinate of a reference point to align with the top-left corner the pattern.
startY | 0 | The y coordinate of a reference point to align with the top-left corner the pattern.

Return Value

A 32-bit integer representing the pattern color.


DrawArea.linearGradientColor

DrawArea.linearGradientColor

Usage

linearGradientColor(startX, startY, endX, endY, startColor, endColor [, periodic ])

Description

Creates a two-point linear gradient color.

Arguments

Argument | Default | Description
startX | (Mandatory) | The x coordinate of the starting point of the reference gradient line segment.
startY | (Mandatory) | The y coordinate of the starting point of the reference gradient line segment.
endX | (Mandatory) | The x coordinate of the ending point of the reference gradient line segment.
endY | (Mandatory) | The y coordinate of the ending point of the reference gradient line segment.
startColor | (Mandatory) | The color at the starting point of the reference gradient line segment.
endColor | (Mandatory) | The color at the ending point of the reference gradient line segment.
periodic | false | Specifies whether the gradient will repeat itself periodically. If the gradient does not repeat itself, the points that lie beyond the end points of the gradient line segment will assume the colors of the end points.

Return Value

A 32-bit integer representing the linear gradient color.


DrawArea.linearGradientColor2

DrawArea.linearGradientColor2

Usage

linearGradientColor2(startX, startY, endX, endY, colorArray [, periodic ])

Description

Creates a multi-point linear gradient color.

In this method, the color points are defined as an array of positions and colors along a reference line segment, in the following format:

position0, color0, position1, color1, .... positionN, colorN

The positions are specified as a number from 0 - 256 (0 - 100 in hex), in which 0 represents the starting point of the reference line segment, and 256 (100 in hex) represents the ending point of the reference line segment.

For example, the array (in hex):

000000, FF0000, 000080, FFFF00, 000100, 00FF00

means the starting point (000000) is red (FF0000), the mid-point (000080 in hex) is yellow (FFFF00), and the ending point (000100 in hex) is green (00FF00).

One common usage of multi-point gradient colors is to define colors that have metallic look and feel. ChartDirector comes from several predefined gradient color arrays as follows.

Name | Value (in Hex)
goldGradient | 000000, FFE743, 000060, FFFFE0, 0000B0, FFF0B0, 000100, FFE743
silverGradient | 000000, C8C8C8, 000060, F8F8F8, 0000B0, E0E0E0, 000100, C8C8C8
redMetalGradient | 000000, E09898, 000060, FFF0F0, 0000B0, F0D8D8, 000100, E09898
greenMetalGradient | 000000, 98E098, 000060, F0FFF0, 0000B0, D8F0D8, 000100, 98E098
blueMetalGradient | 000000, 9898E0, 000060, F0F0FF, 0000B0, D8D8F0, 000100, 9898E0

Arguments

Argument | Default | Description
startX | (Mandatory) | The x coordinate of the starting point of the reference gradient line segment.
startY | (Mandatory) | The y coordinate of the starting point of the reference gradient line segment.
endX | (Mandatory) | The x coordinate of the ending point of the reference gradient line segment.
endY | (Mandatory) | The y coordinate of the ending point of the reference gradient line segment.
colorArray | (Mandatory) | An array defining the positions and colors of the pixels along the reference gradient line segment.
periodic | false | Specifies whether the gradient will repeat itself periodically. If the gradient does not repeat itself, the points that lie beyond the end points of the gradient line segment will assume the colors of the end points.

Return Value

A 32-bit integer representing the linear gradient color.


DrawArea.radialGradientColor

DrawArea.radialGradientColor

Usage

radialGradientColor(cx, cy, rx, ry, startColor, endColor [, periodic ])

Description

Creates a two-point radial gradient color.

Arguments

Argument | Default | Description
cx | (Mandatory) | The x coordinate of the center of the radial gradient.
cy | (Mandatory) | The y coordinate of the center of the radial gradient.
rx | (Mandatory) | The horizontal radius of the radial gradient defining ellipse.
ry | (Mandatory) | The vertical radius of the radial gradient defining ellipse.
startColor | (Mandatory) | The color at the center of the gradient defining ellipse.
endColor | (Mandatory) | The color at the perimeter of the gradient defining ellipse.
periodic | false | Specifies whether the gradient will repeat itself periodically. If the gradient does not repeat itself, the points that lie outside the gradient defining ellipse will assume the color at the perimeter of the gradient defining ellipse.

Return Value

A 32-bit integer representing the radial gradient color.


DrawArea.radialGradientColor2

DrawArea.radialGradientColor2

Usage

radialGradientColor2(cx, cy, rx, ry, colorArray [, periodic ])

Description

Creates a multi-point radial gradient color.

In this method, the color points are defined as an array of radial distances and colors, in the following format:

distance0, color0, distance1, color1, .... distanceN, colorN

The distances are specified as a number from 0 - 256 (0 - 100 in hex), in which 0 represents the center of the gradient defining ellipse, and 256 (100 in hex) represents the perimeter of the gradient defining ellipse.

For example, the array (in hex):

000000, FF0000, 000080, FFFF00, 000100, 00FF00

means the center (000000) is red (FF0000), the mid-point (000080 in hex) is yellow (FFFF00), and the perimeter (000100 in hex) is green (00FF00).

Arguments

Argument | Default | Description
cx | (Mandatory) | The x coordinate of the center of the radial gradient.
cy | (Mandatory) | The y coordinate of the center of the radial gradient.
rx | (Mandatory) | The horizontal radius of the radial gradient defining ellipse.
ry | (Mandatory) | The vertical radius of the radial gradient defining ellipse.
colorArray | (Mandatory) | An array defining the radial distances and colors.
periodic | false | Specifies whether the gradient will repeat itself periodically. If the gradient does not repeat itself, the points that lie outside the gradient defining ellipse will assume the color at the perimeter of the gradient defining ellipse.

Return Value

A 32-bit integer representing the radial gradient color.


DrawArea.gradientColor

DrawArea.gradientColor

Usage

gradientColor(startX, startY, endX, endY, startColor, endColor)

Description

Creates a two-point linear gradient color.

This method is for backward compatibility. Use DrawArea.linearGradientColor instead.

Arguments

Argument | Default | Description
startX | (Mandatory) | The x coordinate of the starting point of the reference gradient line segment.
startY | (Mandatory) | The y coordinate of the starting point of the reference gradient line segment.
endX | (Mandatory) | The x coordinate of the ending point of the reference gradient line segment.
endY | (Mandatory) | The y coordinate of the ending point of the reference gradient line segment.
startColor | (Mandatory) | The color at the starting point of the reference gradient line segment.
endColor | (Mandatory) | The color at the ending point of the reference gradient line segment.

Return Value

A 32-bit integer representing the linear gradient color.


DrawArea.gradientColor2

DrawArea.gradientColor2

Usage

gradientColor2(colorArray [, angle [, scale [, startX, startY ]]])

Description

Creates a multi-point linear gradient color.

This method is for backward compatibility. Use DrawArea.linearGradientColor2 instead.

Arguments

Argument | Default | Description
colorArray | (Mandatory) | An array defining the positions and colors of the pixels along the reference gradient line segment.
angle | 90 | The direction of the reference gradient line segment in degrees, measured clockwise, with 0 degree as the upward pointing direction. The default direction is horizontal from left to right (90 degrees).
scale | 1.0 | The scaling factor for the reference gradient line segment. By default, the reference gradient line segment is 256 pixels in length. The scaling factor can be use to stretch or compress the gradient line segment.
startX | 0 | The x coordinate of the starting point of the reference gradient line segment.
startY | 0 | The y coordinate of the starting point of the reference gradient line segment.

Return Value

A 32-bit integer representing the linear gradient color.


DrawArea.reduceColors

DrawArea.reduceColors

Usage

reduceColors(colorCount [, blackAndWhite ])

Description

Reduces the number of colors in the image.

The colors in the image will be reduced to at most the number of colors specified, which should be 16 - 256. You may also set the image to black and white. In this case, the color count means number of grey levels.

The colors will be reduced by computing an optimal palette for the image. The image will then be converted using the palette based on the current dithering settings (see DrawArea.setDitherMethod).

Arguments

Argument | Default | Description
colorCount | (Mandatory) | The maximum number of colors that image should have after after reduction. Must be between 16 - 256.
blackAndWhite | false (zero) | A true (non-zero) value means the image will be converted to black and white (with grey levels). A false (zero) value means the image will not be converted to black and white.

Return Value

The actual number of colors the converted image has.


TTFText

TTFText

The TTFText class represents text blocks. TTFText objects are created using DrawArea.text3 or DrawArea.text4.

Method | Inherited | Description
getWidth | (Self) | Gets the width of the text block.
getHeight | (Self) | Gets the height of the text block.
getLineHeight | (Self) | Gets the height of a typical line in the text block.
getLineDistance | (Self) | Gets the distance between two lines in the text block.
draw | (Self) | Draws the text block.


TTFText.getWidth

TTFText.getWidth

Usage

getWidth()

Description

Gets the width of the text block.

Arguments

None

Return Value

The width of the text block in pixels.


TTFText.getHeight

TTFText.getHeight

Usage

getHeight()

Description

Gets the height of the text block.

Arguments

None

Return Value

The height of the text block in pixels.


TTFText.getLineHeight

TTFText.getLineHeight

Usage

getLineHeight()

Description

Gets the height of a typical line in the text block.

Arguments

None

Return Value

The height of a typical line in the text block in pixels.


TTFText.getLineDistance

TTFText.getLineDistance

Usage

getLineDistance()

Description

Gets the distance between two lines in the text block.

Arguments

None

Return Value

The distance between two lines in the text block in pixels.


TTFText.draw

TTFText.draw

Usage

draw(x, y, color [, alignment ])

Description

Draws the text block.

Arguments

Argument | Default | Description
x | (Mandatory) | The x coordinate of a reference point to align the text.
y | (Mandatory) | The y coordinate of a reference point to align the text.
color | (Mandatory) | The color of the text.
alignment | TopLeft | The location of the text relative to the reference point. See Alignment Specification for supported alignment types.

Return Value

None


ArrayMath

ArrayMath

The ArrayMath class is a utility class used to perform array computations.

Method | Inherited | Description
ArrayMath | (Self) | Creates an ArrayMath object and initialize it with the given array.
add | (Self) | Adds an array to the ArrayMath object.
add2 | (Self) | Adds a number to every element of the ArrayMath object.
sub | (Self) | Subtracts an array from the ArrayMath object.
sub2 | (Self) | Subtracts a number from every element of the ArrayMath object.
mul | (Self) | Multiplies an array to the ArrayMath object.
mul2 | (Self) | Multiplies a number to every element of the ArrayMath object.
div | (Self) | Divides the ArrayMath object by the given array.
div2 | (Self) | Divides every element of the ArrayMath object by the given number.
financeDiv | (Self) | Divides the ArrayMath object by the given array, with special handling of the case of zero divided by zero.
shift | (Self) | Shifts the array "rightwards".
delta | (Self) | Subtracts each element of the ArrayMath object by an earlier element in the same ArrayMath object.
rate | (Self) | Divides each element of the ArrayMath object by an earlier element in the same ArrayMath object.
abs | (Self) | Replaces each element of the ArrayMath object by its absolute value.
acc | (Self) | Replaces each element of the ArrayMath object by the accumulated total of its previous element (including itself).
selectGTZ | (Self) | Selects the elements of the ArrayMath object by checking if the elements of the given decisionArray is greater than zero.
selectGEZ | (Self) | Selects the elements of the ArrayMath object by checking if the elements of the given decisionArray is greater than or equal to zero.
selectLTZ | (Self) | Selects the elements of the ArrayMath object by checking if the elements of the given decisionArray is less than zero.
selectLEZ | (Self) | Selects the elements of the ArrayMath object by checking if the elements of the given decisionArray is less than or equal to zero.
selectEQZ | (Self) | Selects the elements of the ArrayMath object by checking if the elements of the given decisionArray is equal to zero.
selectNEZ | (Self) | Selects the elements of the ArrayMath object by checking if the elements of the given decisionArray is not equal to zero.
selectStartOfHour | (Self) | Selects the elements of the ArrayMath object that represents a different hour from the previous element.
selectStartOfDay | (Self) | Selects the elements of the ArrayMath object that represents a different day from the previous element.
selectStartOfWeek | (Self) | Selects the elements of the ArrayMath object that represents a different week from the previous element.
selectStartOfMonth | (Self) | Selects the elements of the ArrayMath object that represents a different month from the previous element.
selectStartOfYear | (Self) | Selects the elements of the ArrayMath object that represents a different year from the previous element.
selectRegularSpacing | (Self) | Selects an evenly spaced subset of elements of the ArrayMath object.
trim | (Self) | Trims the ArrayMath object by keeping only some elements in the middle.
insert | (Self) | Inserts the elements of an array to the ArrayMath object.
insert2 | (Self) | Inserts some constant elements to the ArrayMath object.
replace | (Self) | Finds elements that are equal to a given value and replace it with another value.
movAvg | (Self) | Replaces each element of the ArrayMath object by its moving average.
expAvg | (Self) | Replaces each element of the ArrayMath object by its exponential average.
movMed | (Self) | Replaces each element of the ArrayMath object by its moving median.
movPercentile | (Self) | Replaces each element of the ArrayMath object by its moving percentile.
movMax | (Self) | Replaces each element of the ArrayMath object by its moving maximum.
movMin | (Self) | Replaces each element of the ArrayMath object by its moving minimum.
movStdDev | (Self) | Replaces each element of the ArrayMath object by its moving standard deviation.
movCorr | (Self) | Replaces each element of the ArrayMath object by the moving correlation with another array or with itself.
lowess | (Self) | Fits a curve through the data points in the ArrayMath object using the LOWESS algorithm.
lowess2 | (Self) | Fits a curve through the data points in the ArrayMath object using the LOWESS algorithm, where the spacing of the data points is supplied by the given array.
result | (Self) | Gets the content of the ArrayMath object as a normal array to be used in other ChartDirector API.
sum | (Self) | Gets the sum value of the elements of the ArrayMath object.
max | (Self) | Gets the maximum value of the elements of the ArrayMath object.
min | (Self) | Gets the minimum value of the elements of the ArrayMath object.
avg | (Self) | Gets the avg value of the elements of the ArrayMath object.
med | (Self) | Gets the med value of the elements of the ArrayMath object.
percentile | (Self) | Gets the required percentile value of the elements of the ArrayMath object.
stdDev | (Self) | Gets the stdDev value of the elements of the ArrayMath object.
maxIndex | (Self) | Gets the index of the maximum value element of the ArrayMath object.
minIndex | (Self) | Gets the index of the minimum value element of the ArrayMath object.
aggregate | (Self) | Aggregates a data array by merging groups of elements, similar to the GROUP BY clause in SQL statements.


ArrayMath.ArrayMath

ArrayMath.ArrayMath

Usage

ArrayMath(a)

Description

Creates an ArrayMath object and initialize it with the given array.

Note: In the ColdFusion edition of ChartDirector, the ArrayMath constructor is implemented as a method of the ChartDirector.CFChart object called ChartDirector.CFChart.ArrayMath.

Arguments

Argument | Default | Description
a | (Mandatory) | An array of numbers used to initialize the ArrayMath object.

Return Value

The ArrayMath object created.


ArrayMath.add

ArrayMath.add

Usage

add(b)

Description

Adds an array to the ArrayMath object.

The array will be added by adding the each array element to the corresponding element of the ArrayMath object.

Arguments

Argument | Default | Description
b | (Mandatory) | An array of numbers to be added to the ArrayMath object.

Return Value

The current ArrayMath object.


ArrayMath.add2

ArrayMath.add2

Usage

add2(b)

Description

Adds a number to every element of the ArrayMath object.

Arguments

Argument | Default | Description
b | (Mandatory) | A number to be added to every element of the ArrayMath object.

Return Value

The current ArrayMath object.


ArrayMath.sub

ArrayMath.sub

Usage

sub(b)

Description

Subtracts an array from the ArrayMath object.

The array will be subtracted by subtracting each array element from the corresponding element of the ArrayMath object.

Arguments

Argument | Default | Description
b | (Mandatory) | An array of numbers to be subtracted from the ArrayMath object.

Return Value

The current ArrayMath object.


ArrayMath.sub2

ArrayMath.sub2

Usage

sub2(b)

Description

Subtracts a number from every element of the ArrayMath object.

Arguments

Argument | Default | Description
b | (Mandatory) | A number to be subtracted from every element of the ArrayMath object.

Return Value

The current ArrayMath object.


ArrayMath.mul

ArrayMath.mul

Usage

mul(b)

Description

Multiplies an array to the ArrayMath object.

The array will be multiplied by multiplying each array element with the corresponding element of the ArrayMath object.

Arguments

Argument | Default | Description
b | (Mandatory) | An array of numbers to be multiplied to the ArrayMath object.

Return Value

The current ArrayMath object.


ArrayMath.mul2

ArrayMath.mul2

Usage

mul2(b)

Description

Multiplies a number to every element of the ArrayMath object.

Arguments

Argument | Default | Description
b | (Mandatory) | A number to be multiplied to every element of the ArrayMath object.

Return Value

The current ArrayMath object.


ArrayMath.div

ArrayMath.div

Usage

div(b)

Description

Divides the ArrayMath object by the given array.

The ArrayMath object will be divided by dividing each of its elements by the corresponding element in the given array.

Arguments

Argument | Default | Description
b | (Mandatory) | An array of numbers used as divisors to divide the ArrayMath object.

Return Value

The current ArrayMath object.


ArrayMath.div2

ArrayMath.div2

Usage

div2(b)

Description

Divides every element of the ArrayMath object by the given number.

Arguments

Argument | Default | Description
b | (Mandatory) | A number to be used as divisor to divide every element of the ArrayMath object.

Return Value

The current ArrayMath object.


ArrayMath.financeDiv

ArrayMath.financeDiv

Usage

financeDiv(b, zeroByZeroValue)

Description

Divides the ArrayMath object by the given array, with special handling of the case of zero divided by zero.

In many financial formulas, it is possible to have cases of zero divided by zero. For example, the Relative Strength Index is defined as the ratio between positive price changes and absolute value of all price changes over a period of time. In case the price does not change at all during that period, and the RSI will become zero divided by zero.

Traditionally, under the above case, the RSI will be consider as 50%.

To handle these special cases, the financeDiv method has an argument specifying what value to assume in case the division is zero divided by zero.

Arguments

Argument | Default | Description
b | (Mandatory) | An array of numbers used as divisors to divide the ArrayMath object.
zeroByZeroValue | (Mandatory) | The value to use if the division is zero divided by zero.

Return Value

The current ArrayMath object.


ArrayMath.shift

ArrayMath.shift

Usage

shift([ offset [, fillValue ]])

Description

Shifts the array "rightwards".

If the array does not have any NoValue data points, this method will shift the point at position "n" to "n + offset". On the "right" side of the array (the side with the largest index), points that are shifted outside the array will be discarded. On the "left" side of the array, fillValue data points will be shifted in.

If the array contains NoValue data points, these points are not shifted. Conceptually, one can imagine the non-NoValue points being shifted to the next non-NoValue positions, and the process repeats offset number of times.

Arguments

Argument | Default | Description
offset | 1 | The number of positions to shift the array "rightwards."
fillValue | NoValue | The new value to be shifted into the array.

Return Value

The current ArrayMath object.


ArrayMath.delta

ArrayMath.delta

Usage

delta([ offset ])

Description

Subtracts each element of the ArrayMath object by an earlier element in the same ArrayMath object.

Arguments

Argument | Default | Description
offset | 1 | The difference in position between an element and the earlier element to be subtracted from it.

Return Value

The current ArrayMath object.


ArrayMath.rate

ArrayMath.rate

Usage

rate([ offset ])

Description

Divides each element of the ArrayMath object by an earlier element in the same ArrayMath object.

Arguments

Argument | Default | Description
offset | 1 | The difference in position between an element and the earlier element to divide it.

Return Value

The current ArrayMath object.


ArrayMath.abs

ArrayMath.abs

Usage

abs()

Description

Replaces each element of the ArrayMath object by its absolute value.

Arguments

None

Return Value

The current ArrayMath object.


ArrayMath.acc

ArrayMath.acc

Usage

acc()

Description

Replaces each element of the ArrayMath object by the accumulated total of its previous element (including itself).

Arguments

None

Return Value

The current ArrayMath object.


ArrayMath.selectGTZ

ArrayMath.selectGTZ

Usage

selectGTZ([ decisionArray [, fillValue ]])

Description

Selects the elements of the ArrayMath object by checking if the elements of the given decisionArray is greater than zero.

The selected elements will be left unchanged. The remaining elements will be replaced by the given fillValue.

If the decisionArray is empty, the ArrayMath object itself will function as the decision array.

Arguments

Argument | Default | Description
decisionArray | [Empty_Array] | An array of numbers used to decide whether the corresponding elements in the ArrayMath object is selected or not.
fillValue | 0 | The value used to replace the elements that are not selected.

Return Value

The current ArrayMath object.


ArrayMath.selectGEZ

ArrayMath.selectGEZ

Usage

selectGEZ([ decisionArray [, fillValue ]])

Description

Selects the elements of the ArrayMath object by checking if the elements of the given decisionArray is greater than or equal to zero.

The selected elements will be left unchanged. The remaining elements will be replaced by the given fillValue.

If the decisionArray is empty, the ArrayMath object itself will function as the decision array.

Arguments

Argument | Default | Description
decisionArray | [Empty_Array] | An array of numbers used to decide whether the corresponding elements in the ArrayMath object is selected or not.
fillValue | 0 | The value used to replace the elements that are not selected.

Return Value

The current ArrayMath object.


ArrayMath.selectLTZ

ArrayMath.selectLTZ

Usage

selectLTZ([ decisionArray [, fillValue ]])

Description

Selects the elements of the ArrayMath object by checking if the elements of the given decisionArray is less than zero.

The selected elements will be left unchanged. The remaining elements will be replaced by the given fillValue.

If the decisionArray is empty, the ArrayMath object itself will function as the decision array.

Arguments

Argument | Default | Description
decisionArray | [Empty_Array] | An array of numbers used to decide whether the corresponding elements in the ArrayMath object is selected or not.
fillValue | 0 | The value used to replace the elements that are not selected.

Return Value

The current ArrayMath object.


ArrayMath.selectLEZ

ArrayMath.selectLEZ

Usage

selectLEZ([ decisionArray [, fillValue ]])

Description

Selects the elements of the ArrayMath object by checking if the elements of the given decisionArray is less than or equal to zero.

The selected elements will be left unchanged. The remaining elements will be replaced by the given fillValue.

If the decisionArray is empty, the ArrayMath object itself will function as the decision array.

Arguments

Argument | Default | Description
decisionArray | [Empty_Array] | An array of numbers used to decide whether the corresponding elements in the ArrayMath object is selected or not.
fillValue | 0 | The value used to replace the elements that are not selected.

Return Value

The current ArrayMath object.


ArrayMath.selectEQZ

ArrayMath.selectEQZ

Usage

selectEQZ([ decisionArray [, fillValue ]])

Description

Selects the elements of the ArrayMath object by checking if the elements of the given decisionArray is equal to zero.

The selected elements will be left unchanged. The remaining elements will be replaced by the given fillValue.

If the decisionArray is empty, the ArrayMath object itself will function as the decision array.

Arguments

Argument | Default | Description
decisionArray | [Empty_Array] | An array of numbers used to decide whether the corresponding elements in the ArrayMath object is selected or not.
fillValue | 0 | The value used to replace the elements that are not selected.

Return Value

The current ArrayMath object.


ArrayMath.selectNEZ

ArrayMath.selectNEZ

Usage

selectNEZ([ decisionArray [, fillValue ]])

Description

Selects the elements of the ArrayMath object by checking if the elements of the given decisionArray is not equal to zero.

The selected elements will be left unchanged. The remaining elements will be replaced by the given fillValue.

If the decisionArray is empty, the ArrayMath object itself will function as the decision array.

Arguments

Argument | Default | Description
decisionArray | [Empty_Array] | An array of numbers used to decide whether the corresponding elements in the ArrayMath object is selected or not.
fillValue | 0 | The value used to replace the elements that are not selected.

Return Value

The current ArrayMath object.


ArrayMath.selectStartOfHour

ArrayMath.selectStartOfHour

Usage

selectStartOfHour([ majorTickStep [, initialMargin ]])

Description

Selects the elements of the ArrayMath object that represents a different hour from the previous element.

This method assumes the elements of the ArrayMath object are dates/times.

The primary purpose of this method is to select the appropriate elements as ticks on an enumerated axis.

Suppose you want to plot a variable against time. The x-values of the data points will be an array of dates/times. If an enumerated x-axis is used (see Axis.setLabels), there will be a tick at every data point, which may be too dense if there are too many data points.

This method can be used to reduce the ticks to one tick per hour (or one tick per multiple hours). This is by selecting the dates/times in the data array only if it is not the same hour as the previous element in the array. The selected elements will be left unchanged, while the elements not select will be replaced by NoValue. The resulting array can be used directly in Axis.setLabels2.

For the first data point, there is no previous data point to compare, so it is handled differently. The first data point will be selected if it is near the beginning of the hour it represents. By default, near means within 300 seconds. This is configurable using the initialMargin argument.

Note that if the data points does not have data in a certain time range, no element can be selected in that time range, and so there will be no tick for that time range. This is appropriate for many chart types, such as finance charts, in which missing time ranges (non-trading hours, holidays, etc) are traditionally skipped.

However, if the data points may contain missing time ranges, but the ticks cannot be skipped, it may be more appropriate to use a non-enumerated x-axis by using Layer.setXData and Axis.setDateScale3 (or Axis.setDateScale or Axis.setDateScale2).

Arguments

Argument | Default | Description
majorTickStep | 1 | The tick step. The default value of 1 means one tick per hour. A value of n means one tick per n hours.
initialMargin | 300 | The margin for the first data point. The first data point will be selected if it is within initialMargin number of seconds from beginning of the hour it represents. The default is 300 seconds.

Return Value

The current ArrayMath object.


ArrayMath.selectStartOfDay

ArrayMath.selectStartOfDay

Usage

selectStartOfDay([ majorTickStep [, initialMargin ]])

Description

Selects the elements of the ArrayMath object that represents a different day from the previous element.

This method assumes the elements of the ArrayMath object are dates/times.

The primary purpose of this method is to select the appropriate elements as ticks on an enumerated axis.

Suppose you want to plot a variable against time. The x-values of the data points will be an array of dates/times. If an enumerated x-axis is used (see Axis.setLabels), there will be a tick at every data point, which may be too dense if there are too many data points.

This method can be used to reduce the ticks to one tick per day (or one tick per multiple days). This is by selecting the dates/times in the data array only if it is not the same day as the previous element in the array. The selected elements will be left unchanged, while the elements not select will be replaced by NoValue. The resulting array can be used directly in Axis.setLabels2.

For the first data point, there is no previous data point to compare, so it is handled differently. The first data point will be selected if it is near the beginning of the day it represents. By default, near means within 3 hours (10800 seconds). This is configurable using the initialMargin argument.

Note that if the data points does not have data in a certain time range, no element can be selected in that time range, and so there will be no tick for that time range. This is appropriate for many chart types, such as finance charts, in which missing time ranges (non-trading hours, holidays, etc) are traditionally skipped.

However, if the data points may contain missing time ranges, but the ticks cannot be skipped, it may be more appropriate to use a non-enumerated x-axis by using Layer.setXData and Axis.setDateScale3 (or Axis.setDateScale or Axis.setDateScale2).

Arguments

Argument | Default | Description
majorTickStep | 1 | The tick step. The default value of 1 means one tick per day. A value of n means one tick per n days.
initialMargin | 10800 | The margin for the first data point. The first data point will be selected if it is within initialMargin number of seconds from beginning of the day it represents. The default is 3 hours (10800 seconds).

Return Value

The current ArrayMath object.


ArrayMath.selectStartOfWeek

ArrayMath.selectStartOfWeek

Usage

selectStartOfWeek([ majorTickStep [, initialMargin ]])

Description

Selects the elements of the ArrayMath object that represents a different week from the previous element.

This method assumes the elements of the ArrayMath object are dates/times.

The primary purpose of this method is to select the appropriate elements as ticks on an enumerated axis.

Suppose you want to plot a variable against time. The x-values of the data points will be an array of dates/times. If an enumerated x-axis is used (see Axis.setLabels), there will be a tick at every data point, which may be too dense if there are too many data points.

This method can be used to reduce the ticks to one tick per week (or one tick per multiple weeks). This is by selecting the dates/times in the data array only if it is not the same week as the previous element in the array. The selected elements will be left unchanged, while the elements not select will be replaced by NoValue. The resulting array can be used directly in Axis.setLabels2.

For the first data point, there is no previous data point to compare, so it is handled differently. The first data point will be selected if it is near the beginning of the week it represents. By default, near means within 2 days (172800 seconds). This is configurable using the initialMargin argument.

Note that if the data points does not have data in a certain time range, no element can be selected in that time range, and so there will be no tick for that time range. This is appropriate for many chart types, such as finance charts, in which missing time ranges (non-trading hours, holidays, etc) are traditionally skipped.

However, if the data points may contain missing time ranges, but the ticks cannot be skipped, it may be more appropriate to use a non-enumerated x-axis by using Layer.setXData and Axis.setDateScale3 (or Axis.setDateScale or Axis.setDateScale2).

Arguments

Argument | Default | Description
majorTickStep | 1 | The tick step. The default value of 1 means one tick per week. A value of n means one tick per n weeks.
initialMargin | 172800 | The margin for the first data point. The first data point will be selected if it is within initialMargin number of seconds from beginning of the week it represents. The default is 2 days (172800 seconds).

Return Value

The current ArrayMath object.


ArrayMath.selectStartOfMonth

ArrayMath.selectStartOfMonth

Usage

selectStartOfMonth([ majorTickStep [, initialMargin ]])

Description

Selects the elements of the ArrayMath object that represents a different month from the previous element.

This method assumes the elements of the ArrayMath object are dates/times.

The primary purpose of this method is to select the appropriate elements as ticks on an enumerated axis.

Suppose you want to plot a variable against time. The x-values of the data points will be an array of dates/times. If an enumerated x-axis is used (see Axis.setLabels), there will be a tick at every data point, which may be too dense if there are too many data points.

This method can be used to reduce the ticks to one tick per month (or one tick per multiple months). This is by selecting the dates/times in the data array only if it is not the same month as the previous element in the array. The selected elements will be left unchanged, while the elements not select will be replaced by NoValue. The resulting array can be used directly in Axis.setLabels2.

For the first data point, there is no previous data point to compare, so it is handled differently. The first data point will be selected if it is near the beginning of the month it represents. By default, near means within 5 days (432000 seconds). This is configurable using the initialMargin argument.

Note that if the data points does not have data in a certain time range, no element can be selected in that time range, and so there will be no tick for that time range. This is appropriate for many chart types, such as finance charts, in which missing time ranges (non-trading hours, holidays, etc) are traditionally skipped.

However, if the data points may contain missing time ranges, but the ticks cannot be skipped, it may be more appropriate to use a non-enumerated x-axis by using Layer.setXData and Axis.setDateScale3 (or Axis.setDateScale or Axis.setDateScale2).

Arguments

Argument | Default | Description
majorTickStep | 1 | The tick step. The default value of 1 means one tick per month. A value of n means one tick per n months.
initialMargin | 432000 | The margin for the first data point. The first data point will be selected if it is within initialMargin number of seconds from beginning of the month it represents. The default is 5 days (432000 seconds).

Return Value

The current ArrayMath object.


ArrayMath.selectStartOfYear

ArrayMath.selectStartOfYear

Usage

selectStartOfYear([ majorTickStep [, initialMargin ]])

Description

Selects the elements of the ArrayMath object that represents a different year from the previous element.

This method assumes the elements of the ArrayMath object are dates/times.

The primary purpose of this method is to select the appropriate elements as ticks on an enumerated axis.

Suppose you want to plot a variable against time. The x-values of the data points will be an array of dates/times. If an enumerated x-axis is used (see Axis.setLabels), there will be a tick at every data point, which may be too dense if there are too many data points.

This method can be used to reduce the ticks to one tick per year (or one tick per multiple years). This is by selecting the dates/times in the data array only if it is not the same year as the previous element in the array. The selected elements will be left unchanged, while the elements not select will be replaced by NoValue. The resulting array can be used directly in Axis.setLabels2.

For the first data point, there is no previous data point to compare, so it is handled differently. The first data point will be selected if it is near the beginning of the year it represents. By default, near means within 60 days (5184000 seconds). This is configurable using the initialMargin argument.

Note that if the data points does not have data in a certain time range, no element can be selected in that time range, and so there will be no tick for that time range. This is appropriate for many chart types, such as finance charts, in which missing time ranges (non-trading hours, holidays, etc) are traditionally skipped.

However, if the data points may contain missing time ranges, but the ticks cannot be skipped, it may be more appropriate to use a non-enumerated x-axis by using Layer.setXData and Axis.setDateScale3 (or Axis.setDateScale or Axis.setDateScale2).

Arguments

Argument | Default | Description
majorTickStep | 1 | The tick step. The default value of 1 means one tick per year. A value of n means one tick per n years.
initialMargin | 5184000 | The margin for the first data point. The first data point will be selected if it is within initialMargin number of seconds from beginning of the year it represents. The default is 60 days (5184000 seconds).

Return Value

The current ArrayMath object.


ArrayMath.selectRegularSpacing

ArrayMath.selectRegularSpacing

Usage

selectRegularSpacing(majorTickStep [, minorTickStep [, initialMargin ]])

Description

Selects an evenly spaced subset of elements of the ArrayMath object.

The primary purpose of this method is to select the regularly spaced elements as ticks on an enumerated axis.

For example, if the majorTickStep is 10, and minorTickStep is 5, this method will select one out of 10 elements as major tick elements, and one of out of 5 elements as minor tick elements.

Major tick elements will remain intact. The remaining minor ticks elements will have their values replaced with MinorTickOnly. Non-selected elements will have their values replaced with NoValue, so they will not appear on the axis. The resulting array can be used directly in Axis.setLabels2.

Arguments

Argument | Default | Description
majorTickStep | (Mandatory) | The spacing between major ticks.
minorTickStep | 0 | The spacing between minor ticks. The default value of 0 means no minor tick will be used.
initialMargin | 0 | The position of the first tick.

Return Value

The current ArrayMath object.


ArrayMath.trim

ArrayMath.trim

Usage

trim([ startIndex [, len ]])

Description

Trims the ArrayMath object by keeping only some elements in the middle.

Arguments

Argument | Default | Description
startIndex | 0 | The index for the first element to keep.
len | -1 | The number of elements to keep. -1 means keeping all elements from the startIndex to the end of the array.

Return Value

The current ArrayMath object.


ArrayMath.insert

ArrayMath.insert

Usage

insert(a [, insertPoint ])

Description

Inserts the elements of an array to the ArrayMath object.

Arguments

Argument | Default | Description
a | (Mandatory) | An array to be inserted to the ArrayMath object.
insertPoint | -1 | The position of the insertion point. The new elements will be inserted just before the insertion point. -1 means inserting elements at the end of the array.

Return Value

The current ArrayMath object.


ArrayMath.insert2

ArrayMath.insert2

Usage

insert2(c, len [, insertPoint ])

Description

Inserts some constant elements to the ArrayMath object.

Arguments

Argument | Default | Description
c | (Mandatory) | The value of the constant element.
len | (Mandatory) | The number of elements to insert.
insertPoint | -1 | The position of the insertion point. The new elements will be inserted just before the insertion point. -1 means inserting elements at the end of the array.

Return Value

The current ArrayMath object.


ArrayMath.replace

ArrayMath.replace

Usage

replace(a, b)

Description

Finds elements that are equal to a given value and replace it with another value.

Arguments

Argument | Default | Description
a | (Mandatory) | The value to be replaced.
b | (Mandatory) | The replacing value.

Return Value

The current ArrayMath object.


ArrayMath.movAvg

ArrayMath.movAvg

Usage

movAvg(interval)

Description

Replaces each element of the ArrayMath object by its moving average.

The interval parameter specifies the window size for computing moving average. The moving average is computed as the average of the current element with the previous (interval - 1) elements. No moving average can be computed for the first (interval - 1) elements, because there are insufficient previous elements. So the first (interval - 1) elements will be replaced with NoValue.

Arguments

Argument | Default | Description
interval | (Mandatory) | The window size.

Return Value

The current ArrayMath object.


ArrayMath.expAvg

ArrayMath.expAvg

Usage

expAvg(smoothingFactor)

Description

Replaces each element of the ArrayMath object by its exponential average.

The exponential average is computed by :

avg(n) = value(n) * smoothingFactor + avg(n - 1) * (1 - smoothingFactor)

where avg(n) is the exponential average of the nth element, and value(n) is the value of the nth element.

For the first element (n = 0), its exponential average is assumed to be equal to its original value.

Arguments

Argument | Default | Description
smoothingFactor | (Mandatory) | The smoothing factor used for computing exponential average. It should be between 0 - 1.

Return Value

The current ArrayMath object.


ArrayMath.movMed

ArrayMath.movMed

Usage

movMed(interval)

Description

Replaces each element of the ArrayMath object by its moving median.

The interval parameter specifies the window size for computing moving average. The moving average is computed as the median of the current element with the previous (interval - 1) elements. No moving median can be computed for the first (interval - 1) elements, because there are insufficient previous elements. So the first (interval - 1) elements will be replaced with NoValue.

Arguments

Argument | Default | Description
interval | (Mandatory) | The window size.

Return Value

The current ArrayMath object.


ArrayMath.movPercentile

ArrayMath.movPercentile

Usage

movPercentile(interval, percentile)

Description

Replaces each element of the ArrayMath object by its moving percentile.

The interval parameter specifies the window size for computing moving average. The moving average is computed as the percentile of the current element with the previous (interval - 1) elements. No moving percentile can be computed for the first (interval - 1) elements, because there are insufficient previous elements. So the first (interval - 1) elements will be replaced with NoValue.

Arguments

Argument | Default | Description
interval | (Mandatory) | The window size.
percentile | (Mandatory) | The percentile to be computed. It should be between 0 - 100.

Return Value

The current ArrayMath object.


ArrayMath.movMax

ArrayMath.movMax

Usage

movMax(interval)

Description

Replaces each element of the ArrayMath object by its moving maximum.

The interval parameter specifies the window size for computing moving average. The moving average is computed as the maximum of the current element with the previous (interval - 1) elements. No moving maximum can be computed for the first (interval - 1) elements, because there are insufficient previous elements. So the first (interval - 1) elements will be replaced with NoValue.

Arguments

Argument | Default | Description
interval | (Mandatory) | The window size.

Return Value

The current ArrayMath object.


ArrayMath.movMin

ArrayMath.movMin

Usage

movMin(interval)

Description

Replaces each element of the ArrayMath object by its moving minimum.

The interval parameter specifies the window size for computing moving average. The moving average is computed as the minimum of the current element with the previous (interval - 1) elements. No moving minimum can be computed for the first (interval - 1) elements, because there are insufficient previous elements. So the first (interval - 1) elements will be replaced with NoValue.

Arguments

Argument | Default | Description
interval | (Mandatory) | The window size.

Return Value

The current ArrayMath object.


ArrayMath.movStdDev

ArrayMath.movStdDev

Usage

movStdDev(interval)

Description

Replaces each element of the ArrayMath object by its moving standard deviation.

The interval parameter specifies the window size for computing moving average. The moving average is computed as the standard deviation of the current element with the previous (interval - 1) elements. No moving standard deviation can be computed for the first (interval - 1) elements, because there are insufficient previous elements. So the first (interval - 1) elements will be replaced with NoValue.

Arguments

Argument | Default | Description
interval | (Mandatory) | The window size.

Return Value

The current ArrayMath object.


ArrayMath.movCorr

ArrayMath.movCorr

Usage

movCorr(interval [, b ])

Description

Replaces each element of the ArrayMath object by the moving correlation with another array or with itself.

The interval parameter specifies the window size for computing moving correlation. The moving correlation is computed as the correlation coefficient between the ArrayMath object and the other array, where only the current element and the previous (interval - 1) elements are considered in the computation.

If the other array is not provided, it is assumed to be the sequence of numbers 0, 1, 2, 3, 4.... This is equivalent to checking if the elements of the ArrayMath object is linear.

No moving correlation can be computed for the first (interval - 1) elements, because there are insufficient previous elements. So the first (interval - 1) elements will be replaced with NoValue.

Arguments

Argument | Default | Description
interval | (Mandatory) | The window size.
b | [Empty_Array] | The array to be correlated with the ArrayMath object. If this argument is an empty array, the sequence of numbers 0, 1, 2, 3, 4 .... will be used instead.

Return Value

The current ArrayMath object.


ArrayMath.lowess

ArrayMath.lowess

Usage

lowess([ smoothness [, iteration ]])

Description

Fits a curve through the data points in the ArrayMath object using the LOWESS algorithm.

The full name of LOWESS is "Robust locally weighted regression and smoothing scatterplots". It is a commonly used algorithm for drawing a smooth curve through a number of points.

LOWESS works by assuming a small segment of any curve can be approximated by a straight line. For each data point, LOWESS finds the n nearest points to that data point (n is configurable), and performs weighted linear regression using a tricube weighting function. It then adjust the coordinates of the data point based on the result of the weighted linear regression.

LOWESS can run in multiple iterations, in which case it should converge to a stable curve - thus it is called "robust".

In most cases, LOWESS behaves better than many other smoothing algorithms, such as moving average, moving median, exponential average. Curves draw using LOWESS look smoother, yet they track the data points better. Also, LOWESS behaves well at the end points. On the other hand, methods based on moving windows (e.g. moving averages) do not work on the first few data points, because they need sufficient data points to fill the moving window first.

In this method, each element of the ArrayMath object will be replaced by the corresponding value computed using the LOWESS algorithm.

Arguments

Argument | Default | Description
smoothness | 0.25 | The smoothness factor. It must be between 0 - 1. It is the portion of points used in finding the n nearest points. In other words, n = smoothness * no_of_points. A larger value will result in a smoother the curve. A smaller value will result in the curve tracking the data points better. For LOWESS to have any smoothing effect at all, n must be at least 3. You may need to use a large smoothness factor if you only have a few data points.
iteration | 0 | The number of additional iteration used in the LOWESS algorithm. Unless your data is extremely noisy, in most case no additional iteration is necessary.

Return Value

The current ArrayMath object.


ArrayMath.lowess2

ArrayMath.lowess2

Usage

lowess2(b [, smoothness [, iteration ]])

Description

Fits a curve through the data points in the ArrayMath object using the LOWESS algorithm, where the spacing of the data points is supplied by the given array.

Please refer to ArrayMath.lowess for a brief description of the LOWESS algorithm.

In this method, each element of the ArrayMath object will be replaced by the corresponding value computed using the LOWESS algorithm.

Arguments

Argument | Default | Description
b | (Mandatory) | An array of numbers providing the x coordinates of the data points in the ArrayMath object.
smoothness | 0.25 | The smoothness factor. It must be between 0 - 1. It is the portion of points used in finding the n nearest points. In other words, n = smoothness * no_of_points. A larger value will result in a smoother the curve. A smaller value will result in the curve tracking the data points better. For LOWESS to have any smoothing effect at all, n must be at least 3. You may need to use a large smoothness factor if you only have a few data points.
iteration | 0 | The number of additional iteration used in the LOWESS algorithm. Unless your data is extremely noisy, in most case no additional iteration is necessary.

Return Value

The current ArrayMath object.


ArrayMath.result

ArrayMath.result

Usage

result()

Description

Gets the content of the ArrayMath object as a normal array to be used in other ChartDirector API.

Arguments

None

Return Value

The content of the ArrayMath object as a normal array.


ArrayMath.sum

ArrayMath.sum

Usage

sum()

Description

Gets the sum value of the elements of the ArrayMath object.

Arguments

None

Return Value

The sum value of the elements of the ArrayMath object.


ArrayMath.max

ArrayMath.max

Usage

max()

Description

Gets the maximum value of the elements of the ArrayMath object.

Arguments

None

Return Value

The maximum value of the elements of the ArrayMath object.


ArrayMath.min

ArrayMath.min

Usage

min()

Description

Gets the minimum value of the elements of the ArrayMath object.

Arguments

None

Return Value

The minimum value of the elements of the ArrayMath object.


ArrayMath.avg

ArrayMath.avg

Usage

avg()

Description

Gets the avg value of the elements of the ArrayMath object.

Arguments

None

Return Value

The avg value of the elements of the ArrayMath object.


ArrayMath.med

ArrayMath.med

Usage

med()

Description

Gets the med value of the elements of the ArrayMath object.

Arguments

None

Return Value

The med value of the elements of the ArrayMath object.


ArrayMath.percentile

ArrayMath.percentile

Usage

percentile(p)

Description

Gets the required percentile value of the elements of the ArrayMath object.

Arguments

Argument | Default | Description
p | (Mandatory) | The percentile to get. It should be between 0 - 100.

Return Value

The required percentile value of the elements of the ArrayMath object.


ArrayMath.stdDev

ArrayMath.stdDev

Usage

stdDev()

Description

Gets the stdDev value of the elements of the ArrayMath object.

Arguments

None

Return Value

The stdDev value of the elements of the ArrayMath object.


ArrayMath.maxIndex

ArrayMath.maxIndex

Usage

maxIndex()

Description

Gets the index of the maximum value element of the ArrayMath object.

Arguments

None

Return Value

The index of the maximum value element of the ArrayMath object.


ArrayMath.minIndex

ArrayMath.minIndex

Usage

minIndex()

Description

Gets the index of the minimum value element of the ArrayMath object.

Arguments

None

Return Value

The index of the minimum value element of the ArrayMath object.


ArrayMath.aggregate

ArrayMath.aggregate

Usage

aggregate(srcArray, aggregateMethod [, param ])

Description

Aggregates a data array by merging groups of elements, similar to the GROUP BY clause in SQL statements.

This primary usage of this method is for changing data resolution, such as to convert a daily data into weekly data.

If the data is from a database, aggregation can often be more efficiently and conveniently performed by using the GROUP BY clause of SQL. This method should only be used when the data are not coming from a database, or the aggregation method are not supported by the database used.

In this method, the ArrayMath object represents the delimiters used to group elements in the srcArray. The positions of all non-NoValue elements in the ArrayMath object will be used as delimiters positions.

For example, if the ArrayMath object consists of an array of 50 elements, and only the elements at 0, 10, 20, 30, 40 are not NoValue, then the groups will be defined as positions 0 - 9, 10 - 19, 20 - 29, 30 - 39 and 40 - 49.

Note that a group includes the starting delimiter position but excludes the ending delimiter position.

The ArrayMath object is typically created by applying ArrayMath.selectStartOfHour, ArrayMath.selectStartOfDay, ArrayMath.selectStartOfWeek, ArrayMath.selectStartOfMonth, ArrayMath.selectStartOfYear or ArrayMath.selectRegularSpacing to a data array.

For example, to group daily data into weekly data, one may create an ArrayMath object with the dates of the daily data, then ArrayMath.selectStartOfWeek to select only the elements representing the start of a week. The resulting ArrayMath object can then be used to aggregate daily data into weekly data.

Due to aggregation, the length of the output array will usually be shorter than, and never be longer than, the length of the input array.

Arguments

Argument | Default | Description
srcArray | (Mandatory) | The array to be aggregated.
aggregateMethod | (Mandatory) | The method to aggregate the data, which must be one of AggregateSum, AggregateAvg, AggregateStdDev, AggregateMin, AggregateMed, AggregateMax, AggregatePercentile, AggregateFirst, AggregateLast, AggregateCount.
param | 50 | The aggregation parameter, if needed. Currently, only AggregatePercentile needs a parameter to specify the percentile used.

Return Value

The aggregated array.


RanTable

RanTable

RanTable is a utility class to produce tables with random numbers. It facilitates testing and demonstrating ChartDirector programs without needing a real database table.

Method | Inherited | Description
RanTable | (Self) | Creates a RanTable object.
setCol | (Self) | Fill the given column in the RanTable with random numbers in the given range.
setCol2 | (Self) | Fill the given column in the RanTable with random numbers that fluctuates within a given speed.
setDateCol | (Self) | Fill the given column in the RanTable with a date/time series.
setHLOCCols | (Self) | Fill 4 columns in the RanTable with random high, low, open and close records.
selectDate | (Self) | Selects the rows within a certain date range.
getCol | (Self) | Gets the request column as an array of numbers.


RanTable.RanTable

RanTable.RanTable

Usage

RanTable(seed, noOfCols, noOfRows)

Description

Creates a RanTable object.

Note: In the ColdFusion edition of ChartDirector, the RanTable constructor is implemented as a method of the ChartDirector.CFChart object called ChartDirector.CFChart.RanTable.

Arguments

Argument | Default | Description
seed | (Mandatory) | The seed to be used in the random number generator.
noOfCols | (Mandatory) | The number of columns in the random number table.
noOfRows | (Mandatory) | The number of rows in the random number table.

Return Value

The RanTable object created.


RanTable.setCol

RanTable.setCol

Usage

setCol(colNo, minValue, maxValue)

Description

Fill the given column in the RanTable with random numbers in the given range.

Arguments

Argument | Default | Description
colNo | (Mandatory) | The column to fill. The first column is 0. The nth column is (n - 1).
minValue | (Mandatory) | The minimum value of the random number.
maxValue | (Mandatory) | The maximum value of the random number.

Return Value

None


RanTable.setCol2

RanTable.setCol2

Usage

setCol2(colNo, startValue, minDelta, maxDelta [, lowerLimit [, upperLimit ]])

Description

Fill the given column in the RanTable with random numbers that fluctuates within a given speed.

Arguments

Argument | Default | Description
colNo | (Mandatory) | The column to fill. The first column is 0. The nth column is (n - 1).
startValue | (Mandatory) | The value of the first record in the column.
minDelta | (Mandatory) | The minimum change allowed for between the current random number and the previous random number. This parameter is usually negative.
maxDelta | (Mandatory) | The maximum change allowed for between the current random number and the previous random number.
lowerLimit | [-Infinity] | The minimum value of the random number.
upperLimit | [+Infinity] | The maximum value of the random number.

Return Value

None


RanTable.setDateCol

RanTable.setDateCol

Usage

setDateCol(i, startTime, tickInc [, weekDayOnly ])

Description

Fill the given column in the RanTable with a date/time series.

Arguments

Argument | Default | Description
i | (Mandatory) | The column to fill. The first column is 0. The nth column is (n - 1).
startTime | (Mandatory) | The date/time of the first record in the column.
tickInc | (Mandatory) | The change in date/time for subsequent records in seconds. The value 30 * 86400 is assumed to mean 1 month (which is not a constant interval), and its multiplies are assumed to mean multiple months. In particular, the value 360 * 86400 is assumed to mean 12 months, or 1 year.
weekDayOnly | false (zero) | A true (non-zero) value means skipping dates that are not weekdays (Saturday and Sunday). A %F value means no skipping.

Return Value

None


RanTable.setHLOCCols

RanTable.setHLOCCols

Usage

setHLOCCols(i, startValue, minDelta, maxDelta [, lowerLimit [, upperLimit ]])

Description

Fill 4 columns in the RanTable with random high, low, open and close records.

The 4 columns will meet the constraints that for each record, the high value will be greater than or equal to the low value, and both the open and close values will be in between the high and low values.

Arguments

Argument | Default | Description
i | (Mandatory) | The column number of the "high" column. The next column will be assumed to be "low", followed by "open" and "close". The column number starts at 0. The first column is 0. The nth column is (n - 1).
startValue | (Mandatory) | The initial "open" value.
minDelta | (Mandatory) | The minimum change allowed for between the current "open" and the previous "close" value, as well as between the current "close" value and the current "open" value. This parameter is usually negative.
maxDelta | (Mandatory) | The maximum change allowed for between the current "open" and the previous "close" value, as well as between the current "close" value and the current "open" value.
lowerLimit | 0 | The minimum value for "high", "low", "open" and "close".
upperLimit | [+Infinity] | The maximum value for "high", "low", "open" and "close".

Return Value

None


RanTable.selectDate

RanTable.selectDate

Usage

selectDate(colNo, minDate, maxDate)

Description

Selects the rows within a certain date range.

After executing this method, the RanTable will be reduced to only contain rows that are within minDate and maxDate (inclusive of both dates).

Arguments

Argument | Default | Description
colNo | (Mandatory) | The date column to be used as selection criteria.
minDate | (Mandatory) | The minimum date (earliest date).
maxDate | (Mandatory) | The maximum date (latest date).

Return Value

The number of rows selected.


RanTable.getCol

RanTable.getCol

Usage

getCol(i)

Description

Gets the request column as an array of numbers.

Arguments

Argument | Default | Description
i | (Mandatory) | The column to get. The first column is 0. The nth column is (n - 1).

Return Value

An array containing numbers from the requested column.


FinanceSimulator

FinanceSimulator

FinanceSimulator is a utility class to produce tables with random numbers that look like valid financial data series. It facilitates testing and demonstrating ChartDirector financial charts without needing a real database table.

Method | Inherited | Description
FinanceSimulator | (Self) | Creates a FinanceSimulator object.
getTimeStamps | (Self) | Gets the timestamps of the data series.
getHighData | (Self) | Gets the high data series.
getLowData | (Self) | Gets the low data series.
getOpenData | (Self) | Gets the open data series.
getCloseData | (Self) | Gets the close data series.
getVolData | (Self) | Gets the volume data series.


FinanceSimulator.FinanceSimulator

FinanceSimulator.FinanceSimulator

Usage

FinanceSimulator(seed, startTime, endTime, resolution)

Description

Creates a FinanceSimulator object.

Note: In the ColdFusion edition of ChartDirector, the FinanceSimulator constructor is implemented as a method of the ChartDirector.CFChart object called ChartDirector.CFChart.FinanceSimulator.

Arguments

Argument | Default | Description
seed | (Mandatory) | The seed to be used in the random number generator.
startTime | (Mandatory) | The start date/time of the financial date series.
endTime | (Mandatory) | The end date/time of the financial date series.
resolution | (Mandatory) | The resolution of the financial data series in seconds. For example, a value of 86400 means daily data (1 day = 86400 seconds). A value of 7 * 86400 means weekly data. A value of 30 * 86400 means monthly data.

Return Value

The FinanceSimulator object created.


FinanceSimulator.getTimeStamps

FinanceSimulator.getTimeStamps

Usage

getTimeStamps()

Description

Gets the timestamps of the data series.

Arguments

None

Return Value

An array containing the timestamps of the data series.


FinanceSimulator.getHighData

FinanceSimulator.getHighData

Usage

double[] getHighData()

Description

Gets the high data series.

Arguments

None

Return Value

An array containing the high data series.


FinanceSimulator.getLowData

FinanceSimulator.getLowData

Usage

double[] getLowData()

Description

Gets the low data series.

Arguments

None

Return Value

An array containing the low data series.


FinanceSimulator.getOpenData

FinanceSimulator.getOpenData

Usage

double[] getOpenData()

Description

Gets the open data series.

Arguments

None

Return Value

An array containing the open data series.


FinanceSimulator.getCloseData

FinanceSimulator.getCloseData

Usage

double[] getCloseData()

Description

Gets the close data series.

Arguments

None

Return Value

An array containing the close data series.


FinanceSimulator.getVolData

FinanceSimulator.getVolData

Usage

double[] getVolData()

Description

Gets the volume data series.

Arguments

None

Return Value

An array containing the volume data series.


Controls

Controls

This section describes controls and libraries for displaying charts and handling user interactions.

In this section

WebChartViewer
WebChartViewer is the server side class library that works with the browser side JsChartViewer control. Its main function is to handle chart update requests from JsChartViewer.

JsChartViewer
JsChartViewer is a browser side control written in Javascript. It provides view port support and partial chart update (AJAX update) support for the charts.


WebChartViewer

WebChartViewer

WebChartViewer is the server side counterpart to the browser side Javascript ChartViewer (JsChartViewer). Its main function is to handle chart update requests from JsChartViewer.

WebChartViewer is designed to act like a "proxy" to the JsChartViewer. During a partial chart update request, JsChartViewer will send its properties to the WebChartViewer and they will become the properties of the WebChartViewer. For example, the view port positions of the JsChartViewer will become the view port properties of the WebChartViewer. When the WebChartViewer responses, it will send the properties back to the JsChartViewer. Any properties modified on the server side will be reflected on the browser side.

Method | Inherited | Description
WebChartViewer | (Self) | Creates a new WebChartViewer object.
getId | (Self) | Gets the id of the WebChartViewer object.
setImageUrl | (Self) | Sets the URL used by the <IMG> tag to load the chart image.
getImageUrl | (Self) | Gets the URL used by the <IMG> tag to load the chart image.
setImageMap | (Self) | Sets the image map associated with the chart.
getImageMap | (Self) | Gets the image map associated with the chart.
setChartMetrics | (Self) | Sets the chart metrics of the chart.
getChartMetrics | (Self) | Gets the chart metrics of the chart.
makeDelayedMap | (Self) | Creates a delayed image map suitable for use in JsChartViewer.
renderHTML | (Self) | Generates the HTML tags necessary to represent the chart, image map, and the JsChartViewer state.
isPartialUpdateRequest | (Self) | Checks if the current HTTP Request is a partial update request (AJAX request) sent using JsChartViewer.partialUpdate.
isFullUpdateRequest | (Self) | Checks if the current HTTP request is a full update request containing information from a JsChartViewer.
isStreamRequest | (Self) | Checks if the current HTTP request is a stream update request sent using JsChartViewer.streamUpdate.
isViewPortChangedEvent | (Self) | Checks if the JsChartViewer.ViewPortChanged event has occurred.
getSenderClientId | (Self) | Gets the id of the JsChartViewer that sends the current HTTP request.
partialUpdateChart | (Self) | Sends the response to a partial chart update request.
setViewPortLeft | (Self) | Sets the position of the left side of the view port.
getViewPortLeft | (Self) | Gets the position of the left side of the view port.
setViewPortTop | (Self) | Sets the position of the top side of the view port.
getViewPortTop | (Self) | Gets the position of the top side of the view port.
setViewPortWidth | (Self) | Sets the width of the view port.
getViewPortWidth | (Self) | Gets the width of the view port.
setViewPortHeight | (Self) | Sets the height of the view port.
getViewPortHeight | (Self) | Gets the height of the view port.
setMouseUsage | (Self) | Sets the mouse usage mode of the control.
getMouseUsage | (Self) | Gets the mouse usage mode of the control.
setZoomDirection | (Self) | Sets the zoom direction for mouse zoom in/out actions.
getZoomDirection | (Self) | Gets the zoom direction for mouse zoom in/out actions.
setScrollDirection | (Self) | Sets the scroll direction for mouse scroll actions.
getScrollDirection | (Self) | Gets the scroll direction for mouse scroll actions.
setZoomInRatio | (Self) | Sets the magnification ratio for each zoom in click of the mouse.
getZoomInRatio | (Self) | Gets the magnification ratio for each zoom in click of the mouse.
setZoomOutRatio | (Self) | Sets the magnification ratio for each zoom out click of the mouse.
getZoomOutRatio | (Self) | Gets the magnification ratio for each zoom out click of the mouse.
setZoomInWidthLimit | (Self) | Sets the view port width at maximum zoom in.
getZoomInWidthLimit | (Self) | Gets the view port width at maximum zoom in for mouse zoom in actions.
setZoomOutWidthLimit | (Self) | Sets the view port width at maximum zoom out.
getZoomOutWidthLimit | (Self) | Gets the view port width at maximum zoom out for mouse zoom out actions.
setZoomInHeightLimit | (Self) | Sets the view port height at maximum zoom in.
getZoomInHeightLimit | (Self) | Gets the view port height at maximum zoom in for mouse zoom in actions.
setZoomOutHeightLimit | (Self) | Sets the view port height at maximum zoom out.
getZoomOutHeightLimit | (Self) | Gets the view port height at maximum zoom out for mouse zoom out actions.
setMinimumDrag | (Self) | Sets the minimum mouse drag distance before it is considered as an intentional drag.
getMinimumDrag | (Self) | Gets the minimum mouse drag distance before it is considered as an intentional drag.
setSelectionBorderWidth | (Self) | Sets the border width of the zoom selection box.
getSelectionBorderWidth | (Self) | Gets the border width of the zoom selection box.
setSelectionBorderColor | (Self) | Sets the border color of the zoom selection box as an HTML color.
getSelectionBorderColor | (Self) | Gets the border color of the zoom selection box.
setZoomInCursor | (Self) | Sets the mouse cursor to be used when the mouse is used for zoom in.
getZoomInCursor | (Self) | Gets the mouse cursor to be used when the mouse is used for zoom in.
setZoomOutCursor | (Self) | Sets the mouse cursor to be used when the mouse is used for zoom out.
getZoomOutCursor | (Self) | Gets the mouse cursor to be used when the mouse is used for zoom out.
setNoZoomCursor | (Self) | Sets the mouse cursor to be used when the mouse is used for zoom in/out, but the zoom in/out limits has been reached.
getNoZoomCursor | (Self) | Gets the mouse cursor to be used when the mouse is used for zoom in/out, but the zoom in/out limits has been reached.
setScrollCursor | (Self) | Sets the mouse cursor to be used when the mouse is used for scrolling.
getScrollCursor | (Self) | Gets the mouse cursor to be used when the mouse is used for scrolling.
setCustomAttr | (Self) | Sets a custom attribute.
getCustomAttr | (Self) | Gets a custom attribute.


WebChartViewer.WebChartViewer

WebChartViewer.WebChartViewer

Usage

WebChartViewer(pageContext, id)

Description

Creates a new WebChartViewer object.

Note: In the ColdFusion edition of ChartDirector, the WebChartViewer constructor is implemented as a method of the ChartDirector.CFChart object called ChartDirector.CFChart.WebChartViewer.

Arguments

Argument | Default | Description
pageContext | (Mandatory) | The PageContext object representing the current web page. This is typically obtained by using the ColdFusion "GetPageContext" function.
id | (Mandatory) | The id of the WebChartViewer, which is also be used as the id attribute of the <IMG> tag for displaying the chart. It should start with A-Z, a-z or underscore, and consists entirely of alphanumeric characters with no spaces

Return Value

The WebChartViewer object created.


WebChartViewer.getId

WebChartViewer.getId

Usage

getId()

Description

Gets the id of the WebChartViewer object.

Arguments

None

Return Value

The id of the WebChartViewer object.


WebChartViewer.setImageUrl

WebChartViewer.setImageUrl

Usage

setImageUrl(url)

Description

Sets the URL used by the <IMG> tag to load the chart image.

Arguments

Argument | Default | Description
url | (Mandatory) | The URL used by the <IMG> tag to load the chart image.

Return Value

None


WebChartViewer.getImageUrl

WebChartViewer.getImageUrl

Usage

getImageUrl()

Description

Gets the URL used by the <IMG> tag to load the chart image.

Arguments

None

Return Value

The URL used by the <IMG> tag to load the chart image.


WebChartViewer.setImageMap

WebChartViewer.setImageMap

Usage

setImageMap(imageMap)

Description

Sets the image map associated with the chart.

The image map defines "hot spots" on the chart that may have tool tips, becomes clickable and responses to other mouse events.

The WebChartViewer control expects the image map to be in HTML image map format comprising of <AREA> tags only. No <MAP> tag should be included in the image map as the WebChartViewer control will generate the <MAP> tag automatically to match with the <IMG> tag.

The image map for a chart can be generated automatically by using BaseChart.getHTMLImageMap.

This property can also accept an URL to a delayed image map generated by WebChartViewer.makeDelayedMap.

Arguments

Argument | Default | Description
imageMap | (Mandatory) | The image map associated with the chart.

Return Value

None


WebChartViewer.getImageMap

WebChartViewer.getImageMap

Usage

getImageMap()

Description

Gets the image map associated with the chart.

The method returns the same value set by a previous call to WebChartViewer.setImageMap.

Arguments

None

Return Value

The image map associated with the chart.


WebChartViewer.setChartMetrics

WebChartViewer.setChartMetrics

Usage

setChartMetrics(metrics)

Description

Sets the chart metrics of the chart.

The chart metrics is represented by a text string. It must be generated by BaseChart.getChartMetrics. The internal format of the chart metrics are not published.

The WebChartViewer sends the chart metrics to the browser side JsChartViewer so it knows the location of the plot area for supporting view port mouse actions.

Arguments

Argument | Default | Description
metrics | (Mandatory) | A text string obtained from BaseChart.getChartMetrics that represents the metrics of the chart.

Return Value

None


WebChartViewer.getChartMetrics

WebChartViewer.getChartMetrics

Usage

getChartMetrics()

Description

Gets the chart metrics of the chart.

The method returns the same value set by a previous call to WebChartViewer.setChartMetrics.

Arguments

None

Return Value

A text string representing the chart metrics of the chart.


WebChartViewer.makeDelayedMap

WebChartViewer.makeDelayedMap

Usage

makeDelayedMap(imageMap [, compress ])

Description

Creates a delayed image map suitable for use in JsChartViewer.

Normally, for any web page with an image and an image map, the server will send the HTML part of the page to the browser first, which contains the <IMG> tag and the image map (<MAP> and <AREA> tags). The browser, after receiving the HTML, will use the URL in the <IMG> tag to get the image. That means the image map is delivered before the image.

For charts that have a lot of data points, the size of the image map can become significant. For example, a chart with 1000 hot spots, each with a tool tips text and clickable, can easily mean an image map of the order of 100 Kbytes (around 100 bytes per hot spot). Including the image map in the HTML may slow down loading of the web page and loading of the image.

The delayed image map is a new kind of image map delivery method. The image map is not included in the HTML web page, but instead is delivered by AJAX means after the HTML web page and the image are delivered. In this way, the entire web page can be displayed faster, with image map features (like tool tips) available later.

Another advantage of delayed image map is that it can be independently compressed.

Virtually all browsers today supports HTTP compressed web pages. Some web servers are configured to apply HTTP compression to web pages, but most servers nowadays are not configured to use HTTP compression at all.

On the other hand, image maps are usually very compressible. It is common to see compression ratio of the order of 10x (so 100 Kbytes will become 10 Kbytes). If your web server do not already compress HTTP contents, you may ask WebChartViewer to compress the delayed image map. The WebChartViewer will then check if the browser can support HTTP compression (by examining the HTTP headers sent from the browser), and compress the image map if the browser supports it.

In deciding whether to use delayed image map or not, one should compare the advantages of using delayed image map with the disadvantages:

Advantages | Disadvantages
The HTML web page and the image will display faster, because no image map is including in the HTML web page. | Server loading is increased because it needs to create the delayed image map, and to service an additional AJAX request for delayed image map delivery. Also, image map features may not be immediately available when the content is displayed.
Image map compression may further improve network performance. | Image map compression will increase server CPU loading.

In general, if the browser to server connection is high speed (like in an intranet), or if the image map is not large compared to the network bandwidth, it is not necessary to use delayed image map.

On the other hand, if the browser to server connection can be low speed (like in locations where broadband is not common), and the image map is large compared to the network bandwidth, and it is acceptable to have the image map not immediately available when the content is displayed, then the delayed image map feature will be useful.

Because the delayed image map will be retrieved by the browser from a separate HTTP connection, it needs to be stored in some place that can persist across HTTP connections.

The makeDelayedMap method stores the delayed image map in a session variable, and returns a query string so that the delayed image map can be retrieved later using "getchart.cfm". The URL for retrieving the delayed image map should be passed to WebChartViewer.setImageMap for transferring to the browser. For example:

Note that the above assumes the "getchart.cfm" is located in the same directory as the web page. If it is in a different directory, you would need to modify the path to "getchart.cfm".

Arguments

Argument | Default | Description
imageMap | (Mandatory) | The image map to be converted to a delayed image map.
compress | false | Use HTTP compression if the browser supports it.

Return Value

A string representing the query parameters for retrieving the delayed image map using the "getchart.cfm" utility.


WebChartViewer.renderHTML

WebChartViewer.renderHTML

Usage

renderHTML(pageContext [, extraAttrs ])

Description

Generates the HTML tags necessary to represent the chart, image map, and the JsChartViewer state.

The generated tags may include an <IMG> tag, image map tags, and hidden fields. Additional attributes may be included in the <IMG> by using the extraAttrs argument. Any text in extraAttrs will be inserted into the <IMG> tag as is.

Arguments

Argument | Default | Description
pageContext | (Mandatory) | The PageContext object representing the current web page. This is typically obtained by using the ColdFusion "GetPageContext" function.
extraAttrs | "" | Extra attributes to be included in the <IMG> tag.

Return Value

A text string containing the HTML tags necessary to represent the chart, image map, and the JsChartViewer state


WebChartViewer.partialUpdateChart

WebChartViewer.partialUpdateChart

Usage

partialUpdateChart(pageContext [, msg [, timeout ]])

Description

Sends the response to a partial chart update request.

The response can optionally cause a message to pop up on the chart on the browser side. This is useful for displaying error messages or other information to the user. The pop up message may automatically hide after a certain time. An OK button may also be put on the message to allow the user to dismiss it.

Arguments

Argument | Default | Description
pageContext | (Mandatory) | The PageContext object representing the current web page. This is typically obtained by using the ColdFusion "GetPageContext" function.
msg | "" | A pop up message to be displayed on the chart. The default value of an empty string means no pop up message will be displayed.
timeout | 0 | The delay time in milliseconds, after which the pop up message will automatically hide. If a negative number is used, the delay time is set as the absolute value. In addition, there will be an OK button to allow the user to dismiss the message. Use a very large negative number to show the message until the user press OK. The default value of 0 means the pop up message will stay until the chart refreshes.

Return Value

None


WebChartViewer.isPartialUpdateRequest

WebChartViewer.isPartialUpdateRequest

Usage

isPartialUpdateRequest()

Description

Checks if the current HTTP Request is a partial update request (AJAX request) sent using JsChartViewer.partialUpdate.

Note that the JsChartViewer does not need to have the same id as the WebChartViewer object. To get the id of the JsChartViewer object sending the request, use WebChartViewer.getSenderClientId.

Arguments

None

Return Value

True if the current HTTP request is a partial update request (AJAX request) sent using JsChartViewer.partialUpdate, otherwise false.


WebChartViewer.isFullUpdateRequest

WebChartViewer.isFullUpdateRequest

Usage

isFullUpdateRequest()

Description

Checks if the current HTTP request is a full update request containing information from a JsChartViewer.

A full update request does not necessarily come from a JsChartViewer. For example, a submit button in an HTML FORM can trigger an HTTP request. These kind of requests may contain information from JsChartViewer objects, which are stored as hidden fields in the FORM.

Any HTTP request that is not a partial update request (see WebChartViewer.isPartialUpdateRequest) but contains information from a JsChartViewer will meet the criteria of this method.

Arguments

None

Return Value

True if the current HTTP request is a full update request containing information from a JsChartViewer, otherwise false.


WebChartViewer.isStreamRequest

WebChartViewer.isStreamRequest

Usage

isStreamRequest()

Description

Checks if the current HTTP request is a stream update request sent using JsChartViewer.streamUpdate.

Note that the JsChartViewer does not need to have the same id as the WebChartViewer object. To get the id of the JsChartViewer object sending the request, use WebChartViewer.getSenderClientId.

Arguments

None

Return Value

True if the current HTTP request is stream update request sent using JsChartViewer.streamUpdate, otherwise false.


WebChartViewer.isViewPortChangedEvent

WebChartViewer.isViewPortChangedEvent

Usage

isViewPortChangedEvent()

Description

Checks if the JsChartViewer.ViewPortChanged event has occurred.

When mouse actions (such as drag to scroll, drag to select region to zoom into, click to zoom in/out, etc) occurs on the browser side, the JsChartViewer.ViewPortChanged event will occur. Typically, the event handler will send either a partial chart update request (AJAX request) or a full page update request to the server.

However, in a typical web page, there may be other causes of a partial chart update request or full page update request. For example, for a time based chart, the web page may have a FORM to allow the user to enter the start date and end date used, and then press the submit button.

This method determines if the JsChartViewer.ViewPortChanged event has occurred, so as to identify if it is the cause of the HTTP request.

Arguments

None

Return Value

True if the JsChartViewer.ViewPortChanged event has occurred, otherwise false.


WebChartViewer.getSenderClientId

WebChartViewer.getSenderClientId

Usage

getSenderClientId()

Description

Gets the id of the JsChartViewer that sends the current HTTP request.

This method is applicable only if either WebChartViewer.isPartialUpdateRequest or WebChartViewer.isStreamRequest is true.

Arguments

None

Return Value

The id of the JsChartViewer, which is the same as the id attribute of the <IMG> tag that displays the chart.


WebChartViewer.setViewPortLeft

WebChartViewer.setViewPortLeft

Usage

setViewPortLeft(left)

Description

Sets the position of the left side of the view port.

The position of the view port left side is its distance from the left side of the underlying surface, as a fraction of the width of the underlying surface. It should be between 0 and 1.

Arguments

Argument | Default | Description
left | (Mandatory) | The position of the left side of the view port.

Return Value

None


WebChartViewer.getViewPortLeft

WebChartViewer.getViewPortLeft

Usage

getViewPortLeft()

Description

Gets the position of the left side of the view port.

The position of the view port left side is its distance from the left side of the underlying surface, as a fraction of the width of the underlying surface. It should be between 0 and 1.

Arguments

None

Return Value

The position of the left side of the view port.


WebChartViewer.setViewPortTop

WebChartViewer.setViewPortTop

Usage

setViewPortTop(top)

Description

Sets the position of the top side of the view port.

The position of the view port top side is its distance from the top side of the underlying surface, as a fraction of the height of the underlying surface. It should be between 0 and 1.

Arguments

Argument | Default | Description
top | (Mandatory) | The position of the top side of the view port.

Return Value

None


WebChartViewer.getViewPortTop

WebChartViewer.getViewPortTop

Usage

getViewPortTop()

Description

Gets the position of the top side of the view port.

The position of the view port top side is its distance from the top side of the underlying surface, as a fraction of the height of the underlying surface. It should be between 0 and 1.

Arguments

None

Return Value

The position of the top side of the view port.


WebChartViewer.setViewPortWidth

WebChartViewer.setViewPortWidth

Usage

setViewPortWidth(width)

Description

Sets the width of the view port.

The view port width is expressed as a fraction of the width of the underlying surface. It should be between 0 and 1.

Arguments

Argument | Default | Description
width | (Mandatory) | The width of the view port.

Return Value

None


WebChartViewer.getViewPortWidth

WebChartViewer.getViewPortWidth

Usage

getViewPortWidth()

Description

Gets the width of the view port.

The view port width is expressed as a fraction of the width of the underlying surface. It should be between 0 and 1.

Arguments

None

Return Value

The width of the view port.


WebChartViewer.setViewPortHeight

WebChartViewer.setViewPortHeight

Usage

setViewPortHeight(height)

Description

Sets the height of the view port.

The view port height is expressed as a fraction of the height of the underlying surface. It should be between 0 and 1.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the view port.

Return Value

None


WebChartViewer.getViewPortHeight

WebChartViewer.getViewPortHeight

Usage

getViewPortHeight()

Description

Gets the height of the view port.

The view port height is expressed as a fraction of the height of the underlying surface. It should be between 0 and 1.

Arguments

None

Return Value

The height of the view port.


WebChartViewer.setMouseUsage

WebChartViewer.setMouseUsage

Usage

setMouseUsage(mouseUsage)

Description

Sets the mouse usage mode of the control.

The following table describes the supported mouse usage modes and the mouse behaviour in each mode.

Constant Value Description
MouseUsageDefault0This represents the default mouse behaviour, which is to support tool tips and hot spot events as defined by the image map.

See BaseChart.getHTMLImageMap on how to define an image map for a chart.
MouseUsageScroll2The mouse is used for drag scrolling the chart.

When the mouse drags on the plot area, the mouse cursor will change to a scroll cursor, and a selection rectangle representing the shifted plot area will be displayed to reflect the amount dragged. When the mouse is released, the view port coordinates will be updated to reflect the amount dragged, and a JsChartViewer.ViewPortChanged event will be fired.

If the mouse is not dragging inside the plot area, its behaviour is the same as the default mouse behaviour.
MouseUsageZoomIn3The mouse is used for zoom in actions.

When the mouse is inside the plot area, the following behaviour will apply:

  • The mouse cursor will change to a zoom in cursor (a magnifying glass cursor with a '+' sign inside).

  • When the mouse drags on the plot area, a selection rectangle will be visible. When the mouse button is subsequently released, the view port coordinates will be updated to reflect the selection rectangle, and a JsChartViewer.ViewPortChanged event will be fired.

  • When the mouse clicks on the plot area without dragging, the view port will be updated to reflect zooming into the clicked point by a ratio specified in WebChartViewer.setZoomInRatio, and a JsChartViewer.ViewPortChanged event will be fired.
If the mouse is not inside the plot area, its behaviour is the same as the default mouse behaviour.
MouseUsageZoomOut4The mouse is used for zoom out actions.

When the mouse is inside the plot area, the following behaviour will apply:

  • The mouse cursor will change to a zoom out cursor (a magnifying glass cursor with a '-' sign inside).

  • When the mouse clicks on the plot area , the view port will be updated to reflect zooming out from the clicked point by a ratio specified in WebChartViewer.setZoomOutRatio, and a JsChartViewer.ViewPortChanged event will be fired.
If the mouse is not inside the plot area, its behaviour is the same as the default mouse behaviour.

Note: It is known that mouse cursors for scrolling and zooming work on IE 6.0 or above, and FireFox. Due to the different capabilities of the various browsers, the mouse cursors may or may not appear in other browsers.

Arguments

Argument | Default | Description
mouseUsage | (Mandatory) | The mouse usage mode of the control, which must be one of the predefined constants as shown in the table above.

Return Value

None


WebChartViewer.getMouseUsage

WebChartViewer.getMouseUsage

Usage

getMouseUsage()

Description

Gets the mouse usage mode of the control.

Arguments

None

Return Value

An integer representing the mouse usage mode. See WebChartViewer.setMouseUsage for the meaning of this value.


WebChartViewer.setZoomDirection

WebChartViewer.setZoomDirection

Usage

setZoomDirection(direction)

Description

Sets the zoom direction for mouse zoom in/out actions.

In zoom operations for charts, it is common to restrict zooming to one direction only. For example, in a chart plotting temperature against time, zooming in from a yearly chart to a daily chart may mean the time axis (x-axis) is zoomed in by 36500%, while the temperature axis (y-axis) may be auto-scaled and not zoomed in at all. The user may be surprise if you also zoom in the y-axis by 36500%, in which case the chart may become hardly readable.

This method allows you to determine the zoom direction for mouse zoom actions (see WebChartViewer.setMouseUsage), specified using the following predefined constants:

Constant | Value | Description
DirectionHorizontal | 0 | Zoom actions apply to horizontal direction only.
DirectionVertical | 1 | Zoom actions apply to vertical direction only.
DirectionHorizontalVertical | 2 | Zoom actions apply to both horizontal and vertical directions.

Arguments

Argument | Default | Description
direction | (Mandatory) | The zoom direction for mouse zoom actions.

Return Value

None


WebChartViewer.getZoomDirection

WebChartViewer.getZoomDirection

Usage

getZoomDirection()

Description

Gets the zoom direction for mouse zoom in/out actions.

Please refer to WebChartViewer.setZoomDirection for the supported directions.

Arguments

None

Return Value

An integer representing the zoom direction.


WebChartViewer.setScrollDirection

WebChartViewer.setScrollDirection

Usage

setScrollDirection(direction)

Description

Sets the scroll direction for mouse scroll actions.

Please refer to WebChartViewer.setZoomDirection for the supported directions.

Arguments

Argument | Default | Description
direction | (Mandatory) | The scroll direction for mouse scroll actions.

Return Value

None


WebChartViewer.getScrollDirection

WebChartViewer.getScrollDirection

Usage

getScrollDirection()

Description

Gets the scroll direction for mouse scroll actions.

Please refer to WebChartViewer.setZoomDirection for the supported directions.

Arguments

None

Return Value

An integer representing the scroll direction.


WebChartViewer.setZoomInRatio

WebChartViewer.setZoomInRatio

Usage

setZoomInRatio(ratio)

Description

Sets the magnification ratio for each zoom in click of the mouse.

For zoom in, the ratio should be greater than 1. The default is 2.

Arguments

Argument | Default | Description
ratio | (Mandatory) | The zoom in ratio.

Return Value

None


WebChartViewer.getZoomInRatio

WebChartViewer.getZoomInRatio

Usage

getZoomInRatio()

Description

Gets the magnification ratio for each zoom in click of the mouse.

For zoom in, the ratio should be greater than 1. The default is 2.

Arguments

None

Return Value

The magnification ratio.


WebChartViewer.setZoomOutRatio

WebChartViewer.setZoomOutRatio

Usage

setZoomOutRatio(ratio)

Description

Sets the magnification ratio for each zoom out click of the mouse.

For zoom out, the ratio should be less than 1. The default is 0.5.

Arguments

Argument | Default | Description
ratio | (Mandatory) | The zoom out ratio.

Return Value

None


WebChartViewer.getZoomOutRatio

WebChartViewer.getZoomOutRatio

Usage

getZoomOutRatio()

Description

Gets the magnification ratio for each zoom out click of the mouse.

For zoom out, the ratio should be less than 1. The default is 0.5.

Arguments

None

Return Value

The magnification ratio.


WebChartViewer.setZoomInWidthLimit

WebChartViewer.setZoomInWidthLimit

Usage

setZoomInWidthLimit(width)

Description

Sets the view port width at maximum zoom in.

In many applications, it is desirable to set a maximum zoom in level, instead of allowing the user to zoom in indefinitely.

This method determines the minimum allowed view port width. It should be between 0 and 1. The default is 0.01, which means a maximum zoom in of 100x (the view port see only 1% of the underlying surface).

Arguments

Argument | Default | Description
width | (Mandatory) | The minimum allowed view port width.

Return Value

None


WebChartViewer.getZoomInWidthLimit

WebChartViewer.getZoomInWidthLimit

Usage

getZoomInWidthLimit()

Description

Gets the view port width at maximum zoom in for mouse zoom in actions.

Arguments

None

Return Value

The view port width at maximum zoom in. See WebChartViewer.setZoomInWidthLimit for the meaning of this value.


WebChartViewer.setZoomOutWidthLimit

WebChartViewer.setZoomOutWidthLimit

Usage

setZoomOutWidthLimit(width)

Description

Sets the view port width at maximum zoom out.

This method determines the maximum allowed view port width. It should be between 0 and 1. The default is 1, which means at maximum zoom out, the view port width will cover the entire underlying surface.

Arguments

Argument | Default | Description
width | (Mandatory) | The maximum allowed view port width.

Return Value

None


WebChartViewer.getZoomOutWidthLimit

WebChartViewer.getZoomOutWidthLimit

Usage

getZoomOutWidthLimit()

Description

Gets the view port width at maximum zoom out for mouse zoom out actions.

Arguments

None

Return Value

The view port width at maximum zoom out. See WebChartViewer.setZoomOutWidthLimit for the meaning of this value.


WebChartViewer.setZoomInHeightLimit

WebChartViewer.setZoomInHeightLimit

Usage

setZoomInHeightLimit(height)

Description

Sets the view port height at maximum zoom in.

In many applications, it is desirable to set a maximum zoom in level, instead of allowing the user to zoom in indefinitely.

This method determines the minimum allowed view port height. It should be between 0 and 1. The default is 0.01, which means a maximum zoom in of 100x (the view port see only 1% of the underlying surface).

Arguments

Argument | Default | Description
height | (Mandatory) | The minimum allowed view port height.

Return Value

None


WebChartViewer.getZoomInHeightLimit

WebChartViewer.getZoomInHeightLimit

Usage

getZoomInHeightLimit()

Description

Gets the view port height at maximum zoom in for mouse zoom in actions.

Arguments

None

Return Value

The view port height at maximum zoom in. See WebChartViewer.setZoomInHeightLimit for the meaning of this value.


WebChartViewer.setZoomOutHeightLimit

WebChartViewer.setZoomOutHeightLimit

Usage

setZoomOutHeightLimit(height)

Description

Sets the view port height at maximum zoom out.

This method determines the maximum allowed view port height. It should be between 0 and 1. The default is 1, which means at maximum zoom out, the view port height will cover the entire underlying surface.

Arguments

Argument | Default | Description
height | (Mandatory) | The maximum allowed view port height.

Return Value

None


WebChartViewer.getZoomOutHeightLimit

WebChartViewer.getZoomOutHeightLimit

Usage

getZoomOutHeightLimit()

Description

Gets the view port height at maximum zoom out for mouse zoom out actions.

Arguments

None

Return Value

The view port height at maximum zoom out. See WebChartViewer.setZoomOutHeightLimit for the meaning of this value.


WebChartViewer.setMinimumDrag

WebChartViewer.setMinimumDrag

Usage

setMinimumDrag(offset)

Description

Sets the minimum mouse drag distance before it is considered as an intentional drag.

A mouse drag occurs if the mouse button is down while the mouse moves. However, sometimes a user may want to click on a point, but due to mouse vibrations, the mouse moves by a small amount while the button is still down. This may then be interpreted as a mouse drag.

This method determines the minimum drag distance in pixels before it is considered as an intentional drag. The default is 5 pixels. Non-intentional drags will be handled as mouse clicks instead of drags.

Arguments

Argument | Default | Description
offset | (Mandatory) | The minimum mouse drag distance in pixels before it is considered as an intentional drag.

Return Value

None


WebChartViewer.getMinimumDrag

WebChartViewer.getMinimumDrag

Usage

getMinimumDrag()

Description

Gets the minimum mouse drag distance before it is considered as an intentional drag.

Arguments

None

Return Value

The minimum mouse drag distance in pixels before it is considered as an intentional drag. See WebChartViewer.setMinimumDrag for the meaning of this value.


WebChartViewer.setSelectionBorderWidth

WebChartViewer.setSelectionBorderWidth

Usage

setSelectionBorderWidth(width)

Description

Sets the border width of the zoom selection box.

Arguments

Argument | Default | Description
width | (Mandatory) | The border width in pixels.

Return Value

None


WebChartViewer.getSelectionBorderWidth

WebChartViewer.getSelectionBorderWidth

Usage

getSelectionBorderWidth()

Description

Gets the border width of the zoom selection box.

Arguments

None

Return Value

The border width of the zoom selection box in pixels.


WebChartViewer.setSelectionBorderColor

WebChartViewer.setSelectionBorderColor

Usage

setSelectionBorderColor(color)

Description

Sets the border color of the zoom selection box as an HTML color.

Arguments

Argument | Default | Description
color | (Mandatory) | The border color as an HTML color.

Return Value

None


WebChartViewer.getSelectionBorderColor

WebChartViewer.getSelectionBorderColor

Usage

getSelectionBorderColor()

Description

Gets the border color of the zoom selection box.

Arguments

None

Return Value

The border color of the zoom selection box as an HTML color.


WebChartViewer.setZoomInCursor

WebChartViewer.setZoomInCursor

Usage

setZoomInCursor(cursor)

Description

Sets the mouse cursor to be used when the mouse is used for zoom in.

The cursor should be specified in the format used in CSS (Cascaded Style Sheet) cursor attributes.

Arguments

Argument | Default | Description
cursor | (Mandatory) | The mouse cursor to be used when the mouse is used for zoom in.

Return Value

None


WebChartViewer.getZoomInCursor

WebChartViewer.getZoomInCursor

Usage

getZoomInCursor()

Description

Gets the mouse cursor to be used when the mouse is used for zoom in.

Arguments

None

Return Value

The mouse cursor to be used when the mouse is used for zoom in.


WebChartViewer.setZoomOutCursor

WebChartViewer.setZoomOutCursor

Usage

setZoomOutCursor(cursor)

Description

Sets the mouse cursor to be used when the mouse is used for zoom out.

The cursor should be specified in the format used in CSS (Cascaded Style Sheet) cursor attributes.

Arguments

Argument | Default | Description
cursor | (Mandatory) | The mouse cursor to be used when the mouse is used for zoom out.

Return Value

None


WebChartViewer.getZoomOutCursor

WebChartViewer.getZoomOutCursor

Usage

getZoomOutCursor()

Description

Gets the mouse cursor to be used when the mouse is used for zoom out.

Arguments

None

Return Value

The mouse cursor to be used when the mouse is used for zoom out.


WebChartViewer.setNoZoomCursor

WebChartViewer.setNoZoomCursor

Usage

setNoZoomCursor(cursor)

Description

Sets the mouse cursor to be used when the mouse is used for zoom in/out, but the zoom in/out limits has been reached.

The cursor should be specified in the format used in CSS (Cascaded Style Sheet) cursor attributes.

Arguments

Argument | Default | Description
cursor | (Mandatory) | The mouse cursor to be used when the mouse is used for zoom in/out, but the zoom in/out limits has been reached.

Return Value

None


WebChartViewer.getNoZoomCursor

WebChartViewer.getNoZoomCursor

Usage

getNoZoomCursor()

Description

Gets the mouse cursor to be used when the mouse is used for zoom in/out, but the zoom in/out limits has been reached.

Arguments

None

Return Value

The mouse cursor to be used when the mouse is used for zoom in/out, but the zoom in/out limits has been reached.


WebChartViewer.setScrollCursor

WebChartViewer.setScrollCursor

Usage

setScrollCursor(cursor)

Description

Sets the mouse cursor to be used when the mouse is used for scrolling.

The cursor should be specified in the format used in CSS (Cascaded Style Sheet) cursor attributes.

Arguments

Argument | Default | Description
cursor | (Mandatory) | The mouse cursor to be used when the mouse is used for scrolling.

Return Value

None


WebChartViewer.getScrollCursor

WebChartViewer.getScrollCursor

Usage

getScrollCursor()

Description

Gets the mouse cursor to be used when the mouse is used for scrolling.

Arguments

None

Return Value

The mouse cursor to be used when the mouse is used for scrolling.


WebChartViewer.setCustomAttr

WebChartViewer.setCustomAttr

Usage

setCustomAttr(key, value)

Description

Sets a custom attribute.

The WebChartViewer does not interpret or use custom attributes. It merely sends them to the browser side JsChartViewer control. On the browser side, these attributes can be retrieved using JsChartViewer.getCustomAttr.

Custom attributes are useful for transferring application specific information between the server and the browser during partial chart updates (AJAX requests). They are also useful for storing values that needs to be persistent across multiple HTTP requests.

For example, one can use custom attributes to pass the values of browser side HTML controls to the server. (For non-AJAX requests, one can always use FORM POST or GET to pass information to the server.)

Both the key and value of a custom attribute should be text strings. The key should be a valid variable name, that is, it should start with A-Z, a-z or underscore, and consists entirely of alphanumeric characters with no spaces.

Arguments

Argument | Default | Description
key | (Mandatory) | The attribute key.
value | (Mandatory) | The attribute value.

Return Value

None


WebChartViewer.getCustomAttr

WebChartViewer.getCustomAttr

Usage

getCustomAttr(key)

Description

Gets a custom attribute.

The WebChartViewer does not interpret or use custom attributes. It merely receives them from the browser side JsChartViewer control. On the browser side, these attributes are set using JsChartViewer.setCustomAttr.

Custom attributes are useful for transferring application specific information between the server and the browser during partial chart updates (AJAX requests).

For example, one one can use custom attributes to update the states of the HTML controls on the browser side during partial chart updates. (For non-AJAX requests, the server can always update the web page directly.)

Both the key and value of a custom attribute should be text strings. The key should be a valid variable name, that is, it should start with A-Z, a-z or underscore, and consists entirely of alphanumeric characters with no spaces.

Arguments

Argument | Default | Description
key | (Mandatory) | The attribute key.

Return Value

The value of the required attribute.


JsChartViewer

JsChartViewer

JsChartViewer is a browser side Javascript control for supporting advanced chart user interactions. Its main functions are:

  • Provide user interface support for drag to scroll, drag to select zoom in region, and click to zoom in/out.

  • Allow external controls to scroll and zoom the chart and requesting chart updates.

  • Provide AJAX support for chart updates.

  • Provide support for delayed and compressed image map.

In many applications, the JsChartViewer needs to be used with the WebChartViewer on the server side. For example, when JsChartViewer sends a partial chart update request (AJAX request) to the server, the server needs to use a WebChartViewer to interpret the request and to send back the result.

To use JsChartViewer in a web page, it is necessary to include the "cdjcv.js" Javascript library in the HTML code. Typically, this is achieved by inserting a script block in the <HEAD> section of the HTML code:

    <SCRIPT SRC="/path/to/cdjcv.js">

Note: Please replace "/path/to" above to the actual path you put the "cdjcv.js" to.

The "cdjcv.js" requires the following files, which must be located in the same directory as "cdjcv.js".

Filename | Description
cdjcv.js | The main Javascript library file.
zoomin.cur | Zoom in cursor.
zoomin.cur | Zoom out cursor.
nozoom.cur | No zoom cursor.
wait.gif | Rotating clock wait symbol.

During operation, "cdjcv.js" will detect the absolute URL of itself, and use it to load other files in the above table. (It cannot use relative URL, because the URL will be relative to the containing HTML web page, which may or may not be in the same directory as "cdjcv.js".) However, in some cases, you may want to explicitly specify the path for "cdjcv.js" to use. This can be by defining a global Javascript variable "cdjcv_path" that contains the URL directory that contains the files.

To create a JsChartViewer object, one should use the JsChartViewer.get method instead of using the "new" statement. The JsChartViewer.get method creates a JsChartViewer object and binds it the an <IMG> tag for displaying the chart.

JsChartViewer stores its state in a hidden field created by WebChartViewer.renderHTML. This allows a JsChartViewer object to transfer information to WebChartViewer on the server side using standard FORM POST or GET. This is useful for browsers that do not support partial chart update request (AJAX request). to enable using FORM POST or GET, one should include a HTML FORM in the web page, and the FORM should include the <IMG> tag associated with the JsChartViewer object.

JsChartViewer is designed to work with IE 4.0 or above, or any W3C DOM compliant browsers. However, as there are thousands of browser/version combinations in the market, it is practically impossible to test all of them. The followings are the browsers that have been tested as of the date this paragraph is written:

  • IE 4.0
  • IE 5.0
  • IE 5.5
  • IE 6.0
  • FireFox 1.0.3
  • FireFox 1.5
  • Opera 8.0
  • Safari 1.2.3
  • Safari 2.0.3
JsChartViewer is designed to remain silent during loading (no error message will pop up) on older browsers or non-DOM compliant browsers.

Properties
Name | Description
updatingMsg | Gets or sets the HTML message displayed when partial chart update is in progress.
serverErrorMsg | Gets or sets the HTML template for displaying server error messages.
msgContainer | Gets or sets the default message container template.
okButton | Gets or sets the "OK" button for closing the chart message window.
xButton | Gets or sets the "X" button for closing the chart message window.

Methods
Name | Description
get | Gets a JsChartViewer object that binds to the given <IMG> tag for chart display.
getId | Gets the id of the JsChartViewer.
setViewPortLeft | Sets the position of the left side of the view port.
getViewPortLeft | Gets the position of the left side of the view port.
setViewPortTop | Sets the position of the top side of the view port.
getViewPortTop | Gets the position of the top side of the view port.
setViewPortWidth | Sets the width of the view port.
getViewPortWidth | Gets the width of the view port.
setViewPortHeight | Sets the height of the view port.
getViewPortHeight | Gets the height of the view port.
setMouseUsage | Sets the mouse usage mode of the control.
getMouseUsage | Gets the mouse usage mode of the control.
setZoomDirection | Sets the zoom direction for mouse zoom in/out actions.
getZoomDirection | Gets the zoom direction for mouse zoom in/out actions.
setScrollDirection | Sets the scroll direction for mouse scroll actions.
getScrollDirection | Gets the scroll direction for mouse scroll actions.
setZoomInRatio | Sets the magnification ratio for each zoom in click of the mouse.
getZoomInRatio | Gets the magnification ratio for each zoom in click of the mouse.
setZoomOutRatio | Sets the magnification ratio for each zoom out click of the mouse.
getZoomOutRatio | Gets the magnification ratio for each zoom out click of the mouse.
setZoomInWidthLimit | Sets the view port width at maximum zoom in.
getZoomInWidthLimit | Gets the view port width at maximum zoom in for mouse zoom in actions.
setZoomOutWidthLimit | Sets the view port width at maximum zoom out.
getZoomOutWidthLimit | Gets the view port width at maximum zoom out for mouse zoom out actions.
setZoomInHeightLimit | Sets the view port height at maximum zoom in.
getZoomInHeightLimit | Gets the view port height at maximum zoom in for mouse zoom in actions.
setZoomOutHeightLimit | Sets the view port height at maximum zoom out.
getZoomOutHeightLimit | Gets the view port height at maximum zoom out for mouse zoom out actions.
setMinimumDrag | Sets the minimum mouse drag distance before it is considered as an intentional drag.
getMinimumDrag | Gets the minimum mouse drag distance before it is considered as an intentional drag.
setSelectionBorderWidth | Sets the border width of the zoom selection box.
getSelectionBorderWidth | Gets the border width of the zoom selection box.
setSelectionBorderColor | Sets the border color of the zoom selection box as an HTML color.
getSelectionBorderColor | Gets the border color of the zoom selection box.
setZoomInCursor | Sets the mouse cursor to be used when the mouse is used for zoom in.
getZoomInCursor | Gets the mouse cursor to be used when the mouse is used for zoom in.
setZoomOutCursor | Sets the mouse cursor to be used when the mouse is used for zoom out.
getZoomOutCursor | Gets the mouse cursor to be used when the mouse is used for zoom out.
setNoZoomCursor | Sets the mouse cursor to be used when the mouse is used for zoom in/out, but the zoom in/out limits has been reached.
getNoZoomCursor | Gets the mouse cursor to be used when the mouse is used for zoom in/out, but the zoom in/out limits has been reached.
setScrollCursor | Sets the mouse cursor to be used when the mouse is used for scrolling.
getScrollCursor | Gets the mouse cursor to be used when the mouse is used for scrolling.
setCustomAttr | Sets a custom attribute.
getCustomAttr | Gets a custom attribute.
canSupportPartialUpdate | Checks if the browser is capable of supporting partial chart updates (AJAX requests).
partialUpdate | Sends a partial update request (AJAX request) to the server.
streamUpdate | Refreshes the <IMG> that the JsChartViewer is bound to.
attachHandler | Attaches a function to be used as the event handler for an event.
detachHandler | Detaches a function from being an event handler for an event.
applyHandlers | Calls the handlers for an event.

Events
Name | Description
ViewPortChanged | This event occurs when the view port is changed through mouse actions (see JsChartViewer.setMouseUsage).
PreUpdate | This event occurs immediately before a partial chart update request is sent to the server (see JsChartViewer.partialUpdate).
PostUpdate | This event occurs after a partial update response is received from the server and is processed successfully.
UpdateError | This event occurs if an error occurs in during a partial update.


JsChartViewer.get

JsChartViewer.get

Usage

get(id)

Description

Gets a JsChartViewer object that binds to the given <IMG> tag for chart display.

Note: This method is a static method (class method). It should be accessed as JsChartViewer.get, not objName.get. For example:

    var obj = JsChartViewer.get("abc");

The id argument specifies the id attribute of the <IMG> tag that the JsChartViewer binds to. If no such JsChartViewer exists, a new JsChartViewer will be created.

The id is also used as the id of the JsChartViewer itself for communications with the server side WebChartViewer.

Arguments

Argument | Default | Description
id | (Mandatory) | The id of the <IMG> tag that the JsChartViewer binds to, which is the same as the id of the JsChartViewer itself.

Return Value

A JsChartViewer object that binds to the <IMG> tag.


JsChartViewer.getId

JsChartViewer.getId

Usage

getId()

Description

Gets the id of the JsChartViewer.

Arguments

None

Return Value

The id of the JsChartViewer.


JsChartViewer.setViewPortLeft

JsChartViewer.setViewPortLeft

Usage

setViewPortLeft(left)

Description

Sets the position of the left side of the view port.

The position of the view port left side is its distance from the left side of the underlying surface, as a fraction of the width of the underlying surface. It should be between 0 and 1.

Arguments

Argument | Default | Description
left | (Mandatory) | The position of the left side of the view port.

Return Value

None


JsChartViewer.getViewPortLeft

JsChartViewer.getViewPortLeft

Usage

getViewPortLeft()

Description

Gets the position of the left side of the view port.

The position of the view port left side is its distance from the left side of the underlying surface, as a fraction of the width of the underlying surface. It should be between 0 and 1.

Arguments

None

Return Value

The position of the left side of the view port.


JsChartViewer.setViewPortTop

JsChartViewer.setViewPortTop

Usage

setViewPortTop(top)

Description

Sets the position of the top side of the view port.

The position of the view port top side is its distance from the top side of the underlying surface, as a fraction of the height of the underlying surface. It should be between 0 and 1.

Arguments

Argument | Default | Description
top | (Mandatory) | The position of the top side of the view port.

Return Value

None


JsChartViewer.getViewPortTop

JsChartViewer.getViewPortTop

Usage

getViewPortTop()

Description

Gets the position of the top side of the view port.

The position of the view port top side is its distance from the top side of the underlying surface, as a fraction of the height of the underlying surface. It should be between 0 and 1.

Arguments

None

Return Value

The position of the top side of the view port.


JsChartViewer.setViewPortWidth

JsChartViewer.setViewPortWidth

Usage

setViewPortWidth(width)

Description

Sets the width of the view port.

The view port width is expressed as a fraction of the width of the underlying surface. It should be between 0 and 1.

Arguments

Argument | Default | Description
width | (Mandatory) | The width of the view port.

Return Value

None


JsChartViewer.getViewPortWidth

JsChartViewer.getViewPortWidth

Usage

getViewPortWidth()

Description

Gets the width of the view port.

The view port width is expressed as a fraction of the width of the underlying surface. It should be between 0 and 1.

Arguments

None

Return Value

The width of the view port.


JsChartViewer.setViewPortHeight

JsChartViewer.setViewPortHeight

Usage

setViewPortHeight(height)

Description

Sets the height of the view port.

The view port height is expressed as a fraction of the height of the underlying surface. It should be between 0 and 1.

Arguments

Argument | Default | Description
height | (Mandatory) | The height of the view port.

Return Value

None


JsChartViewer.getViewPortHeight

JsChartViewer.getViewPortHeight

Usage

getViewPortHeight()

Description

Gets the height of the view port.

The view port height is expressed as a fraction of the height of the underlying surface. It should be between 0 and 1.

Arguments

None

Return Value

The height of the view port.


JsChartViewer.setMouseUsage

JsChartViewer.setMouseUsage

Usage

setMouseUsage(mouseUsage)

Description

Sets the mouse usage mode of the control.

The following table describes the supported mouse usage modes and the mouse behaviour in each mode.

Constant Value Description
JsChartViewer.Default0This represents the default mouse behaviour, which is to support tool tips and hot spot events as defined by the image map.

See BaseChart.getHTMLImageMap on how to define an image map for a chart.
JsChartViewer.Scroll2The mouse is used for drag scrolling the chart.

When the mouse drags on the plot area, the mouse cursor will change to a scroll cursor, and a selection rectangle representing the shifted plot area will be displayed to reflect the amount dragged. When the mouse is released, the view port coordinates will be updated to reflect the amount dragged, and a JsChartViewer.ViewPortChanged event will be fired.

If the mouse is not dragging inside the plot area, its behaviour is the same as the default mouse behaviour.
JsChartViewer.ZoomIn3The mouse is used for zoom in actions.

When the mouse is inside the plot area, the following behaviour will apply:

  • The mouse cursor will change to a zoom in cursor (a magnifying glass cursor with a '+' sign inside).

  • When the mouse drags on the plot area, a selection rectangle will be visible. When the mouse button is subsequently released, the view port coordinates will be updated to reflect the selection rectangle, and a JsChartViewer.ViewPortChanged event will be fired.

  • When the mouse clicks on the plot area without dragging, the view port will be updated to reflect zooming into the clicked point by a ratio specified in JsChartViewer.setZoomInRatio, and a JsChartViewer.ViewPortChanged event will be fired.
If the mouse is not inside the plot area, its behaviour is the same as the default mouse behaviour.
JsChartViewer.ZoomOut4The mouse is used for zoom out actions.

When the mouse is inside the plot area, the following behaviour will apply:

  • The mouse cursor will change to a zoom out cursor (a magnifying glass cursor with a '-' sign inside).

  • When the mouse clicks on the plot area , the view port will be updated to reflect zooming out from the clicked point by a ratio specified in JsChartViewer.setZoomOutRatio, and a JsChartViewer.ViewPortChanged event will be fired.
If the mouse is not inside the plot area, its behaviour is the same as the default mouse behaviour.

Note: It is known that mouse cursors for scrolling and zooming work on IE 6.0 or above, and FireFox. Due to the different capabilities of the various browsers, the mouse cursors may or may not appear in other browsers.

Arguments

Argument | Default | Description
mouseUsage | (Mandatory) | The mouse usage mode of the control, which must be one of the predefined constants as shown in the table above.

Return Value

None


JsChartViewer.getMouseUsage

JsChartViewer.getMouseUsage

Usage

getMouseUsage()

Description

Gets the mouse usage mode of the control.

Arguments

None

Return Value

An integer representing the mouse usage mode. See JsChartViewer.setMouseUsage for the meaning of this value.


JsChartViewer.setZoomDirection

JsChartViewer.setZoomDirection

Usage

setZoomDirection(direction)

Description

Sets the zoom direction for mouse zoom in/out actions.

In zoom operations for charts, it is common to restrict zooming to one direction only. For example, in a chart plotting temperature against time, zooming in from a yearly chart to a daily chart may mean the time axis (x-axis) is zoomed in by 36500%, while the temperature axis (y-axis) may be auto-scaled and not zoomed in at all. The user may be surprise if you also zoom in the y-axis by 36500%, in which case the chart may become hardly readable.

This method allows you to determine the zoom direction for mouse zoom actions (see JsChartViewer.setMouseUsage), specified using the following predefined constants:

Constant | Value | Description
JsChartViewer.Horizontal | 0 | Zoom actions apply to horizontal direction only.
JsChartViewer.Vertical | 1 | Zoom actions apply to vertical direction only.
JsChartViewer.HorizontalVertical | 2 | Zoom actions apply to both horizontal and vertical directions.

Arguments

Argument | Default | Description
direction | (Mandatory) | The zoom direction for mouse zoom actions.

Return Value

None


JsChartViewer.getZoomDirection

JsChartViewer.getZoomDirection

Usage

getZoomDirection()

Description

Gets the zoom direction for mouse zoom in/out actions.

Please refer to JsChartViewer.setZoomDirection for the supported directions.

Arguments

None

Return Value

An integer representing the zoom direction.


JsChartViewer.setScrollDirection

JsChartViewer.setScrollDirection

Usage

setScrollDirection(direction)

Description

Sets the scroll direction for mouse scroll actions.

Please refer to JsChartViewer.setZoomDirection for the supported directions.

Arguments

Argument | Default | Description
direction | (Mandatory) | The scroll direction for mouse scroll actions.

Return Value

None


JsChartViewer.getScrollDirection

JsChartViewer.getScrollDirection

Usage

getScrollDirection()

Description

Gets the scroll direction for mouse scroll actions.

Please refer to JsChartViewer.setZoomDirection for the supported directions.

Arguments

None

Return Value

An integer representing the scroll direction.


JsChartViewer.setZoomInRatio

JsChartViewer.setZoomInRatio

Usage

setZoomInRatio(ratio)

Description

Sets the magnification ratio for each zoom in click of the mouse.

For zoom in, the ratio should be greater than 1. The default is 2.

Arguments

Argument | Default | Description
ratio | (Mandatory) | The zoom in ratio.

Return Value

None


JsChartViewer.getZoomInRatio

JsChartViewer.getZoomInRatio

Usage

getZoomInRatio()

Description

Gets the magnification ratio for each zoom in click of the mouse.

For zoom in, the ratio should be greater than 1. The default is 2.

Arguments

None

Return Value

The magnification ratio.


JsChartViewer.setZoomOutRatio

JsChartViewer.setZoomOutRatio

Usage

setZoomOutRatio(ratio)

Description

Sets the magnification ratio for each zoom out click of the mouse.

For zoom out, the ratio should be less than 1. The default is 0.5.

Arguments

Argument | Default | Description
ratio | (Mandatory) | The zoom out ratio.

Return Value

None


JsChartViewer.getZoomOutRatio

JsChartViewer.getZoomOutRatio

Usage

getZoomOutRatio()

Description

Gets the magnification ratio for each zoom out click of the mouse.

For zoom out, the ratio should be less than 1. The default is 0.5.

Arguments

None

Return Value

The magnification ratio.


JsChartViewer.setZoomInWidthLimit

JsChartViewer.setZoomInWidthLimit

Usage

setZoomInWidthLimit(width)

Description

Sets the view port width at maximum zoom in.

In many applications, it is desirable to set a maximum zoom in level, instead of allowing the user to zoom in indefinitely.

This method determines the minimum allowed view port width. It should be between 0 and 1. The default is 0.01, which means a maximum zoom in of 100x (the view port see only 1% of the underlying surface).

Arguments

Argument | Default | Description
width | (Mandatory) | The minimum allowed view port width.

Return Value

None


JsChartViewer.getZoomInWidthLimit

JsChartViewer.getZoomInWidthLimit

Usage

getZoomInWidthLimit()

Description

Gets the view port width at maximum zoom in for mouse zoom in actions.

Arguments

None

Return Value

The view port width at maximum zoom in. See JsChartViewer.setZoomInWidthLimit for the meaning of this value.


JsChartViewer.setZoomOutWidthLimit

JsChartViewer.setZoomOutWidthLimit

Usage

setZoomOutWidthLimit(width)

Description

Sets the view port width at maximum zoom out.

This method determines the maximum allowed view port width. It should be between 0 and 1. The default is 1, which means at maximum zoom out, the view port width will cover the entire underlying surface.

Arguments

Argument | Default | Description
width | (Mandatory) | The maximum allowed view port width.

Return Value

None


JsChartViewer.getZoomOutWidthLimit

JsChartViewer.getZoomOutWidthLimit

Usage

getZoomOutWidthLimit()

Description

Gets the view port width at maximum zoom out for mouse zoom out actions.

Arguments

None

Return Value

The view port width at maximum zoom out. See JsChartViewer.setZoomOutWidthLimit for the meaning of this value.


JsChartViewer.setZoomInHeightLimit

JsChartViewer.setZoomInHeightLimit

Usage

setZoomInHeightLimit(height)

Description

Sets the view port height at maximum zoom in.

In many applications, it is desirable to set a maximum zoom in level, instead of allowing the user to zoom in indefinitely.

This method determines the minimum allowed view port height. It should be between 0 and 1. The default is 0.01, which means a maximum zoom in of 100x (the view port see only 1% of the underlying surface).

Arguments

Argument | Default | Description
height | (Mandatory) | The minimum allowed view port height.

Return Value

None


JsChartViewer.getZoomInHeightLimit

JsChartViewer.getZoomInHeightLimit

Usage

getZoomInHeightLimit()

Description

Gets the view port height at maximum zoom in for mouse zoom in actions.

Arguments

None

Return Value

The view port height at maximum zoom in. See JsChartViewer.setZoomInHeightLimit for the meaning of this value.


JsChartViewer.setZoomOutHeightLimit

JsChartViewer.setZoomOutHeightLimit

Usage

setZoomOutHeightLimit(height)

Description

Sets the view port height at maximum zoom out.

This method determines the maximum allowed view port height. It should be between 0 and 1. The default is 1, which means at maximum zoom out, the view port height will cover the entire underlying surface.

Arguments

Argument | Default | Description
height | (Mandatory) | The maximum allowed view port height.

Return Value

None


JsChartViewer.getZoomOutHeightLimit

JsChartViewer.getZoomOutHeightLimit

Usage

getZoomOutHeightLimit()

Description

Gets the view port height at maximum zoom out for mouse zoom out actions.

Arguments

None

Return Value

The view port height at maximum zoom out. See JsChartViewer.setZoomOutHeightLimit for the meaning of this value.


JsChartViewer.setMinimumDrag

JsChartViewer.setMinimumDrag

Usage

setMinimumDrag(offset)

Description

Sets the minimum mouse drag distance before it is considered as an intentional drag.

A mouse drag occurs if the mouse button is down while the mouse moves. However, sometimes a user may want to click on a point, but due to mouse vibrations, the mouse moves by a small amount while the button is still down. This may then be interpreted as a mouse drag.

This method determines the minimum drag distance in pixels before it is considered as an intentional drag. The default is 5 pixels. Non-intentional drags will be handled as mouse clicks instead of drags.

Arguments

Argument | Default | Description
offset | (Mandatory) | The minimum mouse drag distance in pixels before it is considered as an intentional drag.

Return Value

None


JsChartViewer.getMinimumDrag

JsChartViewer.getMinimumDrag

Usage

getMinimumDrag()

Description

Gets the minimum mouse drag distance before it is considered as an intentional drag.

Arguments

None

Return Value

The minimum mouse drag distance in pixels before it is considered as an intentional drag. See JsChartViewer.setMinimumDrag for the meaning of this value.


JsChartViewer.setSelectionBorderWidth

JsChartViewer.setSelectionBorderWidth

Usage

setSelectionBorderWidth(width)

Description

Sets the border width of the zoom selection box.

Arguments

Argument | Default | Description
width | (Mandatory) | The border width in pixels.

Return Value

None


JsChartViewer.getSelectionBorderWidth

JsChartViewer.getSelectionBorderWidth

Usage

getSelectionBorderWidth()

Description

Gets the border width of the zoom selection box.

Arguments

None

Return Value

The border width of the zoom selection box in pixels.


JsChartViewer.setSelectionBorderColor

JsChartViewer.setSelectionBorderColor

Usage

setSelectionBorderColor(color)

Description

Sets the border color of the zoom selection box as an HTML color.

Arguments

Argument | Default | Description
color | (Mandatory) | The border color as an HTML color.

Return Value

None


JsChartViewer.getSelectionBorderColor

JsChartViewer.getSelectionBorderColor

Usage

getSelectionBorderColor()

Description

Gets the border color of the zoom selection box.

Arguments

None

Return Value

The border color of the zoom selection box as an HTML color.


JsChartViewer.setZoomInCursor

JsChartViewer.setZoomInCursor

Usage

setZoomInCursor(cursor)

Description

Sets the mouse cursor to be used when the mouse is used for zoom in.

The cursor should be specified in the format used in CSS (Cascaded Style Sheet) cursor attributes.

Arguments

Argument | Default | Description
cursor | (Mandatory) | The mouse cursor to be used when the mouse is used for zoom in.

Return Value

None


JsChartViewer.getZoomInCursor

JsChartViewer.getZoomInCursor

Usage

getZoomInCursor()

Description

Gets the mouse cursor to be used when the mouse is used for zoom in.

Arguments

None

Return Value

The mouse cursor to be used when the mouse is used for zoom in.


JsChartViewer.setZoomOutCursor

JsChartViewer.setZoomOutCursor

Usage

setZoomOutCursor(cursor)

Description

Sets the mouse cursor to be used when the mouse is used for zoom out.

The cursor should be specified in the format used in CSS (Cascaded Style Sheet) cursor attributes.

Arguments

Argument | Default | Description
cursor | (Mandatory) | The mouse cursor to be used when the mouse is used for zoom out.

Return Value

None


JsChartViewer.getZoomOutCursor

JsChartViewer.getZoomOutCursor

Usage

getZoomOutCursor()

Description

Gets the mouse cursor to be used when the mouse is used for zoom out.

Arguments

None

Return Value

The mouse cursor to be used when the mouse is used for zoom out.


JsChartViewer.setNoZoomCursor

JsChartViewer.setNoZoomCursor

Usage

setNoZoomCursor(cursor)

Description

Sets the mouse cursor to be used when the mouse is used for zoom in/out, but the zoom in/out limits has been reached.

The cursor should be specified in the format used in CSS (Cascaded Style Sheet) cursor attributes.

Arguments

Argument | Default | Description
cursor | (Mandatory) | The mouse cursor to be used when the mouse is used for zoom in/out, but the zoom in/out limits has been reached.

Return Value

None


JsChartViewer.getNoZoomCursor

JsChartViewer.getNoZoomCursor

Usage

getNoZoomCursor()

Description

Gets the mouse cursor to be used when the mouse is used for zoom in/out, but the zoom in/out limits has been reached.

Arguments

None

Return Value

The mouse cursor to be used when the mouse is used for zoom in/out, but the zoom in/out limits has been reached.


JsChartViewer.setScrollCursor

JsChartViewer.setScrollCursor

Usage

setScrollCursor(cursor)

Description

Sets the mouse cursor to be used when the mouse is used for scrolling.

The cursor should be specified in the format used in CSS (Cascaded Style Sheet) cursor attributes.

Arguments

Argument | Default | Description
cursor | (Mandatory) | The mouse cursor to be used when the mouse is used for scrolling.

Return Value

None


JsChartViewer.getScrollCursor

JsChartViewer.getScrollCursor

Usage

getScrollCursor()

Description

Gets the mouse cursor to be used when the mouse is used for scrolling.

Arguments

None

Return Value

The mouse cursor to be used when the mouse is used for scrolling.


JsChartViewer.setCustomAttr

JsChartViewer.setCustomAttr

Usage

setCustomAttr(key, value)

Description

Sets a custom attribute.

The JsChartViewer does not interpret or use custom attributes. It merely sends them to the server side WebChartViewer control. On the server side, these attributes can be retrieved using WebChartViewer.getCustomAttr.

Custom attributes are useful for transferring application specific information between the server and the browser during partial chart updates (AJAX requests). They are also useful for storing values that needs to be persistent across multiple HTTP requests.

For example, one one can use custom attributes to update the states of the HTML controls on the browser side during partial chart updates. (For non-AJAX requests, the server can always update the web page directly.)

Both the key and value of a custom attribute should be text strings. The key should be a valid variable name, that is, it should start with A-Z, a-z or underscore, and consists entirely of alphanumeric characters with no spaces.

Arguments

Argument | Default | Description
key | (Mandatory) | The attribute key.
value | (Mandatory) | The attribute value.

Return Value

None


JsChartViewer.getCustomAttr

JsChartViewer.getCustomAttr

Usage

getCustomAttr(key)

Description

Gets a custom attribute.

The JsChartViewer does not interpret or use custom attributes. It merely receives them from the server side WebChartViewer control. On the server side, these attributes are set using WebChartViewer.setCustomAttr.

Custom attributes are useful for transferring application specific information between the server and the browser during partial chart updates (AJAX requests).

For example, one can use custom attributes to pass the values of browser side HTML controls to the server. (For non-AJAX requests, one can always use FORM POST or GET to pass information to the server.)

Both the key and value of a custom attribute should be text strings. The key should be a valid variable name, that is, it should start with A-Z, a-z or underscore, and consists entirely of alphanumeric characters with no spaces.

Arguments

Argument | Default | Description
key | (Mandatory) | The attribute key.

Return Value

The value of the required attribute.


JsChartViewer.canSupportPartialUpdate

JsChartViewer.canSupportPartialUpdate

Usage

canSupportPartialUpdate()

Description

Checks if the browser is capable of supporting partial chart updates (AJAX requests).

Note: This method is a static method (class method). It should be accessed as JsChartViewer.canSupportPartialUpdate, not objName.canSupportPartialUpdate.

This method allows one to switch between partial chart updates and full page update depending on the capabilities of the browser.

In the current version of JsChartViewer, partial chart updates (AJAX requests) require the browser to support one of the followings:

  • XMLHttpRequest object: This object is supported in most non-Microsoft DOM compliant browsers, such as FireFox, Mozilla, Opera, Safari, etc.

  • Msxml2.XMLHTTP or Microsoft.XMLHTTP ActiveX object on IE 5.0 or above: These objects are included as standard in IE 5.0 or above, so they should be available on IE 5.0 or above.

  • IE 5.5 or above: IE 5.0 or above normally can use the Msxml2.XMLHTTP or Microsoft.XMLHTTP ActiveX object for partial updates. However, some browsers may have ActiveX support disabled for security reasons. In this case, if the browser is IE 5.5 or above, JsChartViewer will to use a "hidden IFRAME" method to communicate with the server.

Arguments

None

Return Value

True if partial chart update is supported, otherwise false.


JsChartViewer.partialUpdate

JsChartViewer.partialUpdate

Usage

partialUpdate()

Description

Sends a partial update request (AJAX request) to the server.

This method will send the state of the JsChartViewer to the server using AJAX techniques. The web page will not be refreshed. It is expected the server will use a WebChartViewer to process the request, and return the updated state, the updated chart and/or the updated image map.

During the partial update, a "rotating clock" icon (configurable using JsChartViewer.updatingMsg) will appear on the chart to indicate that a partial update is in progress.

This method is asynchronous. It will return before the update has been completed.

Arguments

None

Return Value

None


JsChartViewer.streamUpdate

JsChartViewer.streamUpdate

Usage

streamUpdate(timeout)

Description

Refreshes the <IMG> that the JsChartViewer is bound to.

Unlike JsChartViewer.partialUpdate, this method does not send the JsChartViewer state to the server. It merely sends a new request to the server using the existing URL of the <IMG> tag.

If this method is called periodically (eg. using a Javascript timer), and the server sends the most updated chart for these requests, then the chart will appear to be automatically update.

One can always refresh an <IMG> tag using standard client side Javascript without using JsChartViewer at all. This method offers the following additional features:

  • Double buffering

    Instead of directly refreshing the <IMG> tag, this method will create a hidden Javascript Image object using the same URL as the <IMG> tag, and will update that hidden Image object. When the update is completed, it will copy the hidden Image object to the <IMG>.

  • Overlapping updating

    Due to the nature of Internet connections, it is sometimes hard to predict the response time for a chart update. For application that needs to update the chart frequently, it may be possible the a new request be sent before an existing request is completed.

    In standard Javascript, if a new update request is sent before an existing request is completed, the existing request will be aborted, and the new request will be used. However, for periodic updates, if new requests are sent faster than the time needed to update the chart (eg. the chart update needs 20 seconds, but new requests are sent every 15 seconds), then all update requests will be aborted by the next update requests, and the chart will not update at all. Furthermore, the network and/or the server will be overwhelmed by these requests.

    In the streamUpdate method, new update requests will be ignored until existing requests are completed, or until a given timeout has occurred. This ensures the chart does get updated.

  • Error handling

    In standard Javascript, if an <IMG> tag update request failed, the browser may display a "broken image symbol".

    In the streamUpdate method, if the update request failed, nothing will happen, and the existing chart will still be shown. The system will simply wait for the next update request.

  • Cache avoidance

    To avoid caching by the browser and/or intermediate proxy servers, the streamUpdate method will append dummy unique query parameters to the <IMG> URL to ensure each URL is unique, and so avoids the cache.

Arguments

Argument | Default | Description
timeout | 60 | If there is an existing non-completed streamUpdate request, the timeout value determines whether to abort the existing request, or to ignore the current request and continue with the existing request. If the existing request has been pending for longer than the timeout in seconds, it will be aborted, otherwise it will continue.

Return Value

True if the current streamUpdate request is sent out. False if the request is not sent out (due to an existing request that has not timeout).


JsChartViewer.attachHandler

JsChartViewer.attachHandler

Usage

attachHandler(eventId, handler)

Description

Attaches a function to be used as the event handler for an event.

Multiple functions may be attached to the same event may be attached by calling this method multiple times, in which case the functions will be called in the sequence of their attachment.

Note that this method expects the function to be a real function object, not a text string. The function will be called as if it is a method of the JsChartViewer object, which means the "this" pointer inside the function represents the JsChartViewer object that calls the function.

Arguments

Argument | Default | Description
eventId | (Mandatory) | A text string representing the event to attach to.
handler | (Mandatory) | A function object

Return Value

An handler id representing the attachment of the handler to the event. This id can be used in JsChartViewer.detachHandler to detach the handler.


JsChartViewer.detachHandler

JsChartViewer.detachHandler

Usage

detachHandler(handlerId)

Description

Detaches a function from being an event handler for an event.

Arguments

Argument | Default | Description
handlerId | (Mandatory) | The handler id returns from a previous call to JsChartViewer.attachHandler for creating the attachment.

Return Value

None


JsChartViewer.applyHandlers

JsChartViewer.applyHandlers

Usage

applyHandlers(eventId)

Description

Calls the handlers for an event.

This method allows an external object to trigger JsChartViewer events.

Arguments

Argument | Default | Description
eventId | (Mandatory) | A text string representing the event to trigger.

Return Value

The return value of the handler function of the event. If there are multiple handler functions for the event, the first return value that is not equivalent to "false" will be used.


JsChartViewer.ViewPortChanged

JsChartViewer.ViewPortChanged

Description

This event occurs when the view port is changed through mouse actions (see JsChartViewer.setMouseUsage).

Use JsChartViewer.attachHandler with the event id "ViewPortChanged" to attach a handler to this event.

If the browser supports partial chart update (that is, AJAX request - see JsChartViewer.canSupportPartialUpdate), the JsChartViewer.partialUpdate method can be attached to this event, so a partial chart update will occur when the view port changes. If the browser does not support partial chart update, a function to perform a full page update may be attached to this event.

For example, the following is some typical code used after the web page is loaded (typically in the onLoad event handler of the <BODY> tag).

// Detect if browser is capable of support partial update (AJAX chart update)
if (JsChartViewer.canSupportPartialUpdate())
    // Can support partial update, use partialUpdate when view port changed
    viewer.attachHandler("ViewPortChanged", viewer.partialUpdate);
else
    // Cannot support support partial update, so use full page update (in this
    // example, we assume this can be by submitting a form in the web page)
    viewer.attachHandler("ViewPortChanged", function() { document.forms[0].submit(); });


JsChartViewer.UpdateError

JsChartViewer.UpdateError

Description

This event occurs if an error occurs in during a partial update.

Use JsChartViewer.attachHandler with the event id "UpdateError" to attach a handler to this event.

In the event handler, one may use "this.errCode" and "this.errMsg" (without quotes) to retrieve the error code and error message.

If no event handler is attached to this event, or all attached event handler returns false, then default error handling will be used, which is to display the error message on the chart using the JsChartViewer.serverErrorMsg template.


JsChartViewer.PreUpdate

JsChartViewer.PreUpdate

Description

This event occurs immediately before a partial chart update request is sent to the server (see JsChartViewer.partialUpdate).

Use JsChartViewer.attachHandler with the event id "PreUpdate" to attach a handler to this event.

This event is commonly used to include custom information to be sent to the server (by storing them as custom attributes using JsChartViewer.setCustomAttr), such as the states of HTML controls in the web page.


JsChartViewer.PostUpdate

JsChartViewer.PostUpdate

Description

This event occurs after a partial update response is received from the server and is processed successfully.

Use JsChartViewer.attachHandler with the event id "PostUpdate" to attach a handler to this event.

This event is commonly used to retrieve custom information sent from the server (by getting them as custom attributes using JsChartViewer.getCustomAttr), such as the updated states of the HTML controls in the web page.


JsChartViewer.updatingMsg

JsChartViewer.updatingMsg

Description

Gets or sets the HTML message displayed when partial chart update is in progress.

If the message begins with the <DIV> tag, then the message will be used as is, otherwise the message will be put into a container first as defined by JsChartViewer.msgContainer before use.

This property is available as both a static property (class property) and an instance property. If you set the static property (class property) using JsChartViewer.updatingMsg, then all JsChartViewer objects will be affected. If you set the instance property using objName.updatingMsg, then only the object being configured will be affected.

The default JsChartViewer.updatingMsg is to display a "rotating clock" icon followed by the text "Updating".


JsChartViewer.serverErrorMsg

JsChartViewer.serverErrorMsg

Description

Gets or sets the HTML template for displaying server error messages.

When a partial update error occurs, the default behaviour is to display the error message on the chart. (See JsChartViewer.UpdateError on how to change the default behaviour.) This property determines the format to display the error message.

The format should be written in HTML, using "%errCode" and "%errMsg" as the place holder for the error code and the error message. The template may include JsChartViewer.okButton or JsChartViewer.xButton for putting an "OK" or an "X" (close window) button in the template for closing the error message window.

If the template begins with the <DIV> tag, then the template will be used as is, otherwise the template will be put into a container first as defined by JsChartViewer.msgContainer before use.

This property is available as both a static property (class property) and an instance property. If you set the static property (class property) using JsChartViewer.updatingMsg, then all JsChartViewer objects will be affected. If you set the instance property using objName.updatingMsg, then only the object being configured will be affected.

As an example, the default JsChartViewer.serverErrorMsg is:

JsChartViewer.serverErrorMsg = JsChartViewer.xButton +
    '<div style="font-family:Arial; font-weight:bold; font-size:15pt;">' +
        'Error %errCode accessing server' +
    '</div><hr>%errMsg';

The above means that the error message will be display using the default message container, with an "X" button on top for closing the window, followed by a title line showing the error code, followed by the horizontal line separator, and finally the error message.


JsChartViewer.msgContainer

JsChartViewer.msgContainer

Description

Gets or sets the default message container template.

The message container template will be used for chart messages that are not started with the
tag. The template should be written in HTML, using %msg as the place holder where the message should appear.

As an example, the default message container is as follows, which means a rectangle with a black border and light red background, with 8pt Verdana black color as the default font.

<div style="font-family:Verdana;font-size:8pt;font-weight:bold;padding:3 8 3 8;
    border:1pt solid #000000;background-color:#FFCCCC;color:#000000">
    %msg
</div>

Note: This is a static property (class property). It should be accessed as JsChartViewer.msgContainer, not objName.msgContainer.


JsChartViewer.okButton

JsChartViewer.okButton

Description

Gets or sets the "OK" button for closing the chart message window.

This property is useful when customizing the JsChartViewer.serverErrorMsg. It provides the code required to close the message window. It is also used as the close window button for partial update notification messages.

You may customize the "OK" button by creating it in HTML, using "%closeScript" as the place holder for the Javascript that closes the window.

As an example, the default "OK" button is:

<center>[<a href="javascript:%closeScript"> OK </a>]</center>

Note: This is a static property (class property). It should be accessed as JsChartViewer.okButton, not objName.okButton.


JsChartViewer.xButton

JsChartViewer.xButton

Description

Gets or sets the "X" button for closing the chart message window.

You may customize the "X" button by creating it in HTML, using "%closeScript" as the place holder for the Javascript that closes the window.

As an example, the default "X" button is:

[<a href="javascript:%closeScript"> X </a>]

Note: This is a static property (class property). It should be accessed as JsChartViewer.xButton, not objName.xButton.


Data Types

Data Types

This section describes various data types and how they are represented in ChartDirector.

In this section

Color Specification
Describes ChartDirector's advanced color support - including ARGB colors, pattern colors, gradient colors, dash line colors, zone colors, and palette based colors.

Font Specification
Explains various font attributes and how they are represented in ChartDirector.

Shape Specification
Explains how shapes are specified in ChartDirector. Shapes are used in data symbols and as bar shapes in bar charts.

Alignment Specification
Introduces the constants used to specify the relative position of two objects.

Date/Time Specification
Describes how dates and times are represented in ChartDirector.

No Value Specification
Introduces the ChartDirector NoValue constant for denoting missing data values.

Re-Sampling Filters
Describes the resampling filter types used in some low level graphics operations.


Color Specification

Color Specification

Many functions in the ChartDirector API accept colors as parameters. ChartDirector supports colors specified in web and HTML compatible ARGB format, in which ARGB refers to the Alpha transparency, Red, Green and Blue components of the color.

In addition to ARGB colors, ChartDirector supports "dynamic" colors. A dynamic color is a color that changes depending on the position of the pixels. The "dynamic" colors that ChartDirector supports include "pattern colors", "metal colors", "gradient colors", "zone colors" and "dash line colors".

ChartDirector supports specifying colors indirectly using "palette colors". When a "palette color" is used, the color is specified as an index to a palette. The actual color is looked up from the palette.

ARGB Color

ARGB color consists of 4 components - alpha transparency, red, green and blue. The four components are encoded as a 32-bit number, with each component occupying 8 bits. In hexadecimal notation, it is AARRGGBB, where AA, RR, GG and BB are the alpha transparency, red, green and blue components.

Each component ranges from 00 - FF (0 - 255), representing its intensity. For example, pure red color is 00FF0000, pure green color is 0000FF00, and pure blue color is 000000FF. White color is 00FFFFFF, and black color is 00000000.

Unlike most programming languages, ColdFusion does not have a syntax to represent numbers in hexadecimal notation. To address this issue, ChartDirector for ColdFusion supports using a text string to represent hexadecimal numbers in Java/Javascript syntax (that is, putting "0x" in front). For example, the hexadecimal number 0000FF00 can be entered as "0x0000FF00" (with quotes) in ChartDirector API.

For the alpha transparency component, a zero value means the color is not transparent all at. This is equivalent to traditional RGB colors. A non-zero alpha transparency means the the color is partially transparent. The larger the alpha transparency, the more transparent the color will be. If a partially transparent color is used to draw something, the underlying background can still be seen.

For example, 80FF0000 is a partially transparent red color, while 00FF0000 is a non-transparent red color.

Note that ChartDirector's ARGB color is web and HTML compatible. For example, red is FF0000, the same as in HTML. There are many resources on the web that provide tables in which you can click a color and it will show its HTML color code. These color codes can be used in ChartDirector.

If alpha transparency is FF (255), the color is totally transparent. That means the color is invisible. It does not matter what the RGB components are. So in ChartDirector, only one totally transparent color is used - FF000000. All other colors of the form FFnnnnnn are reserved to represent palette colors and dynamic colors, and should not be interpreted as the normal ARGB colors.

The totally transparent color FF000000 is often used in ChartDirector to disable drawing something. For example, if you want to disable drawing the border of a rectangle, you can set the border color to totally transparent.

For convenience, ChartDirector defines a constant called Transparent, which is equivalent to FF000000.

Pattern Color

A pattern color is a dynamic color that changes according to a 2D periodic pattern. When it is used to fill an area, the area will look like being tiled with a wallpaper pattern.

Pattern colors are created using BaseChart.patternColor, BaseChart.patternColor2, DrawArea.patternColor and DrawArea.patternColor2. The patternColor method creates pattern colors using an array of colors as a bitmap. The patternColor2 method creates pattern colors by loading the patterns from image files.

These methods return a 32-bit integer acting as a handle to the pattern color. The handle can be used in any ChartDirector API that expects a color as its input.

Metal Color

A metal color is a color of which the brightness varies smoothly across the chart surface as to make the surface looks shiny and metallic. ChartDirector supports using any color as the base color of the metal color. In particular, using yellow and grey as the base colors will result in metal colors that look gold and silver.

Metal colors are most often used as background colors of charts. They are created using ChartDirector.CFChart.metalColor, ChartDirector.CFChart.goldColor and ChartDirector.CFChart.silverColor. The first method allows you to specify an arbitrary base color. The second and third methods use yellow and grey as the base colors, resulting in gold and silver metal colors.

These methods return a 32-bit integer acting as a handle to the gradient color. The handle can be used in any ChartDirector API that expects a color as its input.

Gradient Color

A gradient color is a color that changes progressively across a direction.

Gradient colors are created using BaseChart.gradientColor, BaseChart.gradientColor2, DrawArea.gradientColor and DrawArea.gradientColor2. The gradientColor method creates a 2-point gradient color that changes from color A to color B. The gradientColor2 method creates a multi-point gradient colors that changes from color A to B to C ....

These methods return a 32-bit integer acting as a handle to the gradient color. The handle can be used in any ChartDirector API that expects a color as its input.

One common use of multi-point gradient colors is to define colors that have metallic look and feel. Please refer to DrawArea.gradientColor2 for details.

Dash Line Colors

A dash line color is a color that switches on and off periodically. When used to draw a line, the line will appear as a dash line.

Dash line colors are created using BaseChart.dashLineColor and DrawArea.dashLineColor. They accept a line color and a dash pattern code as arguments, and return a 32-bit integer acting as a handle to the dash line color. The handle can be used in any ChartDirector API that expects a color as its input.

Zone Colors

A zone color is for XY charts only. It is a color that automatically changes upon reaching a data threshold value along the x-axis or y-axis. Zone colors are created using Layer.xZoneColor, Layer.yZoneColor, XYChart.xZoneColor or XYChart.yZoneColor.

Palette Colors

Palette colors are colors of the format FFFFnnnn, where the least significant 16 bits (nnnn) are the index to the palette. A palette is simply an array of colors. For a palette color, the actual color is obtained by looking up the palette using the index. For example, the color FFFF0001 is the second color in the palette (first color is index 0).

The colors in the palette can be ARGB colors or "dynamic" colors (pattern, gradient and dash line colors).

The first eight palette colors have special significance. The first three palette colors are the background color, default line color, and default text color of the chart. The 4th to 7th palette colors are reserved for future use. The 8th color is a special dynamic color that is equal to the data color of the "current data set".

The 9th color (index = 8) onwards are used for automatic data colors. For example, in a pie chart, if the sector colors are not specified, ChartDirector will automatically use the 9th color for the first sector, the 10th color for the second sector, and so on. Similarly, for a multi-line chart, if the line colors are not specified, ChartDirector will use the 9th color for the first line, the 10th color for the second line, and so on.

The ChartDirector API defines several constants to facilitate using palette colors.

Constant | Value | Description
Palette | FFFF0000 | The starting point of the palette. The first palette color is (Palette + 0). The nth palette color is (Palette + n - 1).
BackgroundColor | FFFF0000 | The background color.
LineColor | FFFF0001 | The default line color.
TextColor | FFFF0002 | The default text color.
[Reserved] | FFFF0003 - FFFF0006 | These palette positions are reserved. Future versions of ChartDirector may use these palette positions for colors that have special significance.
SameAsMainColor | FFFF0007 | A dynamic color that is equal to the data color of the current data set. This color is useful for objects that are associated with data sets. For example, in a pie chart, if the sector label background color is SameAsMainColor, its color will be the same as the corresponding sector color.
DataColor | FFFF0008 | The starting point for the automatic data color allocation.

When a chart is created, it has a default palette. You may modify the palette using BaseChart.setColor, BaseChart.setColors, or BaseChart.setColors2.

The advantages of using palette colors are that you can change the color schemes of the chart in one place. ChartDirector comes with several built-in palettes represented by the following predefined constants.

Constant | Description
defaultPalette | An array of colors representing the default palette. This palette is designed for drawing charts on white backgrounds (or lightly colored backgrounds).
whiteOnBlackPalette | An array of colors useful for drawing charts on black backgrounds (or darkly colored backgrounds).
transparentPalette | An array of colors useful drawing charts on white backgrounds (or lightly colored backgrounds). The data colors in this palette are all semi-transparent.


Font Specification

Font Specification

Font Name

In ChartDirector for ColdFusion, a font can be specified using the format:

{font name} [Bold] [Italic]

The followings are some examples:

Arial Bold
Times New Roman
Courier Bold Italic
SansSerif

Special Note for Headless Systems

Headless systems refer to systems that do not have GUI, such as some Linux/UNIX servers.

On Microsoft Windows and Mac OS X, Java uses the font subsystem provided by the OS. On Linux/UNIX, there is no font subsystem at the OS level. Many Java VM will attempt to use X Window services to support fonts. If the system is headless and does not has X Window running, the Java font system may not function.

As a backup, ChartDirector also comes with its own internal font system. If the Java font system is not functional, ChartDirector will automatically use its internal font system. The internal font system only has 3 fonts - generic sans serif (Arial like font), generic serif (Times New Roman like font) and generic monospace (Courier like font). All of them have bold, italic and bold-italic styles.

You may use "cfdemo/cdinfo.cfm" to determine if the Java font system is functional or not.

Java 1.4 or above contains built-in support for headless systems, so the Java font system can function even on headless systems. However, this feature may need to be enabled by a command line switch. See the following ColdFusion knowledge base article on how to enable headless support in ColdFusion MX.

http://www.adobe.com/cfusion/knowledgebase/index.cfm?id=tn_18747

Font List

Instead of specifying a single font file as the font name, you may specify a list of font files as the font name, separated by semi-colons. This is useful when using international characters that are only available in some fonts.

For example, if you would like to use the Arial font for western characters, and the MingLiu font for Chinese characters (since the Arial font does not have Chinese characters), you may specify the font name as "Arial;MingLiu". In this case, ChartDirector will try the Arial font first. If it cannot find a certain character there, it will try the MingLiu font.

Indirect Font Names

ChartDirector supports several special keywords for specifying the font name indirectly. When these keywords are used as font names, ChartDirector will look up the actual font names from a font table. The keywords are as follows:

Keywords | Description
"normal" | This default normal font, which is the first font in the font table. This is initially mapped to "Arial".
"bold" | The default bold font, which is the second font in the font table. This is initially mapped to "Arial Bold".
"italic" | The default italic font, which is the third font in the font table. This is initially mapped to "Arial Italic".
"boldItalic" | The default bold-italic font, which is the fourth font in the font table. This is initially mapped to "Arial Bold Italic" .
"fontN" | The (N + 1)th font in the font table (the first font is "font0").

The font table can be modified using BaseChart.setFontTable or DrawArea.setFontTable.

The advantage of using indirect font names is that you can change the fonts fonts in your charts in one place.

Font Index

The font index is ignored in ChartDirector for ColdFusion. It is solely for compatibility with other ChartDirector editions.

Font Size

The font size decides how big a font will appear in the image. The font size is expressed in a font unit called points. This is the same unit used in common word processors.

Instead of specifying font size, some ChartDirector API (eg. TextBox.setFontSize) allow you to specify font height and font width separately. In ChartDirector for ColdFusion, only font height is used as the font size, and font width is ignored.

Font Color

This is the color to draw the font. (See Color Specification on how colors are represented in ChartDirector.)

Font Angle

This is the angle in degrees by which the font should be rotated anti-clockwise.

Vertical Layout

By default, text are laid out horizontally, with characters being drawn from left to right.

ChartDirector also supports vertical layout, with characters being drawn from top to bottom. For example, you may use BaseChart.addText to add text that are laid out vertically. Vertical layout is common for oriental languages such as Chinese, Japanese and Korean.


Shape Specification

Shape Specification

Several ChartDirector API accept shape specification as arguments. For example, BarLayer.setBarShape and BarLayer.setBarShape2 can be used to specify shapes of bars in bar charts, while DataSet.setDataSymbol, DataSet.setDataSymbol4, PolarLayer.setDataSymbol and PolarLayer.setDataSymbol4 can be used to specify shapes for data symbols.

Note that in addition to shapes, in many cases ChartDirector also accepts images or custom draw objects for data representation. For example, see DataSet.setDataSymbol2, DataSet.setDataSymbol3, PolarLayer.setDataSymbol2 and PolarLayer.setDataSymbol3.

Built-In Shapes

Built-in shapes are specified as integers. The integers can be explicit constants, or can be generated by a ChartDirector method for parameterized shapes. For example, a circle is represented by an explicit constant CircleShape (=7). On the other hand, the number representing a polygon depends on the number of sides the polygon has, so it is generated by using the PolygonShape method, passing in the number of sides as argument.

The following table illustrates the various ChartDirector shapes:

Shape Id | Value | Description
SquareShape | 1 | Square shape. See (1, 1) above.
DiamondShape | 2 | Diamond shape. See (2, 1) above.
TriangleShape | 3 | Triangle shape pointing upwards. See (3, 1) above.
RightTriangleShape | 4 | Triangle shape pointing rightwards. See (4, 1) above.
LeftTriangleShape | 5 | Triangle shape pointing leftwards. See (5, 1) above.
InvertedTriangleShape | 6 | Triangle shape pointing downwards. See (1, 2) above.
CircleShape | 7 | Circle shape. See (2, 2) above.
StarShape | [Method] | Star shapes of various points. See (2, 3), (2, 4), (2, 5), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5) above for stars with 3 to 10 points.
PolygonShape | [Method] | Polygon shapes symmetrical about a vertical axis with a vertex at the top center position. See (4, 1), (4, 3), (4, 5), (5, 1) for polygons of 5 to 8 sides.
Polygon2Shape | [Method] | Polygon shapes symmetrical about a vertical axis but without any vertex at the top center position. See (4, 2), (4, 4) for polygons of 5 and 6 sides.
CrossShape | [Method] | '+' shapes. See (5, 2), (5, 3), (5, 4), (5, 5), (6, 1), (6, 2), (6. 3) for '+' shape with arm width of 0.1 - 0.7.
Cross2Shape | [Method] | 'X' shapes. See (6, 4), (6, 5), (7, 1), (7, 2), (7, 3), (7, 4), (7, 5) for 'X' shapes with arm width of 0.1 - 0.7.

Custom Shapes

In ChartDirector, custom shapes are specified as an array of integers x0, y0, x1, y1, x2, y2 ... representing the coordinates of the vertices of the custom polygonal shape.

The polygon should be defined with a bounding square of 1000 x 1000 units, in which the x-axis is from -500 to 500 going from left to right, and the y-axis is from 0 to 1000 going from bottom to top.

ChartDirector will automatically scale the polygon so that 1000 units will become to the pixel size as requested by the various ChartDirector API.

As an example, the shape of the standard diamond shape in ChartDirector is represented as an array with 8 numbers:

0, 0, 500, 500, 0, 1000, -500, 500


Alignment Specification

Alignment Specification

In many ChartDirector objects, you may specify the alignment of the object's content relative to its boundary. For example, for a TextBox object, you may specify the text's alignment relative to the box boundary by using TextBox.setAlignment.

The ChartDirector API defines several constants for the alignment options.

Constant | Value | Description
BottomLeft | 1 | The leftmost point on the bottom line.
BottomCenter | 2 | The center point on the bottom line.
BottomRight | 3 | The rightmost point on the bottom line.
Left | 4 | The leftmost point on the middle horizontal line.
Center | 5 | The center point on the middle horizontal line.
Right | 6 | The rightmost point on the middle horizontal line.
TopLeft | 7 | The leftmost point on the top line.
TopCenter | 8 | The center point on the top line.
TopRight | 9 | The rightmost point on the top line.
Bottom | 2 | The center point on the bottom line. Same as BottomCenter.
Top | 8 | The center point on the top line. Same as TopCenter.
TopLeft2 | 10 | An alternative top-left position used in Axis.setTitlePos for axis title positioning only. For a vertical axis, TopLeft2 refers to refers to the left of the top side, while TopLeft refers to the top of the left side. The reverse applies for a horizontal axis.
TopRight2 | 11 | An alternative top-right position used in Axis.setTitlePos for axis title positioning only. For a vertical axis, TopRight2 refers to refers to the right of the top side, while TopRight refers to the top of the right side. The reverse applies for a horizontal axis.
BottomLeft2 | 12 | An alternative bottom-left position used in Axis.setTitlePos for axis title positioning only. For a vertical axis, BottomLeft2 refers to refers to the left of the bottom side, while BottomLeft refers to the bottom of the left side. The reverse applies for a horizontal axis.
BottomRight2 | 13 | An alternative bottom-right position used in Axis.setTitlePos for axis title positioning only. For a vertical axis, BottomRight2 refers to refers to the right of the bottom side, while BottomRight refers to the bottom of the right side. The reverse applies for a horizontal axis.


Date/Time Specification

Date/Time Specification

Many functions in the ChartDirector API accept dates/times as parameters. ChartDirector supports using ColdFusion date objects to represent dates. Note that ChartDirector uses real ColdFusion date objects, not "numeric dates" (ColdFusion dates convert to a number). If ChartDirector encounters a numeric date, it will just treat it as an ordinary number.

Internally, ChartDirector represents dates/times as the seconds elapsed since 1-1-0001 00:00:00. When ChartDirector encounters a ColdFusion date, it will automatically convert it to the internal format for processing.

Some ChartDirector utility functions, such as the RanTable random sequence generator, may output date/time in ChartDirector internal format. ChartDirector provides several functions ChartDirector.CFChart.CTime, ChartDirector.CFChart.CTime2, ChartDirector.CFChart.NTime and ChartDirector.CFChart.NTime2 that can be used to convert between ChartDirector's internal date format and ColdFusion date objects.


No Value Specification

No Value Specification

To draw charts, you need to supply data. In ChartDirector, data are supplied as an array of numbers.

In many cases, a data point will be missing. For example, suppose you are drawing a line chart with one data point per hour. It is possible that due to various reasons, some data points could be missing. However, if you are using an enumerated x-axis (see Axis.setLabels), you cannot not simply remove that point, otherwise the remaining points will all be shifted.

To address this kind of issues, ChartDirector supports a special constant called NoValue, which is equal to 1.7E+308. When ChartDirector sees that a data point is NoValue, it will jump over that point.

In a line chart, if a data point is NoValue, ChartDirector will jump over to the next data point. ChartDirector can use an alternative line color when jumping over a NoValue point to visually reflect that there is a missing point. The default alternative line color is Transparent, which means the NoValue point will result in a discontinuous line. You may use LineLayer.setGapColor to change it to other colors, such as using SameAsMainColor (same color as the normal line) or a dash line color.


Re-Sampling Filters

Re-Sampling Filters

A number of low level ChartDirector graphics primitives using the DrawArea object involve moving some or all pixels by a fractional offset. For example, rotating an image by 45 degrees (using DrawArea.rotate) will cause some pixels to rotate to non-integer coordinates.

Consider the simplest operation - shifting the image leftwards using DrawArea.move. If the image is shifted by an integer number of pixels, it is easy to determine the new image.

How about if the image is shifted by a non-integer number of pixels, such as 1.5 pixels? In this case, the pixel (10, 10) in the new image corresponds to pixel (8.5, 10) in the original image.

In graphics theory, the proper way to estimate non-integer-coordinate pixel is by re-sampling. In simple terms, the non-integer-coordinate pixel is computed using "two dimensional interpolation" from nearby integer-coordinate pixels. The interpolation method is called a "filter".

Re-Sampling Filters

ChartDirector supports a number of filters denoted by the following predefined constants:

Constant | Value | Description
BoxFilter | 0 | Box filter. This is equivalent to setting the color of a non-integer-coordinate pixel to the nearest integer-coordinate pixel.
LinearFilter | 1 | Linear filter. This is equivalent to setting the color of a non-integer-coordinate pixel as the linear weighted average of nearby integer-coordinate pixels.
QuadraticFilter | 2 | Quadratic Filter.
BSplineFilter | 3 | B-spline Filter.
HermiteFilter | 4 | Hermite Filter.
CatromFilter | 5 | Catrom Filter.
MitchellFilter | 6 | Mitchell Filter.
SincFilter | 7 | Sinc Filter.
LanczosFilter | 8 | Lanczos Filter.
GaussianFilter | 9 | Gaussian Filter.
HanningFilter | 10 | Hanning Filter.
HammingFilter | 11 | Hamming Filter.
BlackmanFilter | 12 | Blackman Filter.
BesselFilter | 13 | Bessel Filter.

Filtering Region

Filtering computes a pixel as the weighted average of nearby pixels. What is meant by "nearby"?

In a linear filter, "nearby" means both the horizontal and vertical distances are less than 1 pixel length from the target pixel. This defines the filtering region of the linear filter. Each pixel can have up to 4 integer-coordinate neighbours. So in a linear filter, each pixel is computed by interpolating from up to 4 neighbouring pixels.

The filtering region of different filters are different. For example, the B-spline filter has a filtering region dimension of 2 pixel distance. Each pixel is computed by interpolating from up to 16 nearby pixels. This is because B-spline, being a cubic polynomial algorithm, requires more points for interpolation.

The filtering region will automatically be extended if the graphics operation involves reducing the image size. It is because the each pixel in the reduced image should corresponding to a larger area in the original image. For example, if an image is resized to 30% of the original in width and height, the filtering region dimension will be increased by a factor of 1 / 0.3 = 3.333.

Blur Factor

All ChartDirector API that supports re-sampling also supports an additional blur factor parameter. This parameter can be used to extend or reduce the filtering region. For example, a blur factor of 2.5 will increase the filtering region dimension to 250% of the original.

The effect of increasing the blur factor is to blur the image, making it smoother but less sharp. Reducing the blur factor makes the image sharper but less smooth.


ChartDirector Mark Up Language

ChartDirector Mark Up Language

ChartDirector Mark Up Language (CDML) is a language for including formatting information in text strings by marking up the text with tags.

CDML allows a single text string to be rendered using multiple fonts, with different colors, and even embed images in the text.

Font Styles

You can change the style of the text by using CDML tags. For example, the line:

<*font=timesi.ttf,size=16,color=FF0000*>Hello <*font=arial.ttf,size=12,color=8000*>world!

will result in the following text rendered:

In general, all tags in CDML are enclosed by <* and *>. Attributes within the tags determine the styles of the text following the tags within the same block.

If you want to include <* in text without being interpreted as CDML tags, use <<* as the escape sequence.

The following table describes the supported font style attributes in CDML. See Font Specification for details on various font attributes.

Attribute | Description
font | Starts a new style section, and sets the font name. You may use this attribute without a value (that is, use "font" instead of "font=arial.ttf") to create a new style section without modifying the font name.
size | The font size.
width | The font width. This attribute is used to set the font width and height to different values. If the width and height are the same, use the size attribute.
height | The font height. This attribute is used to set the font width and height to different values. If the width and height are the same, use the size attribute.
color | The text color in hex format.
bgColor | The background color of the text in hex format.
underline | The line width of the line used to underline the following characters. Set to 0 to disable underline.
sub | Set the following text to be in subscript style. This attribute does not need to have a value. (You may use "sub" as the attribute instead of "sub=1".)
super | Set the following text to be in superscript style. Set the following text to be in superscript style. This attribute does not need to have a value. (You may use "super" as the attribute instead of "super=1".)
xoffset | Draw the following the text by shifting the text horizontally from the original position by the specified offset in pixels.
yoffset | Draw the following the text by shifting the text vertically from the original position by the specified offset in pixels.
advance | Move the cursor forward (to the right) by the number of pixels as specified by the value this attribute.
advanceTo | Move the cursor forward (to the right) to the position as specified by the value this attribute. The position is specified as the number of pixels to the right of the left border of the block. If the cursor has already passed through the specified position, the cursor is not moved.

Note that unlike HTML tags, no double or single quotes are used in the tags. It is because CDML tags are often embedded as string literals in source code. The double or single quotes, if used, will conflict with the string literal quotes in the source code. Therefore in CDML, no quotes are necessary and they must not be used.

Also, unlike HTML tags, CDML uses the comma character as the delimiter between attributes. It is because certain attributes may contain embed spaces (such as the font file name). So space is not used as the delimiter and the comma character is used instead.

Note the font attribute above starts a new style section, while other attributes just modify the current style section. You may use <*/font*> to terminate a style section, which will restore the font styles to the state before the style section.

Blocks and Lines

In CDML, a text string may contain multiple blocks. A block may contain multiple lines of text by separating them with new line characters ("\n") or with <*br*>. The latter is useful for programming languages that cannot represent new line characters easily.

For example, the line:

<*size=15*><*block*><*color=FF*>BLOCK<*br*>ONE<*/*> and <*block*><*color=FF00*>BLOCK<*br*>TWO<*/*>

will result in the following text rendered:

The above example contains a line of text. The line contains two blocks with the characters " and " in between. Each block in turn contains two lines. The blocks are defined using <*block*> as the start tag and <*/*> as the end tag.

When a block ends, font styles will be restored to the state before entering the block.

Embedding Images

CDML supports embedding images in text using the following syntax:

<*img=my_image_file.png*>

where my_image_file.png is the path name of the image file.

For example, the line:

<*size=20*>A <*img=sun.png*> day

will result in the following text rendered:

ChartDirector will automatically detect the image file format using the file extension, which must either png, jpg, jpeg, gif, wbmp or wmp (case insensitive).

Please refer to BaseChart.setSearchPath or DrawArea.setSearchPath on the directory that ChartDirector will search for the file.

The <*img*> tag may optionally contain width and height attributes to specify its pixel width and height. In this case, ChartDirector will stretch or compress the image if necessary to the required width and height.

Blocks Attributes

CDML supports nesting blocks, that is, a block can contain other sub-blocks. Attributes are supported in the <*block*> tag to control the alignment and orientation of the sub-blocks. The <*img=my_image_file.png*> is treated as a block for layout purposes.

For example, the line:

<*block,valign=absmiddle*><*img=molecule.png*> <*block*>Hydrazino\nMolecule<*/*><*/*>

will result in the following text rendered:

The the above starts <*block,valign=absmiddle*> which specifies its content should align with each others in the vertical direction using the absolute middle alignment. The block contains an image, followed by a space characters, and then another block which has two lines of text.

The following table describes the supported attributes inside <*block*> tag:

Attribute | Description
width | The width of the block in pixels. By default, the width is automatically determined to be the width necessary for the contents of the block. If the width attribute is specified, it will be used as the width of the block. If the width is insufficient for the contents, the contents will be wrapped into multiple lines.
height | The height of the block in pixels. By default, the height is automatically determined to be the height necessary for the contents of the block. If the height attribute is specified, it will be used as the height of the block.
maxwidth | The maximum width of the block in pixels. If the content is wider than maximum width, it will be wrapped into multiple lines.
truncate | The maximum number of lines of the block. If the content requires more than the maximum number of lines, it will be truncated. In particular, if truncate is 1, the content will be truncated if it exceeds the maximum width (as specified by maxwidth or width) without wrapping. The last few characters at the truncation point will be replaced with "...".
linespacing | The spacing between lines as a ratio to the default line spacing. For example, a line spacing of 2 means the line spacing is two times the default line spacing. The default line spacing is the line spacing as specified in the font used.
bgColor | The background color of the block in hex format.
valignThe vertical alignment of sub-blocks. This is for blocks that contain sub-blocks. Supported values are baseline, top, bottom, middle and absmiddle.

The value baseline means the baseline of sub-blocks should align with the baseline of the block. The baseline is the underline position of text. This is normal method of aligning text, and is the default in CDML. For images or blocks that are rotated, the baseline is the same as the bottom.

The value top means the top line of sub-blocks should align with the top line of the block.

The value bottom means the bottom line of sub-blocks should align with the bottom line of the block.

The value middle means the middle line of sub-blocks should align with the the middle line of the block. The middle line is the middle position between the top line and the baseline.

The value absmiddle means the absolute middle line of sub-blocks should align with the absolute middle line of the block. The absolute middle line is the middle position between the top line and the bottom line.
halignThe horizontal alignment of lines. This is for blocks that contain multiple lines. Supported values are left, center and right.

The value left means the left border of each line should align with the left border of the block. This is the default.

The value center means the horizontal center of each line should align with the horizontal center of the block.

The value right means the right border of each line should align with the right border of the block.
angle | Rotate the content of the block by an angle. The angle is specified in degrees in counter-clockwise direction.


Parameter Substitution and Formatting

Parameter Substitution and Formatting

ChartDirector charts often contain a lot of text strings. For example, sector labels in pie charts, axis labels for x and y axes, data labels for the data points, HTML image maps, etc, are all text strings.

ChartDirector uses parameter substitution to allow you to configure precisely the information contained in the text and their format.

Format Strings

In parameter substitution, format strings are used to specify the entities to be include into labels and how to format numbers and dates.

For example, when drawing a pie chart with side label layout, the default sector label format string is:

"{label} ({percent}%)"

When the sector label is actually drawn, ChartDirector will replace "{label}" with the sector name, and "{percent}" with the sector percentage. So the above label format will result is a sector label similar to "ABC (34.56%)".

You may change the sector label format by changing the format string. For example, you may change it to:

"{label}: US${value|2}K ({percent}%)"

The sector label will then become something like "ABC: US$123.00 (34.56%)".

In general, in ChartDirector parameter substitution, parameters enclosed by curly brackets will be substituted with their actual values when creating the texts.

For parameters that are numbers or dates/times, ChartDirector supports a special syntax in parameter substitution to allow formatting for these values. Please refer to the Number Formatting and Date/Time Formatting sections below for details.

Parameter Expressions

ChartDirector supports numeric expressions in format strings. They are denoted by enclosing the expression with curly brackets and using "=" as the first character. For example:

"USD {value} (Euro {={value}*0.9})"

In the above, "{value}" will be substituted with the actual value of the sector. The expression "{={value}*0.9}" will be substituted with the actual value of the sector multiplied by 0.9.

ChartDirector parameter expressions support operators "+", "-", "*", "/", "%" (modulo) and "^" (exponentiation). Operators "*", "/", "%", "^" is computed first, followed by "+" and "-". Operators of the same precedence are computed from left to right). Parenthesis "(" and ")" can be used to change the computation order.

Parameters for Pie Charts

The following table describes the parameters available for pie charts.

Parameter | Description
sector | The sector number. The first sector is 0, while the nth sector is (n-1).
dataSet | Same as {sector}. See above.
label | The text label of the sector.
dataSetName | Same as {label}. See above.
value | The data value of the sector.
percent | The percentage value of the sector.
fieldN | The (N + 1)th extra field. For example, {field0} means the first extra field. An extra field is an array of custom elements added using BaseChart.addExtraField or BaseChart.addExtraField2.

Parameters for All XY Chart Layers

The followings are parameters that are apply to all XY Chart layers in general. Some layer types may have additional parameters (see below).

Note that certain parameters are inapplicable in some context. For example, when specifying the aggregate label of a stacked bar chart, the {dataSetName} parameter is inapplicable. It is because a stacked bar is composed of multiple data sets. It does not belong to any particular data set and hence does not have a data set name.

Parameter | Description
x | The x value of the data point. For an enumerated x-axis (see Axis.setLabels on what is an enumerated axis), the first data point is 0, and the nth data point is (n-1).
xLabel | The bottom x-axis label of the data point.
x2Label | The top x-axis label of the data point.
value | The value of the data point.
accValue | The sum of values of all data points that are in the same x position and same data group as the current data point, and with data set number less than or equal to the current data point. This is useful for stacked charts, such as stacked bar chart and stacked area chart.
totalValue | The sum of values of all data points that are in the same x position and same data group as the current data point. This is useful for stacked charts, such as stacked bar chart and stacked area chart.
percent | The percentage of the data point based on the total value of all data points that are in the same x position and same data group as the current data point. This is useful for stacked charts, such as stacked bar chart and stacked area chart.
accPercent | The accumulated percentage of the data point based on the total value of all data points that are in the same x position and same data group as the current data point. This is useful for stacked charts, such as stacked bar chart and stacked area chart.
gpercent | The percentage of the data point based on the total value of all data points in a layer.
dataSet | The data set number to which the data point belongs. The first data set is 0. The nth data set is (n-1).
dataSetName | The name of the data set to which the data point belongs.
dataItem | The data point number within the data set. The first data point is 0. The nth data point is (n-1).
dataGroup | The data group number to which the data point belongs. The first data group is 0. The nth data group is (n-1).
dataGroupName | The name of the data group to which the data point belongs.
layerId | The layer number to which the data point belongs. The first layer is 0. The nth layer is (n-1).
fieldN | The (N + 1)th extra field. For example, {field0} means the first extra field. An extra field is an array of custom elements added using Layer.addExtraField, Layer.addExtraField2, BaseChart.addExtraField or BaseChart.addExtraField2. {fieldN} means the extra field is indexed by the data point number. The Pth data point corresponds to the Pth element of the extra field.
diFieldN | Same as fieldN. See above.
dsFieldN | Similar to fieldN, except that dsFieldN means the extra field is indexed by data set number. The Pth data set corresponds to the Pth element of the extra field.
dsdiFieldN | Similar to fieldN, except that dsdiFieldN means the extra fields are indexed by both the data set number and data point number. The Pth data item of the Qth data set corresponds to the Pth element of the (N + Q)th extra field.

Additional Parameters for Line Layers

The followings are parameters that are in additional to the parameters for all XY Chart layers.

Parameter | Description
zx | The symbol scale in the x dimension. Applicable for layers with symbol scales set by LineLayer.setSymbolScale.
zy | The symbol scale in the y dimension. Applicable for layers with symbol scales set by LineLayer.setSymbolScale.
z | The symbol scale without distinguishing the dimension to use. Applicable for layers with symbol scales set by LineLayer.setSymbolScale.

Additional Parameters for Trend Layers

The followings are parameters that are in additional to the parameters for all XY Chart layers.

Parameter | Description
slope | The slope of the trend line.
intercept | The y-intercept of the trend line.
corr | The correlation coefficient in linear regression analysis.
stderr | The standard error in linear regression analysis.

Additional Parameters for Box-Whisker Layers

The followings are parameters that are in additional to the parameters for all XY Chart layers.

Parameter | Description
top | The value of the top edge of the box-whisker symbol.
bottom | The value of the bottom edge of the box-whisker symbol.
max | The value of the maximum mark of the box-whisker symbol.
min | The value of the minimum mark of the box-whisker symbol.
med | The value of the median mark of the box-whisker symbol.

Additional Parameters for HLOC and CandleStick Layers

The followings are parameters that are in additional to the parameters for all XY Chart layers.

Parameter | Description
high | The high value.
low | The low value.
open | The open value.
close | The close value.

Additional Parameters for Vector Layers

The followings are parameters that are in additional to the parameters for all XY Chart layers.

Parameter | Description
dir | The direction of the vector.
len | The length of the vector.

Parameters for All Polar Layers

The followings are parameters that are apply to all Polar Chart layers in general. Some layer types may have additional parameters (see below).

Parameter | Description
radius | The radial value of the data point.
value | Same as {radius}. See above.
angle | The angular value of the data point.
x | Same as {angle}. See above.
label | The angular label of the data point.
xLabel | Same as {label}. See above.
name | The name of the layer to which the data point belongs.
dataSetName | Same as {name}. See above.
i | The data point number. The first data point is 0. The nth data point is (n-1).
dataItem | Same as {i}. See above.
z | The symbol scale. Applicable for layers with symbol scales set by PolarLayer.setSymbolScale.
fieldN | The (N + 1)th extra field. For example, {field0} means the first extra field. An extra field is an array of custom elements added using Layer.addExtraField, Layer.addExtraField2, BaseChart.addExtraField or BaseChart.addExtraField2. {fieldN} means the extra field is indexed by the data point number. The Pth data point corresponds to the Pth element of the extra field.
diFieldN | Same as fieldN. See above.
dsFieldN | Similar to fieldN, except that dsFieldN means the extra field is indexed by layer index. The Pth layer corresponds to the Pth element of the extra field.
dsdiFieldN | Similar to fieldN, except that dsdiFieldN means the extra fields are indexed by both the data set number and data point number. The Pth data item of the Qth layer corresponds to the Pth element of the (N + Q)th extra field.

Additional Parameters for PolarVector Layers

The followings are parameters that are in additional to the parameters for all Polar Chart layers.

Parameter | Description
dir | The direction of the vector.
len | The length of the vector.

Parameters for Axis

The following table describes the parameters available for pie charts.

Parameter | Description
value | The axis value at the tick position.
label | The axis label at the tick position.

Number Formatting

For parameters that are numbers, ChartDirector supports a number of formatting options in parameter substitution.

For example, if you want a numeric field {value} to have a precision of two digits to the right of the decimal point, use ',' (comma) as the thousand separator, and use '.' (dot) as the decimal point, and you may use {value|2,.}. The number 123456.789 will then be displayed as 123,456.79.

For numbers, the formatting options are specified using the following syntax:

{[param]|[a][b][c][d]}

where:

Parameter | Description
[param] | The name of the parameter
[a]If this field a number, it specifies the number of decimal places (digits to the right of the decimal point).

If this field starts with "E" or "e", followed by a number, it means formatting the value using scientific notation with the specified number of decimal places. If the "E" or "e" is not followed by a number, 3 is assumed.

For example, {value|E4} will format the value 10.3 to 1.0300E+1, and {value|e4} will format the same value to 1.0300e+1.

If this field starts with "G" or "g", followed by a number, it means formatting the value using the scientific notation only if the value is large and requires more than the specified number of digits, or the value is less than 0.001. If scientific notation is used, the number following "G" or "g" also specifies the number of significant digits to use. If the "G" or "g" is not followed by a number, 4 is assumed.

For example, consider the format string {value|G4}. The value 10 will be formatted to 10. The value 100000 will be formatted to 1.000E+5. Similarly, for {value|g4}, the value 10 will be formatted to 10, while the value 100000 will be formatted to 1.000e+5.

If you skip this argument, ChartDirector will display the exact value using at most 6 decimal places.
[b] | The thousand separator. Should be a non-alphanumeric character (not 0-9, A-Z, a-z). Use '~' for no thousand separator. The default is '~', which can be modified using BaseChart.setNumberFormat.
[c] | The decimal point character. The default is '.', which can be modified using BaseChart.setNumberFormat.
[d] | The negative sign character. Use '~' for no negative sign character. The default is '-', which can be modified using BaseChart.setNumberFormat.

You may skip [b][c][d]. In this case, the default will be used.

Date/Time Formatting

For parameters that are dates/times, the formatting options can be specified using the following syntax:

{[param]|[datetime_format_string]}

where [datetime_format_string] must start with an english character (A-Z or a-z) that is not "G", "g", "E" or "e", and may contain any characters except '}'. (If it starts with "G", "g", "E" or "e", it will be considered as a number format string.)

Certain characters are substituted according to the following table. Characters that are not substituted will be copied to the output.

Parameter | Description
yyyy | The year in 4 digits (e.g. 2002)
yyy | The year showing only the least significant 3 digits (e.g. 002 for the year 2002)
yy | The year showing only the least significant 2 digits (e.g. 02 for the year 2002)
y | The year showing only the least significant 1 digits (e.g. 2 for the year 2002)
mmm | The month formatted as its name. The default is to use the first 3 characters of the english month name (Jan, Feb, Mar ...). The names can be configured using BaseChart.setMonthNames.
mm | The month formatted as 2 digits from 01 - 12, adding leading zero if necessary.
m | The month formatted using the minimum number of digits from 1 - 12.
MMM | The first 3 characters of the month name converted to upper case. The names can be configured using BaseChart.setMonthNames.
MM | The first 2 characters of the month name converted to upper case. The names can be configured using BaseChart.setMonthNames.
M | The first character of the month name converted to upper case. The names can be configured using BaseChart.setMonthNames.
dd | The day of month formatted as 2 digits from 01 - 31, adding leading zero if necessary.
d | The day of month formatted using the minimum number of digits from 1 - 31.
w | The name of the day of week. The default is to use the first 3 characters of the english day of week name (Sun, Mon, Tue ...). The names can be configured using BaseChart.setWeekDayNames.
hh | The hour of day formatted as 2 digits, adding leading zero if necessary. The 2 digits will be 00 - 23 if the 'a' option (see below) is not specified, otherwise it will be 01 - 12.
h | The hour of day formatted using the minimum number of digits. The digits will be 0 - 23 if the 'a' option (see below) is not specified, otherwise it will be 01 - 12.
nn | The minute formatted as 2 digits from 00 - 59, adding leading zero if necessary.
n | The minute formatted using the minimum number of digits from 00 - 59.
ss | The second formatted as 2 digits from 00 - 59, adding leading zero if necessary.
s | The second formatted using the minimum number of digits from 00 - 59.
a | Display either 'am' or 'pm', depending on whether the time is in the morning or afternoon. The text 'am' and 'pm' can be modified using BaseChart.setAMPM.

For example, a parameter substitution format of {value|mm-dd-yyyy} will display a date as something similar to 09-15-2002. A format of {value|dd/mm/yy hh:nn:ss a} will display a date as something similar to 15/09/02 03:04:05 pm.

If you want to include characters in the format string without substitution, you may enclose the characters in single or double quotes.

For example, the format {value|mmm '<*color=dd0000*>'yyyy} will display a date as something like Jan <*color=dd0000*>2005 (the <*color=dd0000*> is a CDML tag to specify red text color). Note that the <*color=dd0000*> tag is copied directly without substitution, even it contains "dd" which normally will be substituted with the day of month.

Escaping URL/HTML/CDML characters

Parameter substitution is often used to create HTML image maps. In HTML, some characters has special meanings and cannot be used reliably. For example, the '>' is used to represent the end of an HTML tag.

Furthermore, if the field happens to be used as an URL, characters such as '?', '&' and '+' also have special meanings.

By default, ChartDirector will escape template fields used in URL and query parameters when generating image maps. It will modify URL special characters to the URL escape format "%XX" (eg. "?" will become "%3F"). After that, it will modify HTML special characters to the HTML escape format "&s;#nn;" (eg. ">" will become "&s;#62;".). Similarly, it will escape other attributes in the image map using HTML escape format (but not URL escape format).

In addition to escaping HTML and URL special characters, ChartDirector will also remove CDML fields in creating image maps. It is because CDML is only interpreted in ChartDirector, should not be useful outside of ChartDirector (such as in browser tool tips).

In some cases, you may not want ChartDirector to escape the special characters. For example, if the parameters have already been escaped before passing to ChartDirector, you may want to disable ChartDirector from escaping them again.

ChartDirector supports the following special fields to control the escape methods - "{escape_url}", "{noescape_url}", "{escape_html}", "{noescape_html}", "{escape_cdml}" and {noescape_cdml}". These fields enable/disable the escape methods used in the template fields that follow them.


Internationalization

Internationalization

Internally, ChartDirector uses Unicode to handle text. It fully supports international characters (that is, non-English and non-ASCII characters).

International Fonts

For ChartDirector to draw an international character in an image, it must use the proper fonts. By default, ChartDirector uses the Arial font. If the Arial font does not contain characters you want to display, you may need to specify an alternative font that contains the characters you need.

You may change the default font by using BaseChart.setDefaultFonts or DrawArea.setDefaultFonts. ChartDirector API also allows changing the fonts in some particular text labels in the chart. For example, you may use the BaseChart.addTitle to specify the font for the chart title. Finally, you may use the ChartDirector Mark Up Language to specify the font used for any text.

Code Page

If you are using international characters as string literals in your source code, please make sure your programming language interpreter or compiler can understand the encoding of the international characters.

On a web environment, note that even if a web server can serve international web pages correctly, it does not mean that the the web server understands international characters. It may simply pass the characters transparently to the browser. For plain HTML web pages, only the browser needs to understand international characters and have the correct international fonts, not the server.

On the other hand, for ChartDirector applications, charts are rendered on the server side. Therefore, the server needs to understand the international characters and have the proper fonts installed, while there is no particular requirement for the browser.

To ensure ColdFusion can truly understand your encoding, you may need to use the pageEncoding attribute of the cfprocessingdirective tag. For example:

<cfprocessingdirective pageEncoding="big5" />

Number and Date/Time Formats

In ChartDirector, the decimal point, thousand separator and the names used for months, weekdays, etc., are all configurable.

For example, instead of using "." as the decimal point, you may configure ChartDirector to use "," as the decimal point using BaseChart.setNumberFormat, or by using Parameter Substitution and Formatting.

Similarly, instead of using "Sun", "Mon", "Tue", ... etc, for the weekday names in date formatting, you may use BaseChart.setWeekDayNames to supply another set of names. The same applies to month names using BaseChart.setMonthNames, and to AM/PM representation using BaseChart.setAMPM.