ChartDirector 5.1 (Java Edition)

ChartDirector
Version 5.1

Java Edition
Programmer's Manual

By Advanced Software Engineering Limited
© 2012 Advanced Software Engineering Limited. All rights reserved.
[ASE doc code: cddoc Java 5110]


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.

© 2012 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 security reasons, Microsoft Windows may only view CHM files properly if they are located on the local hard disk. CHM files located on network drives may not work properly. Please ensure the CHM file is copied to your local hard disk for reading.

Also, if the CHM file is downloaded from the Internet or copied from a network drive (as opposed to installed by an installer), Microsoft Windows may block the CHM file. You may need to "unblock" the CHM to read it. The steps are:

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

Welcome to ChartDirector

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

  • Comprehensive Chart Styles : Includes pie, donut, bar, line, spline, step-line, trending, curve-fitting, inter-line coloring, area, scatter, bubble, floating box, box-whisker, waterfall, finance, gantt, vector, contour, heat map, surface, 3D scatter, radar, polar line, polar area, polar spline, polar scatter, polar bubble, polar vector, rose, pyramid, cone and funnel. The x and y axes can be swapped. Bar charts can be horizontal or vertical, and so do line charts and other XY chart styles. Many chart styles also support 3D effects.

  • Meters and Gauges : Includes 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, Parabolic SAR, 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 box-whisker layer can used to add error bands to a bar chart. A scatter layer can be used to add symbols to specific points of a line chart. The possibilities are endless.

  • Interactive : Chart objects, such as bars in bar charts, slices in pie charts, legends and labels, etc, can have customizable tooltips and support mouse events. Programmable track cursors can dynamically update legend entries to show the data at the mouse cursor position as the mouse slides across the chart, with axis labels displaying the position of the mouse cursor. Mouse clicks and drags can be used to control zooming and scrolling of the chart.

  • AJAX Enabled For web applications, charts can be updated without reloading the web page. Interactive features are implemented in Javascript. No Flash, Applets or ActiveX controls are required.
  • 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.

  • Advanced Color System : ChartDirector's extended color system supports not only solid colors, but also semi-transparent 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.

  • CDML : 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.

    • Programming Languages

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

    • ASP / COM / Visual Basic / VBScript / JScript
    • .NET (C#, VB, C++/CLI and other CLI Languages)
    • Java
    • PHP
    • Perl
    • Python
    • Ruby
    • ColdFusion
    • C++

    Supported Platforms

    ChartDirector for Java and ColdFusion are written in pure Java and is platform independent. ChartDirector for ASP/COM/VB and .NET are supported on Windows 2000/2003/2008/Vista/XP/7. ChartDirector for PHP, Perl, Python, Ruby and C++ are supported on Windows 2000/2003/2008/Vista/XP/7, Linux, FreeBSD, Mac OS X and Solaris.


Installation

Installation

ChartDirector for JSP/Java contains the ChartDirector Java library, complete documentation, and sample code as JSP and as standalone Java programs.

ChartDirector for JSP/Java is distributed as a zip file, with a directory structure compatible with that of a JSP Web Application Archive (WAR). This allows ChartDirector for JSP/Java to be directly installed to a JSP web server as a web application.

Installing ChartDirector as a JSP Web Application

If you are planning to use ChartDirector in a JSP web server, you may consider to install ChartDirector as a JSP web application. To do this, simply rename the ".zip" file extension to ".war" and use it as a WAR. Virtually all JSP web servers support installing WAR. Please refer to your web server's documentation for details.

The advantages of installing ChartDirector as a web application are that the system will be set up automatically for running the sample code and testing ChartDirector. You can also easily uninstall ChartDirector by uninstalling the web application.

After installing ChartDirector as a JSP web application, you can access the ChartDirector documentation and sample code using:

http://server_name/context_path

where "context_path" is the path of the servlet context that you use during installation.

Most web servers will automatically extract (or unzip) the WAR file during installation. However, some web servers, such as Tomcat configured with unpackWARs="false", may use the WAR file directly without extracting it. In this case, ChartDirector will work normally, but you will be unable to modify the sample code and experiment with ChartDirector.

If your web server does not automatically extract WAR files, you may unzip the WAR file to a directory first, and install the extracted directory to the web server. You may then modify the sample code and experiment with ChartDirector.

Installing ChartDirector in a JSP Web Server Manually

If you do not want to automatically install ChartDirector using WAR, you can manually install the ChartDirector sample code by copying the necessary files.

  • Extract the ChartDirector for JSP/Java distribution into an empty directory.

  • Copy "WEB-INF/lib/ChartDirector.jar" to the "WEB-INF/lib" subdirectory of your web application.

  • Copy the entire sample code directory "jspdemo" to your web application.
For some JSP web servers, you may need to restart the web application after modifying the "WEB-INF/lib" subdirectory.

You may then access the sample code using:

http://server_name/context_path/jspdemo/index.htm

Using ChartDirector in Your Own Web Application

To use ChartDirector in your own web application, you need to:

  • Copy the ChartDirector Java library to your web application.

    The ChartDirector Java library is in "WEB-INF/lib/ChartDirector.jar". Please copy it to the "WEB-INF/lib" subdirectory of your web application.

  • (Optional) Map URL of the format "*.chart" to the ChartDirector.GetSessionImage servlet.

    This step is needed if you are writing servlet applications that do not use JSP. If you are using JSP, this step is usually not needed.

    To set up the servlet mapping, please enter the following lines in the "web.xml" file of your web application.

    <servlet>
 <servlet-name>GetSessionImage</servlet-name>
 <servlet-class>ChartDirector.GetSessionImage</servlet-class>
</servlet>

<servlet-mapping>
 <servlet-name>GetSessionImage</servlet-name>
 <url-pattern>*.chart</url-pattern>
</servlet-mapping>

    If you are using a front-end web server to forward servlet requests to a back-end servlet container (eg. using an Apache web server to forward servlet requests to a Tomcat servlet container), please set up your web server so that it forwards "*.chart" to the servlet container, otherwise the servlet container will not see the "*.chart" requests.

Installing ChartDirector for Standalone Applications

If you are planning to use ChartDirector for standalone Java programs, simply extract the ChartDirector for JSP/Java distribution to an empty directory. You can then compile and run the standalone sample programs in the "javademo" subdirectory:

[Microsoft Windows Command Shell Syntax]
javac -classpath "ChartDirector_s.jar;." ChartDirectorDemo.java
java -classpath "ChartDirector_s.jar;." ChartDirectorDemo

[Typical Linux/UNIX Command Shell Syntax]
javac -classpath ChartDirector_s.jar:. ChartDirectorDemo.java
java -classpath ChartDirector_s.jar:. ChartDirectorDemo

In the above, "ChartDirector_s.jar" is a light-weight version of the full "ChartDirector.jar" library. The light-weight version is for systems that support Java GUI. The full version is for systems that may not have GUI support (eg. some Linux/UNIX servers).

Using ChartDirector in Your Own Standalone Application

To use ChartDirector in your own application, you need to include the ChartDirector Java library in your application by including the ChartDirector library in your class path or Java project.

For Java GUI applications, you may use the light-weight version of the "ChartDirector_s.jar" located in the "javademo" subdirectory.

If you are writing a Java program that may run on a computer without a GUI (eg. some Linux/UNIX serves) and without Java "headless" mode support (see below), you can use the full version "ChartDirector.jar" located in the "WEB-INF/lib" subdirectory.

The full "ChartDirector.jar" contains an internal font system acting as a backup to the Java font system. Many Java systems on Linux/UNIX rely on X Window services to support fonts. On the other hand, may servers do not need GUI and so may not have X Window. In these cases, the Java font system will not work, and ChartDirector will automatically switch to its internal font system.

Java 1.4 or above can run in "headless mode" so that the Java font system is functional without relying on X Window. Please refer to the link below on how to enable "headless mode" in Java.

http://java.sun.com/j2se/1.4.2/docs/guide/awt/AWTChanges.html#headless

Javadoc for IDE Integration

Currently, ChartDirector documentation is not in Javadoc format. Instead, it is in both CHM and HTML formats, with the HTML format being similar to the CHM format. The CHM format is preferred because it has integrated search facility, better indexing features, supports bookmarks, and is easier to print.

If you are currently reading the ChartDirector documentation in HTML format, and you are using a Microsoft Windows computer, you are recommended to download the CHM documentation from http://www.advsofteng.com/download.html.

Some integrated development environments (IDE) can import "Javadoc" and use it to provide "intellisense" tool tips in the source code editor. To support these features, ChartDirector includes "Javadoc" in the "ide_javadoc" subdirectory. Note that the "Javadoc" does not contain any text for human reading. It just contains the ChartDirector API prototypes to allow the IDE to pop up prototypes with proper parameter names in "intellisense". For human reading, please use the CHM (recommended) or standard HTML documentation.

Installing the ChartDirector License

If you have purchased a license to use ChartDirector, you should have a license key 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 key in that line. The whole file should contain only the license key. Name that file "chartdir.lic" and put the file in the Java class path visible to "ChartDirector.jar" (eg. "WEB-INF/classes" in a web application, or the class path of the main class in a standalone application).

    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]/jspdemo/cdinfo.jsp" 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 Chart.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).

    Chart.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 JSP Project
The "Hello World" project for using ChartDirector in an JSP web application - creating a simple bar chart to explore using ChartDirector in your development environment.

The First Java Project
The "Hello World" project for using ChartDirector in standalone application - 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 JSP Project

The First JSP Project

This section introduces using ChartDirector in JSP . If you are using ChartDirector in standalone Java application, you may refer to The First Java Project instead.

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.

The following code is based on the sample programs that come with ChartDirector. If you have not yet installed the sample programs, it is highly recommended you install them now. Please refer to the Installation section for details. They are very useful for exploring and testing the features of ChartDirector.

[JSP Version] jspdemo/simplebar.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the bar chart
double[] data = {85, 156, 179.5, 211, 123};

// The labels for the bar chart
String[] labels = {"Mon", "Tue", "Wed", "Thu", "Fri"};

// Create a XYChart object of size 250 x 250 pixels
XYChart c = new 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
String chart1URL = c.makeSession(request, "chart1");

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "", "title='{xLabel}: US${value}K'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Simple Bar Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

The code is explained below:

  • <%@page import="ChartDirector.*" %>

    The above line imports the ChartDirector namespace into the program to simplify the code. Instead of writing "ChartDirector.XYChart", you can simply write "XYChart".

  • XYChart c = new 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.

  • 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.

  • String chart1URL = c.makeSession(request, "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.

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

    After displaying the chart, 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='<%=response.encodeURL("getchart.jsp?"+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.jsp?"+chart1URL). The getchart.jsp is a standard JSP 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.

    ChartDirector also comes with a GetSessionImage servlet that provides the same function as getchart.jsp. This servlet is useful for servlet applications that do not use JSP.

    The response.encodeURL method above is a method of the standard Java class javax.servlet.http.HttpServletResponse. It encodes the URL if the browser does not support cookies, so as to ensure session variables can work without using cookies.

    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.


The First Java Project

The First Java Project

This section introduces using ChartDirector in standalone Java application. If you are using ChartDirector in JSP, you may refer to The First JSP Project instead.

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.

The following code is based on the sample programs that come with ChartDirector. If you have not yet installed the sample programs, it is highly recommended you install them now. Please refer to the Installation section for details. They are very useful for exploring and testing the features of ChartDirector.

The following code module contains the static "main" method that allows it to run as a standalone program. It also implements the "DemoModule" interface, which allows it to run as part of the ChartDirectorDemo sample code browsing program (javademo/ChartDirectorDemo.java).

[Java Version] javademo/simplebar.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class simplebar implements DemoModule
{
    //Name of demo program
    public String toString() { return "Simple Bar Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the bar chart
        double[] data = {85, 156, 179.5, 211, 123};

        // The labels for the bar chart
        String[] labels = {"Mon", "Tue", "Wed", "Thu", "Fri"};

        // Create a XYChart object of size 250 x 250 pixels
        XYChart c = new 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
        viewer.setChart(c);

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

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new simplebar();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}

The code is explained below:

  • import ChartDirector.*;

    The above line imports the ChartDirector namespace into the program to simplify the code. Instead of writing "ChartDirector.XYChart", you can simply write "XYChart".

  • XYChart c = new 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.

  • 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.

  • viewer.setChart(c);

    Up to this point, the chart is completed. In this project, we output the chart to the ChartViewer component for display.

    The ChartViewer component is an extension to the javax.swing.JLabel component. In addition to displaying the chart, it also supports tool tips on data points and other mouse interactions.

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

    After displaying the chart, 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.

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 subclass of the BaseChart class. 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 but are not true 3D chart types.

    • ThreeDChart : Base class for all true 3D chart types

      • SurfaceChart : Represents surface charts.

      • ThreeDScatterChart : Represents 3D scatter charts.

    • PolarChart : Represents all charts that uses polar coordinates.

    • PyramidChart : Represents pyramid, cone and funnel charts.

    • 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 but are not true 3D chart types. 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 layers, such as simple bar layers, multi-bar layers, stacked bar layers, and percentage bar layers.
LineLayer | Represent line layers.
SplineLayer | Represent spline line layers.
StepLineLayer | Represent step line layers.
TrendLayer | Represent trend layers. A trend line or curve is the best fit line or curve 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 layers.
AreaLayer | Represent area layers.
HLOCLayer | Represent high-low-open-close layers.
CandleStickLayer | Represent candlestick layers.
BoxWhiskerLayer | Represent box-whisker layers.
VectorLayer | Represents vector layers.
ContourLayer | Represents contour layers.

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.

ThreeDChart

The ThreeDChart class is the base class for true 3D chart types. It represents features common to all true 3D chart types, such as controlling the elevation, rotation and twist angles, 3D perspective, 3D plot region position, size and the style of the boundary walls.

SurfaceChart

The SurfaceChart class represents surface charts. A surface chart is a true 3D chart representing the value of a variable (the z coordinate) over the (x, y) plane.

ThreeDScatterChart

The ThreeDScatterChart class represents 3D scatter charts. A scatter chart is a true 3D chart representing (x, y, z) data points with symbols. A single chart can control multiple groups of symbols of different styles, represented using ThreeDScatterGroup objects.

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 layers, as well as scatter and bubble layers. (A scatter layer is a line layer with line set to Transparent. A bubble layer is a scatter layer in which the data symbols are of variable sizes.)
PolarAreaLayer | Represent area layers.
PolarSplineLineLayer | Represent spline line layers.
PolarSplineAreaLayer | Represent spline area layers.
PolarVectorLayer | Represent vector layers.

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

PyramidChart

The PyramidChart class represents pyramid, cone and funnel charts. PyramidChart objects contain PyramidLayer objects, which represent the layers in the pyramid, cone and funnel charts.

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 | Demonstrates the "side label layout" method for positioning the sector labels. Also demonstrates metallic background colors, and sector labels with glass shading effect and rounded corners.
Circular Label Layout | Demonstrates label positioning in the "circular label layout" method.
Pie Chart with Legend (1) | Demonstrates how to add a legend box to a pie chart. Also demonstrates alternative sector label format and rounded edge sector shading.
Pie Chart with Legend (2) | Demonstrates a pie chart with a legend box, together with many effects, such as gradient color background, rounded frame, soft drop shadow, custom sector colors, sector gradient shading, customized sector labels and using CDML and Parameter Substitution and Formatting to format legend text.
Exploded Pie Chart | Demonstrates a pie chart with all sectors exploded. Also demonstrates many effects, such as gradient color background, rounded frame, soft drop shadow, custom sector colors, sector gradient shading, thick sector border, and using CDML and Parameter Substitution and Formatting to format sector labels.
Icon Pie Chart (1) | 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 with ring shading effects. Also demonstrates brushed metal background, rounded frame, customized sector labels and using CDML and Parameter Substitution and Formatting to format legend text.
3D Donut Chart | Demonstrates a 3D donut chart with sector gradient shading. Also demonstrates gradient color background, rounded frame, custom sector colors, and using CDML and Parameter Substitution and Formatting to format 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.
2D Pie Shading | Demonstrates various sector shading effects applicable to 2D pie charts.
3D Pie Shading | Demonstrates various sector shading effects applicable to 3D pie charts.
2D Donut Shading | Demonstrates various sector shading effects applicable to 2D donut charts.
3D Donut Shading | Demonstrates various sector shading effects applicable to 3D donut charts.
Text Styles and Colors | Demonstrates various text styles, text colors, background colors and text box border 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 size of the pyramid using PieChart.setPieSize.

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

  • Generate the chart using BaseChart.makeSession (JSP version) or BaseChart.makeImage (Java version).

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

Source Code Listing

[JSP Version] jspdemo/simplepie.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the pie chart
double[] data = {25, 18, 15, 12, 8, 30, 35};

// The labels for the pie chart
String[] labels = {"Labor", "Licenses", "Taxes", "Legal", "Insurance", "Facilities",
    "Production"};

// Create a PieChart object of size 360 x 300 pixels
PieChart c = new 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
String chart1URL = c.makeSession(request, "chart1");

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{label}: US${value}K ({percent}%)'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Simple Pie Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/simplepie.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class simplepie implements DemoModule
{
    //Name of demo program
    public String toString() { return "Simple Pie Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the pie chart
        double[] data = {25, 18, 15, 12, 8, 30, 35};

        // The labels for the pie chart
        String[] labels = {"Labor", "Licenses", "Taxes", "Legal", "Insurance",
            "Facilities", "Production"};

        // Create a PieChart object of size 360 x 300 pixels
        PieChart c = new 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
        viewer.setChart(c);

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

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new simplepie();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/threedpie.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the pie chart
double[] data = {25, 18, 15, 12, 8, 30, 35};

// The labels for the pie chart
String[] labels = {"Labor", "Licenses", "Taxes", "Legal", "Insurance", "Facilities",
    "Production"};

// Create a PieChart object of size 360 x 300 pixels
PieChart c = new 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
String chart1URL = c.makeSession(request, "chart1");

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{label}: US${value}K ({percent}%)'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    3D Pie Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/threedpie.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class threedpie implements DemoModule
{
    //Name of demo program
    public String toString() { return "3D Pie Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the pie chart
        double[] data = {25, 18, 15, 12, 8, 30, 35};

        // The labels for the pie chart
        String[] labels = {"Labor", "Licenses", "Taxes", "Legal", "Insurance",
            "Facilities", "Production"};

        // Create a PieChart object of size 360 x 300 pixels
        PieChart c = new 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
        viewer.setChart(c);

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

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new threedpie();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/multidepthpie.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the pie chart
double[] data = {72, 18, 15, 12};

// The labels for the pie chart
String[] labels = {"Labor", "Machinery", "Facilities", "Computers"};

// The depths for the sectors
double[] depths = {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
PieChart c = new 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
String chart1URL = c.makeSession(request, "chart1");

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{label}: US${value}K ({percent}%)'");
%>
<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 color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/multidepthpie.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class multidepthpie implements DemoModule
{
    //Name of demo program
    public String toString() { return "Multi-Depth Pie Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the pie chart
        double[] data = {72, 18, 15, 12};

        // The labels for the pie chart
        String[] labels = {"Labor", "Machinery", "Facilities", "Computers"};

        // The depths for the sectors
        double[] depths = {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
        PieChart c = new 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
        viewer.setChart(c);

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

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new multidepthpie();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


Side Label Layout

Side Label Layout

This example demonstrates the "side label layout" method for positioning the sector labels. It also demonstrates metallic background colors, and sector labels with glass shading effect and rounded corners.

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.

"Side label layout" has the advantages that the labels will automatically shift up and down to avoid overlapping. In the above chart, there are a number of small sectors at the bottom-right of the pie. Note that the labels are shifted to avoid overlapping.

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

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

  • The side label layout method is specified with PieChart.setLabelLayout.

  • The glass shading effect of the sector labels is defined using Chart.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.
This example demonstrates a technique for further improving label layout by adjusting the start angle of the first sector using PieChart.setStartAngle.

If the data have a lot of small values and are sorted, the small sectors will be crowded together. For these cases, label layout will be optimal (with the least shifting required) if the small sectors are at the left or right side of the pie, rather than at the top or bottom.

If the data are in descending order (like this example), a start angle of 135 degrees with clockwise sector layout can be used to put the small sectors at approximately 45 - 135 degrees (the right side of the pie). If the data are in ascending order, a start angle of 45 degrees with clockwise sector layout can be used to achieve similar effects.

Source Code Listing

[JSP Version] jspdemo/sidelabelpie.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the pie chart
double[] data = {35, 30, 25, 7, 6, 5, 4, 3, 2, 1};

// The labels for the pie chart
String[] labels = {"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
PieChart c = new PieChart(560, 270, Chart.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(Chart.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(Chart.SideLayout);

// Set the label box background color the same as the sector color, with glass
// effect, and with 5 pixels rounded corners
TextBox t = c.setLabelStyle();
t.setBackground(Chart.SameAsMainColor, Chart.Transparent, Chart.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(Chart.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
String chart1URL = c.makeSession(request, "chart1");

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{label}: US${value}K ({percent}%)'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Side Label Layout
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/sidelabelpie.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class sidelabelpie implements DemoModule
{
    //Name of demo program
    public String toString() { return "Side Label Layout"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the pie chart
        double[] data = {35, 30, 25, 7, 6, 5, 4, 3, 2, 1};

        // The labels for the pie chart
        String[] labels = {"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
        PieChart c = new PieChart(560, 270, Chart.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(Chart.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(Chart.SideLayout);

        // Set the label box background color the same as the sector color, with
        // glass effect, and with 5 pixels rounded corners
        TextBox t = c.setLabelStyle();
        t.setBackground(Chart.SameAsMainColor, Chart.Transparent, Chart.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(Chart.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
        viewer.setChart(c);

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

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new sidelabelpie();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


Circular Label Layout

Circular Label Layout

This example demonstrates label positioning in the "circular label layout" method.

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

The PieChart.setLabelPos method can be used to control the distance between the labels and the pie perimeter, and add join lines to connect the labels to the sectors. The join lines are useful if the labels are far away from the pie perimeter.

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

Source Code Listing

[JSP Version] jspdemo/circlelabelpie.jsp
<%@page import="ChartDirector.*" %>
<%@page import="javax.servlet.http.*" %>
<%!
// A simple structure to represent a chart image with an image map
private static class ImageWithHotSpot
{
    String imageURL;
    String imageMap;
}

// Function to create the demo charts
ImageWithHotSpot createChart(HttpServletRequest request, int index)
{
    // The data for the pie chart
    double[] data = {42, 18, 8};

    // The labels for the pie chart
    String[] labels = {"Agree", "Disagree", "Not Sure"};

    // The colors to use for the sectors
    int[] colors = {0x66ff66, 0xff6666, 0xffff00};

    // Create a PieChart object of size 300 x 300 pixels. Set the background to a
    // gradient color from blue (aaccff) to sky blue (ffffff), with a grey (888888)
    // border. Use rounded corners and soft drop shadow.
    PieChart c = new PieChart(300, 300);
    c.setBackground(c.linearGradientColor(0, 0, 0, c.getHeight() / 2, 0xaaccff,
        0xffffff), 0x888888);
    c.setRoundedFrame();
    c.setDropShadow();

    if (index == 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, Chart.LineColor);

    }

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

    // Set the sector colors
    c.setColors2(Chart.DataColor, colors);

    // Use local gradient shading, with a 1 pixel semi-transparent black (bb000000)
    // border
    c.setSectorStyle(Chart.LocalGradientShading, 0xbb000000, 1);

    // Output the chart
    ImageWithHotSpot ret = new ImageWithHotSpot();
    ret.imageURL = c.makeSession(request, "chart" + index);

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

    return ret;
}
%>
<%
ImageWithHotSpot chart0 = createChart(request, 0);
ImageWithHotSpot chart1 = createChart(request, 1);
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Circular Label Layout
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart0.imageURL)%>'
    usemap="#map0" border="0">
<map name="map0"><%=chart0.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1.imageURL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=chart1.imageMap%></map>
</body>
</html>

[Java Version] javademo/circlelabelpie.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class circlelabelpie implements DemoModule
{
    //Name of demo program
    public String toString() { return "Circular Label Layout"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 2; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the pie chart
        double[] data = {42, 18, 8};

        // The labels for the pie chart
        String[] labels = {"Agree", "Disagree", "Not Sure"};

        // The colors to use for the sectors
        int[] colors = {0x66ff66, 0xff6666, 0xffff00};

        // Create a PieChart object of size 300 x 300 pixels. Set the background to a
        // gradient color from blue (aaccff) to sky blue (ffffff), with a grey
        // (888888) border. Use rounded corners and soft drop shadow.
        PieChart c = new PieChart(300, 300);
        c.setBackground(c.linearGradientColor(0, 0, 0, c.getHeight() / 2, 0xaaccff,
            0xffffff), 0x888888);
        c.setRoundedFrame();
        c.setDropShadow();

        if (index == 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, Chart.LineColor);

        }

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

        // Set the sector colors
        c.setColors2(Chart.DataColor, colors);

        // Use local gradient shading, with a 1 pixel semi-transparent black
        // (bb000000) border
        c.setSectorStyle(Chart.LocalGradientShading, 0xbb000000, 1);

        // Output the chart
        viewer.setChart(c);

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

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new circlelabelpie();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);
        frame.getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
        frame.setSize(800, 450);

        // Create the charts and put them in the content pane
        for (int i = 0; i < demo.getNoOfCharts(); ++i)
        {
            ChartViewer viewer = new ChartViewer();
            demo.createChart(viewer, i);
            frame.getContentPane().add(viewer);
        }

        // Display the window
        frame.setVisible(true);
    }
}


Pie Chart with Legend (1)

Pie Chart with Legend (1)

This example demonstrates how to add a legend box to a pie chart. It also demonstrates alternative sector label format and rounded edge sector shading.

  • Add a legend box using BaseChart.addLegend.

  • Change the sector label format using PieChart.setLabelFormat.

  • Set rounded edge sector shading using PieChart.setSectorStyle.

Source Code Listing

[JSP Version] jspdemo/legendpie.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the pie chart
double[] data = {25, 18, 15, 12, 8, 30, 35};

// The labels for the pie chart
String[] labels = {"Labor", "Licenses", "Taxes", "Legal", "Insurance", "Facilities",
    "Production"};

// Create a PieChart object of size 450 x 270 pixels
PieChart c = new PieChart(450, 270);

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

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

// modify the sector label format to show percentages only
c.setLabelFormat("{percent}%");

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

// Use rounded edge shading, with a 1 pixel white (FFFFFF) border
c.setSectorStyle(Chart.RoundedEdgeShading, 0xffffff, 1);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{label}: US${value}K ({percent}%)'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Pie Chart with Legend (1)
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/legendpie.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class legendpie implements DemoModule
{
    //Name of demo program
    public String toString() { return "Pie Chart with Legend (1)"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the pie chart
        double[] data = {25, 18, 15, 12, 8, 30, 35};

        // The labels for the pie chart
        String[] labels = {"Labor", "Licenses", "Taxes", "Legal", "Insurance",
            "Facilities", "Production"};

        // Create a PieChart object of size 450 x 270 pixels
        PieChart c = new PieChart(450, 270);

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

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

        // modify the sector label format to show percentages only
        c.setLabelFormat("{percent}%");

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

        // Use rounded edge shading, with a 1 pixel white (FFFFFF) border
        c.setSectorStyle(Chart.RoundedEdgeShading, 0xffffff, 1);

        // Output the chart
        viewer.setChart(c);

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

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new legendpie();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


Pie Chart with Legend (2)

Pie Chart with Legend (2)

This example demonstrates a pie chart with a legend box, together with many effects, such as gradient color background, rounded frame, soft drop shadow, custom sector colors, sector gradient shading, customized sector labels and using CDML and Parameter Substitution and Formatting to format legend text.

  • The gradient background is achieved by using BaseChart.linearGradientColor to define the gradient color, then use BaseChart.setBackground to set it as the chart background color.

  • The rounded frame is configured using BaseChart.setRoundedFrame.

  • The soft drop shadow is configured using BaseChart.setDropShadow.

  • The sector colors are set using BaseChart.setColors. The sector gradient shading is configured using PieChart.setSectorStyle.

  • The sector labels are configured using PieChart.setLabelFormat to show the sector number. PieChart.setLabelStyle is used to set the label style. It returns a TextBox object representing the sector label prototype. The Box.setBackground method of the label prototype is then used to add black borders around the labels.

  • The legend text is configured by calling the TextBox.setText method of the LegendBox object. The legend text template is specified using CDML and Parameter Substitution and Formatting as follows:

    <*block,valign=top*>{={sector}+1}.<*advanceTo=22*><*block,width=120*>{label}<*/*><*block,width=40,halign=right*>{percent}<*/*>%

    The starting "<*block,valign=top*>" means the different parts in the legend entry should be aligned to the top. This is necessarily because the second part of the legend entry (described below) can have multiple lines.

    The first part of the legend entry is "{={sector}+1}.<*advanceTo=22*>", which means the show the sector number, then "tab" to the 22th pixel position. (In ChartDirector, the sector number starts from 0. So we add 1 to {sector} to make the displayed sector number to start from 1.)

    The second part "<*block,width=120*>{label}<*/*>" which means to show the sector label in a 120 pixels block. If the label is wider than 120 pixels, it will be wrapped into multiple lines within the block.

    The last part "<*block,width=40,halign=right*>{percent}<*/*>%" means to show the percentage in a 40 pixels block, with the contents right aligned.

Source Code Listing

[JSP Version] jspdemo/legendpie2.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the pie chart
double[] data = {21, 18, 15, 12, 8, 24};

// The labels for the pie chart
String[] labels = {"Labor", "Licenses", "Taxes", "Legal", "Facilities", "Production"}
    ;

// The colors to use for the sectors
int[] colors = {0x66aaee, 0xeebb22, 0xbbbbbb, 0x8844ff, 0xdd2222, 0x009900};

// Create a PieChart object of size 600 x 320 pixels. Use a vertical gradient color
// from light blue (99ccff) to white (ffffff) spanning the top 100 pixels as
// background. Set border to grey (888888). Use rounded corners. Enable soft drop
// shadow.
PieChart c = new PieChart(600, 320);
c.setBackground(c.linearGradientColor(0, 0, 0, 100, 0x99ccff, 0xffffff), 0x888888);
c.setRoundedFrame();
c.setDropShadow();

// Add a title using 18 pts Times New Roman Bold Italic font. Add 16 pixels top
// margin to the title.
c.addTitle("Pie Chart With Legend Demonstration", "Times New Roman Bold Italic", 18
    ).setMargin2(0, 0, 16, 0);

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

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

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

// Set the sector colors
c.setColors2(Chart.DataColor, colors);

// Use local gradient shading for the sectors
c.setSectorStyle(Chart.LocalGradientShading);

// Use the side label layout method, with the labels positioned 16 pixels from the
// pie bounding box
c.setLabelLayout(Chart.SideLayout, 16);

// Show only the sector number as the sector label
c.setLabelFormat("{={sector}+1}");

// Set the sector label style to Arial Bold 10pt, with a dark grey (444444) border
c.setLabelStyle("Arial Bold", 10).setBackground(Chart.Transparent, 0x444444);

// Add a legend box, with the center of the left side anchored at (330, 175), and
// using 10 pts Arial Bold Italic font
LegendBox b = c.addLegend(330, 175, true, "Arial Bold Italic", 10);
b.setAlignment(Chart.Left);

// Set the legend box border to dark grey (444444), and with rounded conerns
b.setBackground(Chart.Transparent, 0x444444);
b.setRoundedCorners();

// Set the legend box margin to 16 pixels, and the extra line spacing between the
// legend entries as 5 pixels
b.setMargin(16);
b.setKeySpacing(0, 5);

// Set the legend box icon to have no border (border color same as fill color)
b.setKeyBorder(Chart.SameAsMainColor);

// Set the legend text to show the sector number, followed by a 120 pixels wide block
// showing the sector label, and a 40 pixels wide block showing the percentage
b.setText(
    "<*block,valign=top*>{={sector}+1}.<*advanceTo=22*><*block,width=120*>{label}" +
    "<*/*><*block,width=40,halign=right*>{percent}<*/*>%");

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{label}: US${value}K ({percent}%)'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Pie Chart with Legend (2)
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/legendpie2.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class legendpie2 implements DemoModule
{
    //Name of demo program
    public String toString() { return "Pie Chart with Legend (2)"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the pie chart
        double[] data = {21, 18, 15, 12, 8, 24};

        // The labels for the pie chart
        String[] labels = {"Labor", "Licenses", "Taxes", "Legal", "Facilities",
            "Production"};

        // The colors to use for the sectors
        int[] colors = {0x66aaee, 0xeebb22, 0xbbbbbb, 0x8844ff, 0xdd2222, 0x009900};

        // Create a PieChart object of size 600 x 320 pixels. Use a vertical gradient
        // color from light blue (99ccff) to white (ffffff) spanning the top 100
        // pixels as background. Set border to grey (888888). Use rounded corners.
        // Enable soft drop shadow.
        PieChart c = new PieChart(600, 320);
        c.setBackground(c.linearGradientColor(0, 0, 0, 100, 0x99ccff, 0xffffff),
            0x888888);
        c.setRoundedFrame();
        c.setDropShadow();

        // Add a title using 18 pts Times New Roman Bold Italic font. Add 16 pixels
        // top margin to the title.
        c.addTitle("Pie Chart With Legend Demonstration",
            "Times New Roman Bold Italic", 18).setMargin2(0, 0, 16, 0);

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

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

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

        // Set the sector colors
        c.setColors2(Chart.DataColor, colors);

        // Use local gradient shading for the sectors
        c.setSectorStyle(Chart.LocalGradientShading);

        // Use the side label layout method, with the labels positioned 16 pixels
        // from the pie bounding box
        c.setLabelLayout(Chart.SideLayout, 16);

        // Show only the sector number as the sector label
        c.setLabelFormat("{={sector}+1}");

        // Set the sector label style to Arial Bold 10pt, with a dark grey (444444)
        // border
        c.setLabelStyle("Arial Bold", 10).setBackground(Chart.Transparent, 0x444444);

        // Add a legend box, with the center of the left side anchored at (330, 175),
        // and using 10 pts Arial Bold Italic font
        LegendBox b = c.addLegend(330, 175, true, "Arial Bold Italic", 10);
        b.setAlignment(Chart.Left);

        // Set the legend box border to dark grey (444444), and with rounded conerns
        b.setBackground(Chart.Transparent, 0x444444);
        b.setRoundedCorners();

        // Set the legend box margin to 16 pixels, and the extra line spacing between
        // the legend entries as 5 pixels
        b.setMargin(16);
        b.setKeySpacing(0, 5);

        // Set the legend box icon to have no border (border color same as fill
        // color)
        b.setKeyBorder(Chart.SameAsMainColor);

        // Set the legend text to show the sector number, followed by a 120 pixels
        // wide block showing the sector label, and a 40 pixels wide block showing
        // the percentage
        b.setText(
            "<*block,valign=top*>{={sector}+1}.<*advanceTo=22*><*block,width=120*>" +
            "{label}<*/*><*block,width=40,halign=right*>{percent}<*/*>%");

        // Output the chart
        viewer.setChart(c);

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

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new legendpie2();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


Exploded Pie Chart

Exploded Pie Chart

This example demonstrates a pie chart with all sectors exploded. It also demonstrates many effects, such as gradient color background, rounded frame, soft drop shadow, custom sector colors, sector gradient shading, thick sector border, and using CDML and Parameter Substitution and Formatting to format sector labels.

  • The gradient background is achieved by using BaseChart.linearGradientColor to define the gradient color, then use BaseChart.setBackground to set it as the chart background color.

  • The rounded frame is configured using BaseChart.setRoundedFrame.

  • The soft drop shadow is configured using BaseChart.setDropShadow.

  • The sector colors are set using BaseChart.setColors. The sector gradient shading and thick sector border is configured using PieChart.setSectorStyle.

  • The sector label style are configured using PieChart.setLabelStyle. It returns a TextBox object representing the sector label prototype. The gradient background color and rounded corners of the sector labels are configured using the Box.setBackground and Box.setRoundedCorners methods of the label prototype.

  • The sector label contents are configured using PieChart.setLabelFormat. The template is specified using CDML and Parameter Substitution and Formatting. It consists of two lines using different fonts. This first line shows the sector label, while the second line shows the sector value and percentage.

Source Code Listing

[JSP Version] jspdemo/explodedpie.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the pie chart
double[] data = {21, 18, 15, 12, 8, 24};

// The labels for the pie chart
String[] labels = {"Labor", "Licenses", "Taxes", "Legal", "Facilities", "Production"}
    ;

// The colors to use for the sectors
int[] colors = {0x66aaee, 0xeebb22, 0xbbbbbb, 0x8844ff, 0xdd2222, 0x009900};

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

// Use the white on black palette, which means the default text and line colors are
// white
c.setColors(Chart.whiteOnBlackPalette);

// Use a vertical gradient color from deep blue (000066) to blue (0000cc) as
// background. Use rounded corners of 20 pixels radius. Enable soft drop shadow.
c.setBackground(c.linearGradientColor(0, 0, 0, c.getHeight(), 0x000066, 0x0000cc));
c.setRoundedFrame(0xffffff, 20);
c.setDropShadow();

// Add a title using 18 pts Times New Roman Bold Italic font. Add 16 pixels top
// margin to the title.
c.addTitle("Exploded Pie Chart Demonstration", "Times New Roman Bold Italic", 18
    ).setMargin2(0, 0, 16, 0);

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

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

// Set the sector colors
c.setColors2(Chart.DataColor, colors);

// Use local gradient shading for the sectors, with 5 pixels wide semi-transparent
// white (bbffffff) borders
c.setSectorStyle(Chart.LocalGradientShading, 0xbbffffff, 5);

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

// Use 10pt Arial Bold as the default label font. Set the label box background color
// the same as the sector color. Use soft lighting effect with light direction from
// right. Use 8 pixels rounded corners.
TextBox t = c.setLabelStyle("Arial Bold", 10, 0x000000);
t.setBackground(Chart.SameAsMainColor, Chart.Transparent, Chart.softLighting(
    Chart.Right, 0));
t.setRoundedCorners(8);

// Set the sector label format. The label is centered in a 110 pixels wide bounding
// box. It consists of two lines. The first line is the sector name. The second line
// shows the data value and percentage.
c.setLabelFormat(
    "<*block,halign=center,width=110*>{label}\n<*font=Arial,size=8*>US$ {value}M " +
    "({percent}%)<*/*>");

// Explode all sectors 10 pixels from the center
c.setExplode(-1, 10);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{label}: US${value}M ({percent}%)'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Exploded Pie Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/explodedpie.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class explodedpie implements DemoModule
{
    //Name of demo program
    public String toString() { return "Exploded Pie Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the pie chart
        double[] data = {21, 18, 15, 12, 8, 24};

        // The labels for the pie chart
        String[] labels = {"Labor", "Licenses", "Taxes", "Legal", "Facilities",
            "Production"};

        // The colors to use for the sectors
        int[] colors = {0x66aaee, 0xeebb22, 0xbbbbbb, 0x8844ff, 0xdd2222, 0x009900};

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

        // Use the white on black palette, which means the default text and line
        // colors are white
        c.setColors(Chart.whiteOnBlackPalette);

        // Use a vertical gradient color from deep blue (000066) to blue (0000cc) as
        // background. Use rounded corners of 20 pixels radius. Enable soft drop
        // shadow.
        c.setBackground(c.linearGradientColor(0, 0, 0, c.getHeight(), 0x000066,
            0x0000cc));
        c.setRoundedFrame(0xffffff, 20);
        c.setDropShadow();

        // Add a title using 18 pts Times New Roman Bold Italic font. Add 16 pixels
        // top margin to the title.
        c.addTitle("Exploded Pie Chart Demonstration", "Times New Roman Bold Italic",
            18).setMargin2(0, 0, 16, 0);

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

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

        // Set the sector colors
        c.setColors2(Chart.DataColor, colors);

        // Use local gradient shading for the sectors, with 5 pixels wide
        // semi-transparent white (bbffffff) borders
        c.setSectorStyle(Chart.LocalGradientShading, 0xbbffffff, 5);

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

        // Use 10pt Arial Bold as the default label font. Set the label box
        // background color the same as the sector color. Use soft lighting effect
        // with light direction from right. Use 8 pixels rounded corners.
        TextBox t = c.setLabelStyle("Arial Bold", 10, 0x000000);
        t.setBackground(Chart.SameAsMainColor, Chart.Transparent, Chart.softLighting(
            Chart.Right, 0));
        t.setRoundedCorners(8);

        // Set the sector label format. The label is centered in a 110 pixels wide
        // bounding box. It consists of two lines. The first line is the sector name.
        // The second line shows the data value and percentage.
        c.setLabelFormat(
            "<*block,halign=center,width=110*>{label}\n<*font=Arial,size=8*>US$ " +
            "{value}M ({percent}%)<*/*>");

        // Explode all sectors 10 pixels from the center
        c.setExplode(-1, 10);

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='{label}: US${value}M ({percent}%)'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new explodedpie();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


Icon Pie Chart (1)

Icon Pie Chart (1)

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 Chart.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 Chart.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

[JSP Version] jspdemo/iconpie.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the pie chart
double[] data = {72, 18, 15, 12};

// The depths for the sectors
double[] depths = {30, 20, 10, 10};

// The labels for the pie chart
String[] labels = {"Sunny", "Cloudy", "Rainy", "Snowy"};

// The icons for the sectors
String[] icons = {"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
PieChart c = new PieChart(400, 310, Chart.metalColor(0xccccff, 0), 0x000000, 1);
c.setRoundedFrame();

//Set search path to current JSP directory for loading icon images
c.setSearchPath(getServletConfig().getServletContext(), request);

// 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, Chart.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}\n{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
String chart1URL = c.makeSession(request, "chart1");

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{label}: {value} days ({percent}%)'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Icon Pie Chart (1)
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/iconpie.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class iconpie implements DemoModule
{
    //Name of demo program
    public String toString() { return "Icon Pie Chart (1)"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the pie chart
        double[] data = {72, 18, 15, 12};

        // The depths for the sectors
        double[] depths = {30, 20, 10, 10};

        // The labels for the pie chart
        String[] labels = {"Sunny", "Cloudy", "Rainy", "Snowy"};

        // The icons for the sectors
        String[] icons = {"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
        PieChart c = new PieChart(400, 310, Chart.metalColor(0xccccff, 0), 0x000000,
            1);
        c.setRoundedFrame();

        // 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, Chart.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}\n" +
            "{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
        viewer.setChart(c);

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

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new iconpie();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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 Chart.silverColor to create the silver color, then use it in PieChart.PieChart 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 Chart.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

[JSP Version] jspdemo/iconpie2.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the pie chart
double[] data = {28, 45, 5, 1, 12};

// The labels for the pie chart
String[] labels = {"Excellent", "Good", "Bad", "Very Bad", "Neutral"};

// The icons for the sectors
String[] icons = {"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
PieChart c = new PieChart(560, 300, Chart.silverColor(), 0x000000, 1);
c.setRoundedFrame();

//Set search path to current JSP directory for loading icon images
c.setSearchPath(getServletConfig().getServletContext(), request);

// 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, Chart.glassEffect());

// Add a logo to the chart written in CDML as the bottom title aligned to the bottom
// right
c.addTitle2(Chart.BottomRight,
    "<*block,valign=absmiddle*><*img=molecule.png*> <*block*><*color=FF*>" +
    "<*font=Times New Roman Bold Italic,size=12*>Molecular Engineering\n" +
    "<*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(Chart.SideLayout);

// Set the label background color to transparent
c.setLabelStyle().setBackground(Chart.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
String chart1URL = c.makeSession(request, "chart1");

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{label}: {value} responses ({percent}%)'");
%>
<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 color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/iconpie2.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class iconpie2 implements DemoModule
{
    //Name of demo program
    public String toString() { return "Icon Pie Chart (2)"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the pie chart
        double[] data = {28, 45, 5, 1, 12};

        // The labels for the pie chart
        String[] labels = {"Excellent", "Good", "Bad", "Very Bad", "Neutral"};

        // The icons for the sectors
        String[] icons = {"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
        PieChart c = new PieChart(560, 300, Chart.silverColor(), 0x000000, 1);
        c.setRoundedFrame();

        // 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, Chart.glassEffect());

        // Add a logo to the chart written in CDML as the bottom title aligned to the
        // bottom right
        c.addTitle2(Chart.BottomRight,
            "<*block,valign=absmiddle*><*img=molecule.png*> <*block*><*color=FF*>" +
            "<*font=Times New Roman Bold Italic,size=12*>Molecular Engineering\n" +
            "<*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(Chart.SideLayout);

        // Set the label background color to transparent
        c.setLabelStyle().setBackground(Chart.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
        viewer.setChart(c);

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

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new iconpie2();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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 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

[JSP Version] jspdemo/multipie.jsp
<%@page import="ChartDirector.*" %>
<%@page import="javax.servlet.http.*" %>
<%!
// A simple structure to represent a chart image with an image map
private static class ImageWithHotSpot
{
    String imageURL;
    String imageMap;
}

// Function to create the demo charts
ImageWithHotSpot createChart(HttpServletRequest request, int index)
{
    // The data for the pie chart
    double[] data0 = {25, 18, 15};
    double[] data1 = {14, 32, 24};
    double[] data2 = {25, 23, 9};

    // The labels for the pie chart
    String[] labels = {"Software", "Hardware", "Services"};

    // Create a PieChart object of size 180 x 160 pixels
    PieChart c = new 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(Chart.CircleLayout, -10);

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

    // Output the chart
    ImageWithHotSpot ret = new ImageWithHotSpot();
    ret.imageURL = c.makeSession(request, "chart" + index);

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

    return ret;
}
%>
<%
ImageWithHotSpot chart0 = createChart(request, 0);
ImageWithHotSpot chart1 = createChart(request, 1);
ImageWithHotSpot chart2 = createChart(request, 2);
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Multi-Pie Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart0.imageURL)%>'
    usemap="#map0" border="0">
<map name="map0"><%=chart0.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1.imageURL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=chart1.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart2.imageURL)%>'
    usemap="#map2" border="0">
<map name="map2"><%=chart2.imageMap%></map>
</body>
</html>

[Java Version] javademo/multipie.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class multipie implements DemoModule
{
    //Name of demo program
    public String toString() { return "Multi-Pie Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 3; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the pie chart
        double[] data0 = {25, 18, 15};
        double[] data1 = {14, 32, 24};
        double[] data2 = {25, 23, 9};

        // The labels for the pie chart
        String[] labels = {"Software", "Hardware", "Services"};

        // Create a PieChart object of size 180 x 160 pixels
        PieChart c = new 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(Chart.CircleLayout, -10);

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

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='{label}: US${value}M ({percent}%)'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new multipie();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);
        frame.getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
        frame.setSize(800, 450);

        // Create the charts and put them in the content pane
        for (int i = 0; i < demo.getNoOfCharts(); ++i)
        {
            ChartViewer viewer = new ChartViewer();
            demo.createChart(viewer, i);
            frame.getContentPane().add(viewer);
        }

        // Display the window
        frame.setVisible(true);
    }
}


Donut Chart

Donut Chart

This example demonstrates a donut chart with ring shading effects. It also demonstrates brushed metal background, rounded frame, customized sector labels and using CDML and Parameter Substitution and Formatting to format legend text.

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

  • The brushed silver background is achieved by using Chart.brushedSilverColor to create the brushed silver color, then use it in PieChart.PieChart as the chart background color.

  • The rounded frame is configured using BaseChart.setRoundedFrame.

  • The sector labels are configured using PieChart.setLabelFormat to show the sector number. PieChart.setLabelStyle is used to set the label style. It returns a TextBox object representing the sector label prototype. The Box.setBackground method of the label prototype is then used to add black borders around the labels.

  • The legend text is configured by calling the TextBox.setText method of the LegendBox object. The legend text template is specified using CDML and Parameter Substitution and Formatting as follows:

    <*block,valign=top*>{={sector}+1}.<*advanceTo=22*><*block,width=120*>{label}<*/*><*block,width=40,halign=right*>{percent}<*/*>%

    The starting "<*block,valign=top*>" means the different parts in the legend entry should be aligned to the top. This is necessarily because the second part of the legend entry (described below) can have multiple lines.

    The first part of the legend entry is "{={sector}+1}.<*advanceTo=22*>", which means the show the sector number, then "tab" to the 22th pixel position. (In ChartDirector, the sector number starts from 0. So we add 1 to {sector} to make the displayed sector number to start from 1.)

    The second part "<*block,width=120*>{label}<*/*>" which means to show the sector label in a 120 pixels block. If the label is wider than 120 pixels, it will be wrapped into multiple lines within the block.

    The last part "<*block,width=40,halign=right*>{percent}<*/*>%" means to show the percentage in a 40 pixels block, with the contents right aligned.

Source Code Listing

[JSP Version] jspdemo/donut.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the pie chart
double[] data = {25, 18, 15, 12, 8, 30, 35};

// The labels for the pie chart
String[] labels = {"Labor", "Licenses", "Taxes", "Legal", "Insurance", "Facilities",
    "Production"};

// Create a PieChart object of size 600 x 320 pixels. Set background color to brushed
// silver, with a 2 pixel 3D border. Use rounded corners of 20 pixels radius.
PieChart c = new PieChart(600, 320, Chart.brushedSilverColor(), Chart.Transparent, 2)
    ;
c.setRoundedFrame(0xffffff, 20);

// Add a title using 18 pts Times New Roman Bold Italic font. #Set top/bottom margins
// to 8 pixels.
TextBox title = c.addTitle("Donut Chart Demonstration",
    "Times New Roman Bold Italic", 18);
title.setMargin2(0, 0, 8, 8);

// Add a 2 pixels wide separator line just under the title
c.addLine(10, title.getHeight(), c.getWidth() - 11, title.getHeight(),
    Chart.LineColor, 2);

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

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

// Use ring shading effect for the sectors
c.setSectorStyle(Chart.RingShading);

// Use the side label layout method, with the labels positioned 16 pixels from the
// donut bounding box
c.setLabelLayout(Chart.SideLayout, 16);

// Show only the sector number as the sector label
c.setLabelFormat("{={sector}+1}");

// Set the sector label style to Arial Bold 10pt, with a dark grey (444444) border
c.setLabelStyle("Arial Bold", 10).setBackground(Chart.Transparent, 0x444444);

// Add a legend box, with the center of the left side anchored at (330, 175), and
// using 10 pts Arial Bold Italic font
LegendBox b = c.addLegend(330, 175, true, "Arial Bold Italic", 10);
b.setAlignment(Chart.Left);

// Set the legend box border to dark grey (444444), and with rounded conerns
b.setBackground(Chart.Transparent, 0x444444);
b.setRoundedCorners();

// Set the legend box margin to 16 pixels, and the extra line spacing between the
// legend entries as 5 pixels
b.setMargin(16);
b.setKeySpacing(0, 5);

// Set the legend text to show the sector number, followed by a 120 pixels wide block
// showing the sector label, and a 40 pixels wide block showing the percentage
b.setText(
    "<*block,valign=top*>{={sector}+1}.<*advanceTo=22*><*block,width=120*>{label}" +
    "<*/*><*block,width=40,halign=right*>{percent}<*/*>%");

// Output the chart
String chart1URL = c.makeSession(request, "chart1", Chart.JPG);

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{label}: US${value}K ({percent}%)'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Donut Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/donut.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class donut implements DemoModule
{
    //Name of demo program
    public String toString() { return "Donut Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the pie chart
        double[] data = {25, 18, 15, 12, 8, 30, 35};

        // The labels for the pie chart
        String[] labels = {"Labor", "Licenses", "Taxes", "Legal", "Insurance",
            "Facilities", "Production"};

        // Create a PieChart object of size 600 x 320 pixels. Set background color to
        // brushed silver, with a 2 pixel 3D border. Use rounded corners of 20 pixels
        // radius.
        PieChart c = new PieChart(600, 320, Chart.brushedSilverColor(),
            Chart.Transparent, 2);
        c.setRoundedFrame(0xffffff, 20);

        // Add a title using 18 pts Times New Roman Bold Italic font. #Set top/bottom
        // margins to 8 pixels.
        TextBox title = c.addTitle("Donut Chart Demonstration",
            "Times New Roman Bold Italic", 18);
        title.setMargin2(0, 0, 8, 8);

        // Add a 2 pixels wide separator line just under the title
        c.addLine(10, title.getHeight(), c.getWidth() - 11, title.getHeight(),
            Chart.LineColor, 2);

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

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

        // Use ring shading effect for the sectors
        c.setSectorStyle(Chart.RingShading);

        // Use the side label layout method, with the labels positioned 16 pixels
        // from the donut bounding box
        c.setLabelLayout(Chart.SideLayout, 16);

        // Show only the sector number as the sector label
        c.setLabelFormat("{={sector}+1}");

        // Set the sector label style to Arial Bold 10pt, with a dark grey (444444)
        // border
        c.setLabelStyle("Arial Bold", 10).setBackground(Chart.Transparent, 0x444444);

        // Add a legend box, with the center of the left side anchored at (330, 175),
        // and using 10 pts Arial Bold Italic font
        LegendBox b = c.addLegend(330, 175, true, "Arial Bold Italic", 10);
        b.setAlignment(Chart.Left);

        // Set the legend box border to dark grey (444444), and with rounded conerns
        b.setBackground(Chart.Transparent, 0x444444);
        b.setRoundedCorners();

        // Set the legend box margin to 16 pixels, and the extra line spacing between
        // the legend entries as 5 pixels
        b.setMargin(16);
        b.setKeySpacing(0, 5);

        // Set the legend text to show the sector number, followed by a 120 pixels
        // wide block showing the sector label, and a 40 pixels wide block showing
        // the percentage
        b.setText(
            "<*block,valign=top*>{={sector}+1}.<*advanceTo=22*><*block,width=120*>" +
            "{label}<*/*><*block,width=40,halign=right*>{percent}<*/*>%");

        // Output the chart
        viewer.setChart(c);

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

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new donut();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


3D Donut Chart

3D Donut Chart

This example demonstrates a 3D donut chart with sector gradient shading. It also demonstrates gradient color background, rounded frame, custom sector colors, and using CDML and Parameter Substitution and Formatting to format sector labels

  • The gradient background is achieved by using BaseChart.linearGradientColor to define the gradient color, then use BaseChart.setBackground to set it as the chart background color.

  • The rounded frame is configured using BaseChart.setRoundedFrame.

  • The sector colors are set using BaseChart.setColors. The sector gradient shading and thick sector border is configured using PieChart.setSectorStyle.

  • The sector label style are configured using PieChart.setLabelStyle. It returns a TextBox object representing the sector label prototype. The gradient background color and rounded corners of the sector labels are configured using the Box.setBackground and Box.setRoundedCorners methods of the label prototype.

  • The sector label contents are configured using PieChart.setLabelFormat. The template is specified using CDML and Parameter Substitution and Formatting. It consists of two lines using different fonts. This first line shows the sector label, while the second line shows the sector value and percentage.

Source Code Listing

[JSP Version] jspdemo/threeddonut.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the pie chart
double[] data = {20, 10, 15, 12};

// The labels for the pie chart
String[] labels = {"Labor", "Licenses", "Facilities", "Production"};

// The colors to use for the sectors
int[] colors = {0x66aaee, 0xeebb22, 0xcccccc, 0xcc88ff};

// Create a PieChart object of size 600 x 320 pixels. Use a vertical gradient color
// from deep blue (000066) to blue (0000cc) as background. Use rounded corners of 20
// pixels radius.
PieChart c = new PieChart(600, 320);
c.setBackground(c.linearGradientColor(0, 0, 0, c.getHeight(), 0x000066, 0x0000cc));
c.setRoundedFrame(0xffffff, 20);

// Add a title using 18 pts Times New Roman Bold Italic font in white (ffffff) color.
// Set top/bottom margins to 8 pixels.
TextBox title = c.addTitle("Donut Chart Demonstration",
    "Times New Roman Bold Italic", 18, 0xffffff);
title.setMargin2(0, 0, 8, 8);

// Add a separator line in white color just under the title
c.addLine(10, title.getHeight(), c.getWidth() - 11, title.getHeight(), 0xffffff);

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

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

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

// Set the sector colors
c.setColors2(Chart.DataColor, colors);

// Use local gradient shading for the sectors
c.setSectorStyle(Chart.LocalGradientShading);

// Set sector border color to same as fill color. Set label join line color to white
// (ffffff)
c.setLineColor(Chart.SameAsMainColor, 0xffffff);

// Use the side label layout method, with the labels positioned 16 pixels from the
// donut bounding box
c.setLabelLayout(Chart.SideLayout, 16);

// 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 label box background color the same as the sector color. Use soft lighting
// effect with light direction from right. Use rounded corners.
TextBox t = c.setLabelStyle();
t.setBackground(Chart.SameAsMainColor, Chart.Transparent, Chart.softLighting(
    Chart.Right));
t.setRoundedCorners();

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{label}: US${value}K ({percent}%)'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    3D Donut Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/threeddonut.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class threeddonut implements DemoModule
{
    //Name of demo program
    public String toString() { return "3D Donut Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the pie chart
        double[] data = {20, 10, 15, 12};

        // The labels for the pie chart
        String[] labels = {"Labor", "Licenses", "Facilities", "Production"};

        // The colors to use for the sectors
        int[] colors = {0x66aaee, 0xeebb22, 0xcccccc, 0xcc88ff};

        // Create a PieChart object of size 600 x 320 pixels. Use a vertical gradient
        // color from deep blue (000066) to blue (0000cc) as background. Use rounded
        // corners of 20 pixels radius.
        PieChart c = new PieChart(600, 320);
        c.setBackground(c.linearGradientColor(0, 0, 0, c.getHeight(), 0x000066,
            0x0000cc));
        c.setRoundedFrame(0xffffff, 20);

        // Add a title using 18 pts Times New Roman Bold Italic font in white
        // (ffffff) color. Set top/bottom margins to 8 pixels.
        TextBox title = c.addTitle("Donut Chart Demonstration",
            "Times New Roman Bold Italic", 18, 0xffffff);
        title.setMargin2(0, 0, 8, 8);

        // Add a separator line in white color just under the title
        c.addLine(10, title.getHeight(), c.getWidth() - 11, title.getHeight(),
            0xffffff);

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

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

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

        // Set the sector colors
        c.setColors2(Chart.DataColor, colors);

        // Use local gradient shading for the sectors
        c.setSectorStyle(Chart.LocalGradientShading);

        // Set sector border color to same as fill color. Set label join line color
        // to white (ffffff)
        c.setLineColor(Chart.SameAsMainColor, 0xffffff);

        // Use the side label layout method, with the labels positioned 16 pixels
        // from the donut bounding box
        c.setLabelLayout(Chart.SideLayout, 16);

        // 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 label box background color the same as the sector color. Use soft
        // lighting effect with light direction from right. Use rounded corners.
        TextBox t = c.setLabelStyle();
        t.setBackground(Chart.SameAsMainColor, Chart.Transparent, Chart.softLighting(
            Chart.Right));
        t.setRoundedCorners();

        // Output the chart
        viewer.setChart(c);

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

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new threeddonut();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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.

  • Chart.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

[JSP Version] jspdemo/icondonut.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the pie chart
double[] data = {72, 18, 15, 12};

// The depths for the sectors
double[] depths = {30, 20, 10, 10};

// The labels for the pie chart
String[] labels = {"Sunny", "Cloudy", "Rainy", "Snowy"};

// The icons for the sectors
String[] icons = {"sun.png", "cloud.png", "rain.png", "snowy.png"};

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

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

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

//Set search path to current JSP directory for loading icon images
c.setSearchPath(getServletConfig().getServletContext(), request);

// 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(Chart.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}\n{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
String chart1URL = c.makeSession(request, "chart1");

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{label}: {value} days ({percent}%)'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Icon Donut Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/icondonut.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class icondonut implements DemoModule
{
    //Name of demo program
    public String toString() { return "Icon Donut Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the pie chart
        double[] data = {72, 18, 15, 12};

        // The depths for the sectors
        double[] depths = {30, 20, 10, 10};

        // The labels for the pie chart
        String[] labels = {"Sunny", "Cloudy", "Rainy", "Snowy"};

        // The icons for the sectors
        String[] icons = {"sun.png", "cloud.png", "rain.png", "snowy.png"};

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

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

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

        // 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(Chart.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}\n" +
            "{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
        viewer.setChart(c);

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

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new icondonut();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/texturedonut.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the pie chart
double[] data = {18, 45, 28};

// The labels for the pie chart
String[] labels = {"Marble", "Wood", "Granite"};

// The icons for the sectors
String[] texture = {"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
PieChart c = new PieChart(400, 330, Chart.metalColor(0x88ee88), 0x000000, 1);

//Set search path to current JSP directory for loading icon images
c.setSearchPath(getServletConfig().getServletContext(), request);

// 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(
    Chart.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(Chart.DataColor + 0, c.patternColor2(texture[0]));
c.setColor(Chart.DataColor + 1, c.patternColor2(texture[1]));
c.setColor(Chart.DataColor + 2, c.patternColor2(texture[2]));

// 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
String chart1URL = c.makeSession(request, "chart1");

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{label}: {value}kg ({percent}%)'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Texture Donut Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/texturedonut.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class texturedonut implements DemoModule
{
    //Name of demo program
    public String toString() { return "Texture Donut Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the pie chart
        double[] data = {18, 45, 28};

        // The labels for the pie chart
        String[] labels = {"Marble", "Wood", "Granite"};

        // The icons for the sectors
        String[] texture = {"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
        PieChart c = new PieChart(400, 330, Chart.metalColor(0x88ee88), 0x000000, 1);

        // 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(Chart.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(Chart.DataColor + 0, c.patternColor2(texture[0]));
        c.setColor(Chart.DataColor + 1, c.patternColor2(texture[1]));
        c.setColor(Chart.DataColor + 2, c.patternColor2(texture[2]));

        // 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
        viewer.setChart(c);

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

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new texturedonut();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/concentric.jsp
<%@page import="ChartDirector.*" %>
<%
// Data for outer ring
double[] data = {88, 124, 96};

// Data for inner ring
double[] data2 = {77, 87, 45};

// Labels for the sectors
String[] labels = {"Hardware", "Software", "Services"};

// Colors for the sectors
int[] colors = {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
PieChart c = new 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
TextBox t = c.addText(260, 300, " Year 2006 ", "Arial Bold Italic", 12, 0xffffff);
t.setBackground(0x008800, Chart.Transparent, Chart.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(Chart.Transparent,
    Chart.Transparent);

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

// Set the pie colors
c.setColors2(Chart.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
PieChart c2 = new PieChart(280, 320, Chart.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
TextBox t2 = c2.addText(110, 110, " Year 2005 ", "Arial Bold Italic", 12, 0xffffff,
    Chart.Center);
t2.setBackground(0x0000cc, Chart.Transparent, Chart.softLighting());
t2.setRoundedCorners(5);

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

// Set the pie colors
c2.setColors2(Chart.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, Chart.TopLeft, 0);

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

// include tool tip for the chart
String 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}%)'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Concentric Donut Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/concentric.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class concentric implements DemoModule
{
    //Name of demo program
    public String toString() { return "Concentric Donut Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // Data for outer ring
        double[] data = {88, 124, 96};

        // Data for inner ring
        double[] data2 = {77, 87, 45};

        // Labels for the sectors
        String[] labels = {"Hardware", "Software", "Services"};

        // Colors for the sectors
        int[] colors = {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
        PieChart c = new 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
        TextBox t = c.addText(260, 300, " Year 2006 ", "Arial Bold Italic", 12,
            0xffffff);
        t.setBackground(0x008800, Chart.Transparent, Chart.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(
            Chart.Transparent, Chart.Transparent);

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

        // Set the pie colors
        c.setColors2(Chart.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
        PieChart c2 = new PieChart(280, 320, Chart.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
        TextBox t2 = c2.addText(110, 110, " Year 2005 ", "Arial Bold Italic", 12,
            0xffffff, Chart.Center);
        t2.setBackground(0x0000cc, Chart.Transparent, Chart.softLighting());
        t2.setRoundedCorners(5);

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

        // Set the pie colors
        c2.setColors2(Chart.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, Chart.TopLeft, 0);

        // Output the chart
        viewer.setChart(c);

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

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new concentric();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


2D Pie Shading

2D Pie Shading

This example demonstrates various sector shading effects applicable to 2D pie charts.

Source Code Listing

[JSP Version] jspdemo/pieshading.jsp
<%@page import="ChartDirector.*" %>
<%@page import="javax.servlet.http.*" %>
<%!
// A simple structure to represent a chart image with an image map
private static class ImageWithHotSpot
{
    String imageURL;
    String imageMap;
}

// Function to create the demo charts
ImageWithHotSpot createChart(HttpServletRequest request, int index)
{
    // The data for the pie chart
    double[] data = {18, 30, 20, 15};

    // The labels for the pie chart
    String[] labels = {"Labor", "Licenses", "Facilities", "Production"};

    // The colors to use for the sectors
    int[] colors = {0x66aaee, 0xeebb22, 0xbbbbbb, 0x8844ff};

    // Create a PieChart object of size 200 x 220 pixels. Use a vertical gradient
    // color from blue (0000cc) to deep blue (000044) as background. Use rounded
    // corners of 16 pixels radius.
    PieChart c = new PieChart(200, 220);
    c.setBackground(c.linearGradientColor(0, 0, 0, c.getHeight(), 0x0000cc, 0x000044)
        );
    c.setRoundedFrame(0xffffff, 16);

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

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

    // Set the sector colors
    c.setColors2(Chart.DataColor, colors);

    // Demonstrates various shading modes
    if (index == 0) {
        c.addTitle("Default Shading", "bold", 12, 0xffffff);
    } else if (index == 1) {
        c.addTitle("Local Gradient", "bold", 12, 0xffffff);
        c.setSectorStyle(Chart.LocalGradientShading);
    } else if (index == 2) {
        c.addTitle("Global Gradient", "bold", 12, 0xffffff);
        c.setSectorStyle(Chart.GlobalGradientShading);
    } else if (index == 3) {
        c.addTitle("Concave Shading", "bold", 12, 0xffffff);
        c.setSectorStyle(Chart.ConcaveShading);
    } else if (index == 4) {
        c.addTitle("Rounded Edge", "bold", 12, 0xffffff);
        c.setSectorStyle(Chart.RoundedEdgeShading);
    } else if (index == 5) {
        c.addTitle("Radial Gradient", "bold", 12, 0xffffff);
        c.setSectorStyle(Chart.RadialShading);
    }

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

    // Output the chart
    ImageWithHotSpot ret = new ImageWithHotSpot();
    ret.imageURL = c.makeSession(request, "chart" + index);

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

    return ret;
}
%>
<%
ImageWithHotSpot chart0 = createChart(request, 0);
ImageWithHotSpot chart1 = createChart(request, 1);
ImageWithHotSpot chart2 = createChart(request, 2);
ImageWithHotSpot chart3 = createChart(request, 3);
ImageWithHotSpot chart4 = createChart(request, 4);
ImageWithHotSpot chart5 = createChart(request, 5);
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    2D Pie Shading
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart0.imageURL)%>'
    usemap="#map0" border="0">
<map name="map0"><%=chart0.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1.imageURL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=chart1.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart2.imageURL)%>'
    usemap="#map2" border="0">
<map name="map2"><%=chart2.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart3.imageURL)%>'
    usemap="#map3" border="0">
<map name="map3"><%=chart3.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart4.imageURL)%>'
    usemap="#map4" border="0">
<map name="map4"><%=chart4.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart5.imageURL)%>'
    usemap="#map5" border="0">
<map name="map5"><%=chart5.imageMap%></map>
</body>
</html>

[Java Version] javademo/pieshading.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class pieshading implements DemoModule
{
    //Name of demo program
    public String toString() { return "2D Pie Shading"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 6; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the pie chart
        double[] data = {18, 30, 20, 15};

        // The labels for the pie chart
        String[] labels = {"Labor", "Licenses", "Facilities", "Production"};

        // The colors to use for the sectors
        int[] colors = {0x66aaee, 0xeebb22, 0xbbbbbb, 0x8844ff};

        // Create a PieChart object of size 200 x 220 pixels. Use a vertical gradient
        // color from blue (0000cc) to deep blue (000044) as background. Use rounded
        // corners of 16 pixels radius.
        PieChart c = new PieChart(200, 220);
        c.setBackground(c.linearGradientColor(0, 0, 0, c.getHeight(), 0x0000cc,
            0x000044));
        c.setRoundedFrame(0xffffff, 16);

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

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

        // Set the sector colors
        c.setColors2(Chart.DataColor, colors);

        // Demonstrates various shading modes
        if (index == 0) {
            c.addTitle("Default Shading", "bold", 12, 0xffffff);
        } else if (index == 1) {
            c.addTitle("Local Gradient", "bold", 12, 0xffffff);
            c.setSectorStyle(Chart.LocalGradientShading);
        } else if (index == 2) {
            c.addTitle("Global Gradient", "bold", 12, 0xffffff);
            c.setSectorStyle(Chart.GlobalGradientShading);
        } else if (index == 3) {
            c.addTitle("Concave Shading", "bold", 12, 0xffffff);
            c.setSectorStyle(Chart.ConcaveShading);
        } else if (index == 4) {
            c.addTitle("Rounded Edge", "bold", 12, 0xffffff);
            c.setSectorStyle(Chart.RoundedEdgeShading);
        } else if (index == 5) {
            c.addTitle("Radial Gradient", "bold", 12, 0xffffff);
            c.setSectorStyle(Chart.RadialShading);
        }

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

        // Output the chart
        viewer.setChart(c);

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

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new pieshading();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);
        frame.getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
        frame.setSize(800, 450);

        // Create the charts and put them in the content pane
        for (int i = 0; i < demo.getNoOfCharts(); ++i)
        {
            ChartViewer viewer = new ChartViewer();
            demo.createChart(viewer, i);
            frame.getContentPane().add(viewer);
        }

        // Display the window
        frame.setVisible(true);
    }
}


3D Pie Shading

3D Pie Shading

This example demonstrates various sector shading effects applicable to 3D pie charts.

Source Code Listing

[JSP Version] jspdemo/threedpieshading.jsp
<%@page import="ChartDirector.*" %>
<%@page import="javax.servlet.http.*" %>
<%!
// A simple structure to represent a chart image with an image map
private static class ImageWithHotSpot
{
    String imageURL;
    String imageMap;
}

// Function to create the demo charts
ImageWithHotSpot createChart(HttpServletRequest request, int index)
{
    // The data for the pie chart
    double[] data = {18, 30, 20, 15};

    // The labels for the pie chart
    String[] labels = {"Labor", "Licenses", "Facilities", "Production"};

    // The colors to use for the sectors
    int[] colors = {0x66aaee, 0xeebb22, 0xbbbbbb, 0x8844ff};

    // Create a PieChart object of size 200 x 200 pixels. Use a vertical gradient
    // color from blue (0000cc) to deep blue (000044) as background. Use rounded
    // corners of 16 pixels radius.
    PieChart c = new PieChart(200, 200);
    c.setBackground(c.linearGradientColor(0, 0, 0, c.getHeight(), 0x0000cc, 0x000044)
        );
    c.setRoundedFrame(0xffffff, 16);

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

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

    // Set the sector colors
    c.setColors2(Chart.DataColor, colors);

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

    // Demonstrates various shading modes
    if (index == 0) {
        c.addTitle("Default Shading", "bold", 12, 0xffffff);
    } else if (index == 1) {
        c.addTitle("Flat Gradient", "bold", 12, 0xffffff);
        c.setSectorStyle(Chart.FlatShading);
    } else if (index == 2) {
        c.addTitle("Local Gradient", "bold", 12, 0xffffff);
        c.setSectorStyle(Chart.LocalGradientShading);
    } else if (index == 3) {
        c.addTitle("Global Gradient", "bold", 12, 0xffffff);
        c.setSectorStyle(Chart.GlobalGradientShading);
    } else if (index == 4) {
        c.addTitle("Concave Shading", "bold", 12, 0xffffff);
        c.setSectorStyle(Chart.ConcaveShading);
    } else if (index == 5) {
        c.addTitle("Rounded Edge", "bold", 12, 0xffffff);
        c.setSectorStyle(Chart.RoundedEdgeShading);
    } else if (index == 6) {
        c.addTitle("Radial Gradient", "bold", 12, 0xffffff);
        c.setSectorStyle(Chart.RadialShading);
    }

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

    // Output the chart
    ImageWithHotSpot ret = new ImageWithHotSpot();
    ret.imageURL = c.makeSession(request, "chart" + index);

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

    return ret;
}
%>
<%
ImageWithHotSpot chart0 = createChart(request, 0);
ImageWithHotSpot chart1 = createChart(request, 1);
ImageWithHotSpot chart2 = createChart(request, 2);
ImageWithHotSpot chart3 = createChart(request, 3);
ImageWithHotSpot chart4 = createChart(request, 4);
ImageWithHotSpot chart5 = createChart(request, 5);
ImageWithHotSpot chart6 = createChart(request, 6);
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    3D Pie Shading
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart0.imageURL)%>'
    usemap="#map0" border="0">
<map name="map0"><%=chart0.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1.imageURL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=chart1.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart2.imageURL)%>'
    usemap="#map2" border="0">
<map name="map2"><%=chart2.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart3.imageURL)%>'
    usemap="#map3" border="0">
<map name="map3"><%=chart3.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart4.imageURL)%>'
    usemap="#map4" border="0">
<map name="map4"><%=chart4.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart5.imageURL)%>'
    usemap="#map5" border="0">
<map name="map5"><%=chart5.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart6.imageURL)%>'
    usemap="#map6" border="0">
<map name="map6"><%=chart6.imageMap%></map>
</body>
</html>

[Java Version] javademo/threedpieshading.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class threedpieshading implements DemoModule
{
    //Name of demo program
    public String toString() { return "3D Pie Shading"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 7; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the pie chart
        double[] data = {18, 30, 20, 15};

        // The labels for the pie chart
        String[] labels = {"Labor", "Licenses", "Facilities", "Production"};

        // The colors to use for the sectors
        int[] colors = {0x66aaee, 0xeebb22, 0xbbbbbb, 0x8844ff};

        // Create a PieChart object of size 200 x 200 pixels. Use a vertical gradient
        // color from blue (0000cc) to deep blue (000044) as background. Use rounded
        // corners of 16 pixels radius.
        PieChart c = new PieChart(200, 200);
        c.setBackground(c.linearGradientColor(0, 0, 0, c.getHeight(), 0x0000cc,
            0x000044));
        c.setRoundedFrame(0xffffff, 16);

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

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

        // Set the sector colors
        c.setColors2(Chart.DataColor, colors);

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

        // Demonstrates various shading modes
        if (index == 0) {
            c.addTitle("Default Shading", "bold", 12, 0xffffff);
        } else if (index == 1) {
            c.addTitle("Flat Gradient", "bold", 12, 0xffffff);
            c.setSectorStyle(Chart.FlatShading);
        } else if (index == 2) {
            c.addTitle("Local Gradient", "bold", 12, 0xffffff);
            c.setSectorStyle(Chart.LocalGradientShading);
        } else if (index == 3) {
            c.addTitle("Global Gradient", "bold", 12, 0xffffff);
            c.setSectorStyle(Chart.GlobalGradientShading);
        } else if (index == 4) {
            c.addTitle("Concave Shading", "bold", 12, 0xffffff);
            c.setSectorStyle(Chart.ConcaveShading);
        } else if (index == 5) {
            c.addTitle("Rounded Edge", "bold", 12, 0xffffff);
            c.setSectorStyle(Chart.RoundedEdgeShading);
        } else if (index == 6) {
            c.addTitle("Radial Gradient", "bold", 12, 0xffffff);
            c.setSectorStyle(Chart.RadialShading);
        }

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

        // Output the chart
        viewer.setChart(c);

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

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new threedpieshading();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);
        frame.getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
        frame.setSize(800, 450);

        // Create the charts and put them in the content pane
        for (int i = 0; i < demo.getNoOfCharts(); ++i)
        {
            ChartViewer viewer = new ChartViewer();
            demo.createChart(viewer, i);
            frame.getContentPane().add(viewer);
        }

        // Display the window
        frame.setVisible(true);
    }
}


2D Donut Shading

2D Donut Shading

This example demonstrates various sector shading effects applicable to 2D donut charts.

Source Code Listing

[JSP Version] jspdemo/donutshading.jsp
<%@page import="ChartDirector.*" %>
<%@page import="javax.servlet.http.*" %>
<%!
// A simple structure to represent a chart image with an image map
private static class ImageWithHotSpot
{
    String imageURL;
    String imageMap;
}

// Function to create the demo charts
ImageWithHotSpot createChart(HttpServletRequest request, int index)
{
    // The data for the pie chart
    double[] data = {18, 30, 20, 15};

    // The labels for the pie chart
    String[] labels = {"Labor", "Licenses", "Facilities", "Production"};

    // The colors to use for the sectors
    int[] colors = {0x66aaee, 0xeebb22, 0xbbbbbb, 0x8844ff};

    // Create a PieChart object of size 200 x 220 pixels. Use a vertical gradient
    // color from blue (0000cc) to deep blue (000044) as background. Use rounded
    // corners of 16 pixels radius.
    PieChart c = new PieChart(200, 220);
    c.setBackground(c.linearGradientColor(0, 0, 0, c.getHeight(), 0x0000cc, 0x000044)
        );
    c.setRoundedFrame(0xffffff, 16);

    // Set donut center at (100, 120), and outer/inner radii as 80/40 pixels
    c.setDonutSize(100, 120, 80, 40);

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

    // Set the sector colors
    c.setColors2(Chart.DataColor, colors);

    // Demonstrates various shading modes
    if (index == 0) {
        c.addTitle("Default Shading", "bold", 12, 0xffffff);
    } else if (index == 1) {
        c.addTitle("Local Gradient", "bold", 12, 0xffffff);
        c.setSectorStyle(Chart.LocalGradientShading);
    } else if (index == 2) {
        c.addTitle("Global Gradient", "bold", 12, 0xffffff);
        c.setSectorStyle(Chart.GlobalGradientShading);
    } else if (index == 3) {
        c.addTitle("Concave Shading", "bold", 12, 0xffffff);
        c.setSectorStyle(Chart.ConcaveShading);
    } else if (index == 4) {
        c.addTitle("Rounded Edge", "bold", 12, 0xffffff);
        c.setSectorStyle(Chart.RoundedEdgeShading);
    } else if (index == 5) {
        c.addTitle("Radial Gradient", "bold", 12, 0xffffff);
        c.setSectorStyle(Chart.RadialShading);
    } else if (index == 6) {
        c.addTitle("Ring Shading", "bold", 12, 0xffffff);
        c.setSectorStyle(Chart.RingShading);
    }

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

    // Output the chart
    ImageWithHotSpot ret = new ImageWithHotSpot();
    ret.imageURL = c.makeSession(request, "chart" + index);

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

    return ret;
}
%>
<%
ImageWithHotSpot chart0 = createChart(request, 0);
ImageWithHotSpot chart1 = createChart(request, 1);
ImageWithHotSpot chart2 = createChart(request, 2);
ImageWithHotSpot chart3 = createChart(request, 3);
ImageWithHotSpot chart4 = createChart(request, 4);
ImageWithHotSpot chart5 = createChart(request, 5);
ImageWithHotSpot chart6 = createChart(request, 6);
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    2D Donut Shading
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart0.imageURL)%>'
    usemap="#map0" border="0">
<map name="map0"><%=chart0.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1.imageURL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=chart1.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart2.imageURL)%>'
    usemap="#map2" border="0">
<map name="map2"><%=chart2.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart3.imageURL)%>'
    usemap="#map3" border="0">
<map name="map3"><%=chart3.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart4.imageURL)%>'
    usemap="#map4" border="0">
<map name="map4"><%=chart4.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart5.imageURL)%>'
    usemap="#map5" border="0">
<map name="map5"><%=chart5.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart6.imageURL)%>'
    usemap="#map6" border="0">
<map name="map6"><%=chart6.imageMap%></map>
</body>
</html>

[Java Version] javademo/donutshading.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class donutshading implements DemoModule
{
    //Name of demo program
    public String toString() { return "2D Donut Shading"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 7; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the pie chart
        double[] data = {18, 30, 20, 15};

        // The labels for the pie chart
        String[] labels = {"Labor", "Licenses", "Facilities", "Production"};

        // The colors to use for the sectors
        int[] colors = {0x66aaee, 0xeebb22, 0xbbbbbb, 0x8844ff};

        // Create a PieChart object of size 200 x 220 pixels. Use a vertical gradient
        // color from blue (0000cc) to deep blue (000044) as background. Use rounded
        // corners of 16 pixels radius.
        PieChart c = new PieChart(200, 220);
        c.setBackground(c.linearGradientColor(0, 0, 0, c.getHeight(), 0x0000cc,
            0x000044));
        c.setRoundedFrame(0xffffff, 16);

        // Set donut center at (100, 120), and outer/inner radii as 80/40 pixels
        c.setDonutSize(100, 120, 80, 40);

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

        // Set the sector colors
        c.setColors2(Chart.DataColor, colors);

        // Demonstrates various shading modes
        if (index == 0) {
            c.addTitle("Default Shading", "bold", 12, 0xffffff);
        } else if (index == 1) {
            c.addTitle("Local Gradient", "bold", 12, 0xffffff);
            c.setSectorStyle(Chart.LocalGradientShading);
        } else if (index == 2) {
            c.addTitle("Global Gradient", "bold", 12, 0xffffff);
            c.setSectorStyle(Chart.GlobalGradientShading);
        } else if (index == 3) {
            c.addTitle("Concave Shading", "bold", 12, 0xffffff);
            c.setSectorStyle(Chart.ConcaveShading);
        } else if (index == 4) {
            c.addTitle("Rounded Edge", "bold", 12, 0xffffff);
            c.setSectorStyle(Chart.RoundedEdgeShading);
        } else if (index == 5) {
            c.addTitle("Radial Gradient", "bold", 12, 0xffffff);
            c.setSectorStyle(Chart.RadialShading);
        } else if (index == 6) {
            c.addTitle("Ring Shading", "bold", 12, 0xffffff);
            c.setSectorStyle(Chart.RingShading);
        }

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

        // Output the chart
        viewer.setChart(c);

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

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new donutshading();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);
        frame.getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
        frame.setSize(800, 450);

        // Create the charts and put them in the content pane
        for (int i = 0; i < demo.getNoOfCharts(); ++i)
        {
            ChartViewer viewer = new ChartViewer();
            demo.createChart(viewer, i);
            frame.getContentPane().add(viewer);
        }

        // Display the window
        frame.setVisible(true);
    }
}


3D Donut Shading

3D Donut Shading

This example demonstrates various sector shading effects applicable to 3D donut charts.

Source Code Listing

[JSP Version] jspdemo/threeddonutshading.jsp
<%@page import="ChartDirector.*" %>
<%@page import="javax.servlet.http.*" %>
<%!
// A simple structure to represent a chart image with an image map
private static class ImageWithHotSpot
{
    String imageURL;
    String imageMap;
}

// Function to create the demo charts
ImageWithHotSpot createChart(HttpServletRequest request, int index)
{
    // The data for the pie chart
    double[] data = {18, 30, 20, 15};

    // The labels for the pie chart
    String[] labels = {"Labor", "Licenses", "Facilities", "Production"};

    // The colors to use for the sectors
    int[] colors = {0x66aaee, 0xeebb22, 0xbbbbbb, 0x8844ff};

    // Create a PieChart object of size 200 x 200 pixels. Use a vertical gradient
    // color from blue (0000cc) to deep blue (000044) as background. Use rounded
    // corners of 16 pixels radius.
    PieChart c = new PieChart(200, 200);
    c.setBackground(c.linearGradientColor(0, 0, 0, c.getHeight(), 0x0000cc, 0x000044)
        );
    c.setRoundedFrame(0xffffff, 16);

    // Set donut center at (100, 100), and outer/inner radii as 80/40 pixels
    c.setDonutSize(100, 100, 80, 40);

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

    // Set the sector colors
    c.setColors2(Chart.DataColor, colors);

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

    // Demonstrates various shading modes
    if (index == 0) {
        c.addTitle("Default Shading", "bold", 12, 0xffffff);
    } else if (index == 1) {
        c.addTitle("Flat Gradient", "bold", 12, 0xffffff);
        c.setSectorStyle(Chart.FlatShading);
    } else if (index == 2) {
        c.addTitle("Local Gradient", "bold", 12, 0xffffff);
        c.setSectorStyle(Chart.LocalGradientShading);
    } else if (index == 3) {
        c.addTitle("Global Gradient", "bold", 12, 0xffffff);
        c.setSectorStyle(Chart.GlobalGradientShading);
    } else if (index == 4) {
        c.addTitle("Concave Shading", "bold", 12, 0xffffff);
        c.setSectorStyle(Chart.ConcaveShading);
    } else if (index == 5) {
        c.addTitle("Rounded Edge", "bold", 12, 0xffffff);
        c.setSectorStyle(Chart.RoundedEdgeShading);
    } else if (index == 6) {
        c.addTitle("Radial Gradient", "bold", 12, 0xffffff);
        c.setSectorStyle(Chart.RadialShading);
    } else if (index == 7) {
        c.addTitle("Ring Shading", "bold", 12, 0xffffff);
        c.setSectorStyle(Chart.RingShading);
    }

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

    // Output the chart
    ImageWithHotSpot ret = new ImageWithHotSpot();
    ret.imageURL = c.makeSession(request, "chart" + index);

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

    return ret;
}
%>
<%
ImageWithHotSpot chart0 = createChart(request, 0);
ImageWithHotSpot chart1 = createChart(request, 1);
ImageWithHotSpot chart2 = createChart(request, 2);
ImageWithHotSpot chart3 = createChart(request, 3);
ImageWithHotSpot chart4 = createChart(request, 4);
ImageWithHotSpot chart5 = createChart(request, 5);
ImageWithHotSpot chart6 = createChart(request, 6);
ImageWithHotSpot chart7 = createChart(request, 7);
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    3D Donut Shading
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart0.imageURL)%>'
    usemap="#map0" border="0">
<map name="map0"><%=chart0.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1.imageURL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=chart1.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart2.imageURL)%>'
    usemap="#map2" border="0">
<map name="map2"><%=chart2.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart3.imageURL)%>'
    usemap="#map3" border="0">
<map name="map3"><%=chart3.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart4.imageURL)%>'
    usemap="#map4" border="0">
<map name="map4"><%=chart4.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart5.imageURL)%>'
    usemap="#map5" border="0">
<map name="map5"><%=chart5.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart6.imageURL)%>'
    usemap="#map6" border="0">
<map name="map6"><%=chart6.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart7.imageURL)%>'
    usemap="#map7" border="0">
<map name="map7"><%=chart7.imageMap%></map>
</body>
</html>

[Java Version] javademo/threeddonutshading.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class threeddonutshading implements DemoModule
{
    //Name of demo program
    public String toString() { return "3D Donut Shading"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 8; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the pie chart
        double[] data = {18, 30, 20, 15};

        // The labels for the pie chart
        String[] labels = {"Labor", "Licenses", "Facilities", "Production"};

        // The colors to use for the sectors
        int[] colors = {0x66aaee, 0xeebb22, 0xbbbbbb, 0x8844ff};

        // Create a PieChart object of size 200 x 200 pixels. Use a vertical gradient
        // color from blue (0000cc) to deep blue (000044) as background. Use rounded
        // corners of 16 pixels radius.
        PieChart c = new PieChart(200, 200);
        c.setBackground(c.linearGradientColor(0, 0, 0, c.getHeight(), 0x0000cc,
            0x000044));
        c.setRoundedFrame(0xffffff, 16);

        // Set donut center at (100, 100), and outer/inner radii as 80/40 pixels
        c.setDonutSize(100, 100, 80, 40);

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

        // Set the sector colors
        c.setColors2(Chart.DataColor, colors);

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

        // Demonstrates various shading modes
        if (index == 0) {
            c.addTitle("Default Shading", "bold", 12, 0xffffff);
        } else if (index == 1) {
            c.addTitle("Flat Gradient", "bold", 12, 0xffffff);
            c.setSectorStyle(Chart.FlatShading);
        } else if (index == 2) {
            c.addTitle("Local Gradient", "bold", 12, 0xffffff);
            c.setSectorStyle(Chart.LocalGradientShading);
        } else if (index == 3) {
            c.addTitle("Global Gradient", "bold", 12, 0xffffff);
            c.setSectorStyle(Chart.GlobalGradientShading);
        } else if (index == 4) {
            c.addTitle("Concave Shading", "bold", 12, 0xffffff);
            c.setSectorStyle(Chart.ConcaveShading);
        } else if (index == 5) {
            c.addTitle("Rounded Edge", "bold", 12, 0xffffff);
            c.setSectorStyle(Chart.RoundedEdgeShading);
        } else if (index == 6) {
            c.addTitle("Radial Gradient", "bold", 12, 0xffffff);
            c.setSectorStyle(Chart.RadialShading);
        } else if (index == 7) {
            c.addTitle("Ring Shading", "bold", 12, 0xffffff);
            c.setSectorStyle(Chart.RingShading);
        }

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

        // Output the chart
        viewer.setChart(c);

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

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new threeddonutshading();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);
        frame.getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
        frame.setSize(800, 450);

        // Create the charts and put them in the content pane
        for (int i = 0; i < demo.getNoOfCharts(); ++i)
        {
            ChartViewer viewer = new ChartViewer();
            demo.createChart(viewer, i);
            frame.getContentPane().add(viewer);
        }

        // Display the window
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/fontpie.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the pie chart
double[] data = {25, 18, 15, 12, 8, 30, 35};

// The labels for the pie chart
String[] labels = {"Labor", "Licenses", "Taxes", "Legal", "Insurance", "Facilities",
    "Production"};

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

//Set search path to current JSP directory for loading icon images
c.setSearchPath(getServletConfig().getServletContext(), request);

// 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)
LegendBox b = c.addLegend(465, 70, true, "Arial Bold Italic", 11);
b.setBackground(c.patternColor("marble2.png"), Chart.Transparent, 1);
b.setAlignment(Chart.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(Chart.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,
    Chart.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
String chart1URL = c.makeSession(request, "chart1", Chart.JPG);

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{label}: US${value}K ({percent}%)'");
%>
<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 color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/fontpie.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class fontpie implements DemoModule
{
    //Name of demo program
    public String toString() { return "Text Style and Colors"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the pie chart
        double[] data = {25, 18, 15, 12, 8, 30, 35};

        // The labels for the pie chart
        String[] labels = {"Labor", "Licenses", "Taxes", "Legal", "Insurance",
            "Facilities", "Production"};

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

        // 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)
        LegendBox b = c.addLegend(465, 70, true, "Arial Bold Italic", 11);
        b.setBackground(c.patternColor("marble2.png"), Chart.Transparent, 1);
        b.setAlignment(Chart.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(
            Chart.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, Chart.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
        viewer.setChart(c);

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

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new fontpie();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/threedanglepie.jsp
<%@page import="ChartDirector.*" %>
<%@page import="javax.servlet.http.*" %>
<%!
// A simple structure to represent a chart image with an image map
private static class ImageWithHotSpot
{
    String imageURL;
    String imageMap;
}

// Function to create the demo charts
ImageWithHotSpot createChart(HttpServletRequest request, int index)
{
    // the tilt angle of the pie
    int angle = index * 15;

    // The data for the pie chart
    double[] data = {25, 18, 15, 12, 8, 30, 35};

    // The labels for the pie chart
    String[] labels = {"Labor", "Licenses", "Taxes", "Legal", "Insurance",
        "Facilities", "Production"};

    // Create a PieChart object of size 100 x 110 pixels
    PieChart c = new 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, Chart.Transparent);

    // Output the chart
    ImageWithHotSpot ret = new ImageWithHotSpot();
    ret.imageURL = c.makeSession(request, "chart" + index);

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

    return ret;
}
%>
<%
ImageWithHotSpot chart0 = createChart(request, 0);
ImageWithHotSpot chart1 = createChart(request, 1);
ImageWithHotSpot chart2 = createChart(request, 2);
ImageWithHotSpot chart3 = createChart(request, 3);
ImageWithHotSpot chart4 = createChart(request, 4);
ImageWithHotSpot chart5 = createChart(request, 5);
ImageWithHotSpot chart6 = createChart(request, 6);
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    3D Angle
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart0.imageURL)%>'
    usemap="#map0" border="0">
<map name="map0"><%=chart0.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1.imageURL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=chart1.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart2.imageURL)%>'
    usemap="#map2" border="0">
<map name="map2"><%=chart2.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart3.imageURL)%>'
    usemap="#map3" border="0">
<map name="map3"><%=chart3.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart4.imageURL)%>'
    usemap="#map4" border="0">
<map name="map4"><%=chart4.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart5.imageURL)%>'
    usemap="#map5" border="0">
<map name="map5"><%=chart5.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart6.imageURL)%>'
    usemap="#map6" border="0">
<map name="map6"><%=chart6.imageMap%></map>
</body>
</html>

[Java Version] javademo/threedanglepie.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class threedanglepie implements DemoModule
{
    //Name of demo program
    public String toString() { return "3D Angle"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 7; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // the tilt angle of the pie
        int angle = index * 15;

        // The data for the pie chart
        double[] data = {25, 18, 15, 12, 8, 30, 35};

        // The labels for the pie chart
        String[] labels = {"Labor", "Licenses", "Taxes", "Legal", "Insurance",
            "Facilities", "Production"};

        // Create a PieChart object of size 100 x 110 pixels
        PieChart c = new 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, Chart.Transparent);

        // Output the chart
        viewer.setChart(c);

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

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new threedanglepie();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);
        frame.getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
        frame.setSize(800, 450);

        // Create the charts and put them in the content pane
        for (int i = 0; i < demo.getNoOfCharts(); ++i)
        {
            ChartViewer viewer = new ChartViewer();
            demo.createChart(viewer, i);
            frame.getContentPane().add(viewer);
        }

        // Display the window
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/threeddepthpie.jsp
<%@page import="ChartDirector.*" %>
<%@page import="javax.servlet.http.*" %>
<%!
// A simple structure to represent a chart image with an image map
private static class ImageWithHotSpot
{
    String imageURL;
    String imageMap;
}

// Function to create the demo charts
ImageWithHotSpot createChart(HttpServletRequest request, int index)
{
    // the tilt angle of the pie
    int depth = index * 5 + 5;

    // The data for the pie chart
    double[] data = {25, 18, 15, 12, 8, 30, 35};

    // The labels for the pie chart
    String[] labels = {"Labor", "Licenses", "Taxes", "Legal", "Insurance",
        "Facilities", "Production"};

    // Create a PieChart object of size 100 x 110 pixels
    PieChart c = new 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, Chart.Transparent);

    // Output the chart
    ImageWithHotSpot ret = new ImageWithHotSpot();
    ret.imageURL = c.makeSession(request, "chart" + index);

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

    return ret;
}
%>
<%
ImageWithHotSpot chart0 = createChart(request, 0);
ImageWithHotSpot chart1 = createChart(request, 1);
ImageWithHotSpot chart2 = createChart(request, 2);
ImageWithHotSpot chart3 = createChart(request, 3);
ImageWithHotSpot chart4 = createChart(request, 4);
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    3D Depth
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart0.imageURL)%>'
    usemap="#map0" border="0">
<map name="map0"><%=chart0.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1.imageURL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=chart1.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart2.imageURL)%>'
    usemap="#map2" border="0">
<map name="map2"><%=chart2.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart3.imageURL)%>'
    usemap="#map3" border="0">
<map name="map3"><%=chart3.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart4.imageURL)%>'
    usemap="#map4" border="0">
<map name="map4"><%=chart4.imageMap%></map>
</body>
</html>

[Java Version] javademo/threeddepthpie.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class threeddepthpie implements DemoModule
{
    //Name of demo program
    public String toString() { return "3D Depth"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 5; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // the tilt angle of the pie
        int depth = index * 5 + 5;

        // The data for the pie chart
        double[] data = {25, 18, 15, 12, 8, 30, 35};

        // The labels for the pie chart
        String[] labels = {"Labor", "Licenses", "Taxes", "Legal", "Insurance",
            "Facilities", "Production"};

        // Create a PieChart object of size 100 x 110 pixels
        PieChart c = new 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, Chart.Transparent);

        // Output the chart
        viewer.setChart(c);

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

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new threeddepthpie();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);
        frame.getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
        frame.setSize(800, 450);

        // Create the charts and put them in the content pane
        for (int i = 0; i < demo.getNoOfCharts(); ++i)
        {
            ChartViewer viewer = new ChartViewer();
            demo.createChart(viewer, i);
            frame.getContentPane().add(viewer);
        }

        // Display the window
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/shadowpie.jsp
<%@page import="ChartDirector.*" %>
<%@page import="javax.servlet.http.*" %>
<%!
// A simple structure to represent a chart image with an image map
private static class ImageWithHotSpot
{
    String imageURL;
    String imageMap;
}

// Function to create the demo charts
ImageWithHotSpot createChart(HttpServletRequest request, int index)
{
    // the tilt angle of the pie
    int angle = index * 90 + 45;

    // The data for the pie chart
    double[] data = {25, 18, 15, 12, 8, 30, 35};

    // The labels for the pie chart
    String[] labels = {"Labor", "Licenses", "Taxes", "Legal", "Insurance",
        "Facilities", "Production"};

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

    // Set the center of the pie at (50, 55) and the radius to 36 pixels
    c.setPieSize(55, 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, Chart.Transparent);

    // Output the chart
    ImageWithHotSpot ret = new ImageWithHotSpot();
    ret.imageURL = c.makeSession(request, "chart" + index);

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

    return ret;
}
%>
<%
ImageWithHotSpot chart0 = createChart(request, 0);
ImageWithHotSpot chart1 = createChart(request, 1);
ImageWithHotSpot chart2 = createChart(request, 2);
ImageWithHotSpot chart3 = createChart(request, 3);
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    3D Shadow Mode
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart0.imageURL)%>'
    usemap="#map0" border="0">
<map name="map0"><%=chart0.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1.imageURL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=chart1.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart2.imageURL)%>'
    usemap="#map2" border="0">
<map name="map2"><%=chart2.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart3.imageURL)%>'
    usemap="#map3" border="0">
<map name="map3"><%=chart3.imageMap%></map>
</body>
</html>

[Java Version] javademo/shadowpie.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class shadowpie implements DemoModule
{
    //Name of demo program
    public String toString() { return "3D Shadow Mode"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 4; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // the tilt angle of the pie
        int angle = index * 90 + 45;

        // The data for the pie chart
        double[] data = {25, 18, 15, 12, 8, 30, 35};

        // The labels for the pie chart
        String[] labels = {"Labor", "Licenses", "Taxes", "Legal", "Insurance",
            "Facilities", "Production"};

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

        // Set the center of the pie at (50, 55) and the radius to 36 pixels
        c.setPieSize(55, 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, Chart.Transparent);

        // Output the chart
        viewer.setChart(c);

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

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new shadowpie();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);
        frame.getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
        frame.setSize(800, 450);

        // Create the charts and put them in the content pane
        for (int i = 0; i < demo.getNoOfCharts(); ++i)
        {
            ChartViewer viewer = new ChartViewer();
            demo.createChart(viewer, i);
            frame.getContentPane().add(viewer);
        }

        // Display the window
        frame.setVisible(true);
    }
}


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 PieChart.setStartAngle is to facilitate layout of pie charts containing many small sectors. Please refer to Side Label Layout for an example.

Source Code Listing

[JSP Version] jspdemo/anglepie.jsp
<%@page import="ChartDirector.*" %>
<%@page import="javax.servlet.http.*" %>
<%!
// A simple structure to represent a chart image with an image map
private static class ImageWithHotSpot
{
    String imageURL;
    String imageMap;
}

// Function to create the demo charts
ImageWithHotSpot createChart(HttpServletRequest request, int index)
{
    // Determine the starting angle and direction based on input parameter
    int angle = 0;
    boolean clockwise = true;
    if (index != 0) {
        angle = 90;
        clockwise = false;
    }

    // The data for the pie chart
    double[] data = {25, 18, 15, 12, 8, 30, 35};

    // The labels for the pie chart
    String[] labels = {"Labor", "Licenses", "Taxes", "Legal", "Insurance",
        "Facilities", "Production"};

    // Create a PieChart object of size 280 x 240 pixels
    PieChart c = new 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\nDirection = Clockwise");
    } else {
        c.addTitle("Start Angle = " + angle + " degrees\nDirection = 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
    ImageWithHotSpot ret = new ImageWithHotSpot();
    ret.imageURL = c.makeSession(request, "chart" + index);

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

    return ret;
}
%>
<%
ImageWithHotSpot chart0 = createChart(request, 0);
ImageWithHotSpot chart1 = createChart(request, 1);
%>
<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 color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart0.imageURL)%>'
    usemap="#map0" border="0">
<map name="map0"><%=chart0.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1.imageURL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=chart1.imageMap%></map>
</body>
</html>

[Java Version] javademo/anglepie.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class anglepie implements DemoModule
{
    //Name of demo program
    public String toString() { return "Start Angle and Direction"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 2; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // Determine the starting angle and direction based on input parameter
        int angle = 0;
        boolean clockwise = true;
        if (index != 0) {
            angle = 90;
            clockwise = false;
        }

        // The data for the pie chart
        double[] data = {25, 18, 15, 12, 8, 30, 35};

        // The labels for the pie chart
        String[] labels = {"Labor", "Licenses", "Taxes", "Legal", "Insurance",
            "Facilities", "Production"};

        // Create a PieChart object of size 280 x 240 pixels
        PieChart c = new 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\nDirection = Clockwise");
        } else {
            c.addTitle("Start Angle = " + angle +
                " degrees\nDirection = 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
        viewer.setChart(c);

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

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new anglepie();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);
        frame.getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
        frame.setSize(800, 450);

        // Create the charts and put them in the content pane
        for (int i = 0; i < demo.getNoOfCharts(); ++i)
        {
            ChartViewer viewer = new ChartViewer();
            demo.createChart(viewer, i);
            frame.getContentPane().add(viewer);
        }

        // Display the window
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/donutwidth.jsp
<%@page import="ChartDirector.*" %>
<%@page import="javax.servlet.http.*" %>
<%!
// A simple structure to represent a chart image with an image map
private static class ImageWithHotSpot
{
    String imageURL;
    String imageMap;
}

// Function to create the demo charts
ImageWithHotSpot createChart(HttpServletRequest request, int index)
{
    // Determine the donut inner radius (as percentage of outer radius) based on
    // input parameter
    int donutRadius = index * 25;

    // The data for the pie chart
    double[] data = {10, 10, 10, 10, 10};

    // The labels for the pie chart
    String[] labels = {"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
    PieChart c = new 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, Chart.Transparent);

    // Output the chart
    ImageWithHotSpot ret = new ImageWithHotSpot();
    ret.imageURL = c.makeSession(request, "chart" + index);

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

    return ret;
}
%>
<%
ImageWithHotSpot chart0 = createChart(request, 0);
ImageWithHotSpot chart1 = createChart(request, 1);
ImageWithHotSpot chart2 = createChart(request, 2);
ImageWithHotSpot chart3 = createChart(request, 3);
ImageWithHotSpot chart4 = createChart(request, 4);
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Donut Width
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart0.imageURL)%>'
    usemap="#map0" border="0">
<map name="map0"><%=chart0.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1.imageURL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=chart1.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart2.imageURL)%>'
    usemap="#map2" border="0">
<map name="map2"><%=chart2.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart3.imageURL)%>'
    usemap="#map3" border="0">
<map name="map3"><%=chart3.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart4.imageURL)%>'
    usemap="#map4" border="0">
<map name="map4"><%=chart4.imageMap%></map>
</body>
</html>

[Java Version] javademo/donutwidth.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class donutwidth implements DemoModule
{
    //Name of demo program
    public String toString() { return "Donut Width"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 5; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // Determine the donut inner radius (as percentage of outer radius) based on
        // input parameter
        int donutRadius = index * 25;

        // The data for the pie chart
        double[] data = {10, 10, 10, 10, 10};

        // The labels for the pie chart
        String[] labels = {"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
        PieChart c = new 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, Chart.Transparent);

        // Output the chart
        viewer.setChart(c);

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

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new donutwidth();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);
        frame.getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
        frame.setSize(800, 450);

        // Create the charts and put them in the content pane
        for (int i = 0; i < demo.getNoOfCharts(); ++i)
        {
            ChartViewer viewer = new ChartViewer();
            demo.createChart(viewer, i);
            frame.getContentPane().add(viewer);
        }

        // Display the window
        frame.setVisible(true);
    }
}


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 Charts refer to charts that have x and y axes. These include bar charts, line charts, spline line charts, trend line charts, step line charts, scatter charts, bubble charts, vector charts, area charts, floating box charts, box-whisker charts, waterfall charts, gantt charts, contour charts, heat maps, finance 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 combination charts.

For clarity and ease of understanding, this documentation is separated into sections to explain the various chart types. Please note that each chart type is just a layer in the XY Chart, and you may freely combine them together to create 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, polynomial, exponential and logarithmic regression trending lines with confidence bands, and arbitrary curve fitting using LOWESS.

Scatter/Bubble/Vector Charts
Demonstrates scatter charts with built-in and custom symbols, bubble charts with bubbles of different shapes and with horizontal and vertical sizes independently controlled, and vector charts.

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.

Floating Box/Waterfall Charts
Demonstrates vertical and horizontal box-whisker charts, and its application in floating box and waterfall charts.

Gantt Charts
Demonstrates gantt charts.

Coutour Charts/Heat Maps
Demonstrates contour charts and heat maps with stepwise and smooth coloring, and with bi-linear and spline surface interpolation.

Finance Charts
Demonstrates creating finance charts with OHLC bars, candlesticks, volume bars, moving averages, Bollinger bands, Donchian channels, RSI, MACD, Stochastic, and numerous other 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 effect 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 axis labels on both sides of the plot area.
Gradient Bar Shading | Demonstrates using bar gradient shading for a horizontal bar chart. Also demonstrates using gradient color background, partially rounded frame, and automatic resizing of the plot area to fit the chart.
Cylinder Bar Shading | Demonstrates using cylinder shading effect for bars. Also demonstrates brushed metal background, rounded frame, and 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 with a legend box. Also demonstrates gradient background color, rounded frame, soft drop shadow, and using CDML to include custom icons in the legend box.
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.
Gradient Multi-Bar Chart | Demonstrates a multi-bar chart with bar gradient shading 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.
Bars with Marks | Demonstrates combine a bar layer with a box-whisker layer to create bars with marks. Also demonstrates gradient background color, rounded frame, soft drop shadow, and automatic resizing of the plot area to fit the chart.
Pareto Chart | Demonstrates the pareto chart style.
Variable Width Bar Chart | Demonstrates a bar chart with variable bar widths.
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 (JSP version) or BaseChart.makeImage (Java version).

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

Source Code Listing

[JSP Version] jspdemo/simplebar.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the bar chart
double[] data = {85, 156, 179.5, 211, 123};

// The labels for the bar chart
String[] labels = {"Mon", "Tue", "Wed", "Thu", "Fri"};

// Create a XYChart object of size 250 x 250 pixels
XYChart c = new 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
String chart1URL = c.makeSession(request, "chart1");

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "", "title='{xLabel}: US${value}K'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Simple Bar Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/simplebar.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class simplebar implements DemoModule
{
    //Name of demo program
    public String toString() { return "Simple Bar Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the bar chart
        double[] data = {85, 156, 179.5, 211, 123};

        // The labels for the bar chart
        String[] labels = {"Mon", "Tue", "Wed", "Thu", "Fri"};

        // Create a XYChart object of size 250 x 250 pixels
        XYChart c = new 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
        viewer.setChart(c);

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

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new simplebar();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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 Chart.goldColor to create a golden color. Set it as the background color with 3D border effects using XYChart.XYChart.

  • Use Chart.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

[JSP Version] jspdemo/colorbar.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the bar chart
double[] data = {85, 156, 179.5, 211, 123};

// The labels for the bar chart
String[] labels = {"Mon", "Tue", "Wed", "Thu", "Fri"};

// The colors for the bar chart
int[] colors = {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.
XYChart c = new XYChart(300, 220, Chart.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(Chart.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
String chart1URL = c.makeSession(request, "chart1");

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "", "title='{xLabel}: {value} GBytes'");
%>
<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 color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/colorbar.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class colorbar implements DemoModule
{
    //Name of demo program
    public String toString() { return "Multi-Color Bar Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the bar chart
        double[] data = {85, 156, 179.5, 211, 123};

        // The labels for the bar chart
        String[] labels = {"Mon", "Tue", "Wed", "Thu", "Fri"};

        // The colors for the bar chart
        int[] colors = {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.
        XYChart c = new XYChart(300, 220, Chart.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(
            Chart.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
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='{xLabel}: {value} GBytes'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new colorbar();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


Soft Bar Shading

Soft Bar Shading

This example demonstrates using soft lighting effect 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 Chart.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

[JSP Version] jspdemo/softlightbar.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the bar chart
double[] data = {450, 560, 630, 800, 1100, 1350, 1600, 1950, 2300, 2700};

// The labels for the bar chart
String[] labels = {"1996", "1997", "1998", "1999", "2000", "2001", "2002", "2003",
    "2004", "2005"};

// Create a XYChart object of size 600 x 360 pixels
XYChart c = new 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(Chart.Transparent, Chart.softLighting(Chart.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
String chart1URL = c.makeSession(request, "chart1");

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "", "title='Year {xLabel}: US$ {value}M'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Soft Bar Shading
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/softlightbar.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class softlightbar implements DemoModule
{
    //Name of demo program
    public String toString() { return "Soft Bar Shading"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the bar chart
        double[] data = {450, 560, 630, 800, 1100, 1350, 1600, 1950, 2300, 2700};

        // The labels for the bar chart
        String[] labels = {"1996", "1997", "1998", "1999", "2000", "2001", "2002",
            "2003", "2004", "2005"};

        // Create a XYChart object of size 600 x 360 pixels
        XYChart c = new 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(Chart.Transparent, Chart.softLighting(
            Chart.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
        viewer.setChart(c);

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

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new softlightbar();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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 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 Chart.glassEffect, then applied to the bars using Layer.setBorderColor.

  • XYChart.syncYAxis is used to show two synchronized y-axes on both sides of the plot area.

  • Axis.setColors is used to set the y-axes to Transparent, so only the axis labels are visible.

  • The axis label font is set to Arial Bold using Axis.setLabelStyle.

Source Code Listing

[JSP Version] jspdemo/glasslightbar.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the bar chart
double[] data = {450, 560, 630, 800, 1100, 1350, 1600, 1950, 2300, 2700};

// The labels for the bar chart
String[] labels = {"1996", "1997", "1998", "1999", "2000", "2001", "2002", "2003",
    "2004", "2005"};

// Create a XYChart object of size 600 x 360 pixels
XYChart c = new 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(Chart.Transparent, Chart.glassEffect(
    Chart.NormalGlare, Chart.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(Chart.Transparent);
c.yAxis().setColors(Chart.Transparent);
c.yAxis2().setColors(Chart.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
String chart1URL = c.makeSession(request, "chart1");

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "", "title='Year {xLabel}: US$ {value}M'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Glass Bar Shading
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/glasslightbar.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class glasslightbar implements DemoModule
{
    //Name of demo program
    public String toString() { return "Glass Bar Shading"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the bar chart
        double[] data = {450, 560, 630, 800, 1100, 1350, 1600, 1950, 2300, 2700};

        // The labels for the bar chart
        String[] labels = {"1996", "1997", "1998", "1999", "2000", "2001", "2002",
            "2003", "2004", "2005"};

        // Create a XYChart object of size 600 x 360 pixels
        XYChart c = new 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(Chart.Transparent, Chart.glassEffect(
            Chart.NormalGlare, Chart.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(Chart.Transparent);
        c.yAxis().setColors(Chart.Transparent);
        c.yAxis2().setColors(Chart.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
        viewer.setChart(c);

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

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new glasslightbar();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


Gradient Bar Shading

Gradient Bar Shading

This example demonstrates using bar gradient shading for a horizontal bar chart. It also demonstrates using gradient color background, partially rounded frame, and automatic resizing of the plot area to fit the chart.

  • The gradient background is achieved by using BaseChart.linearGradientColor to define the gradient color, then use BaseChart.setBackground to set it as the chart background color.

  • The partially rounded frame is configured using BaseChart.setRoundedFrame. Note that only 2 of the 4 corners are rounded.

  • The x-axis and y-axis are swapped using XYChart.swapXY, so the bars become horizontal.

  • The bar gradient effect is defined using Chart.barLighting, then applied to the bars using Layer.setBorderColor.

  • After the entire chart is configured, the XYChart.packPlotArea method is used to adjust the plot area size, so as to fit the plot area and the axes in a given bounding box.

Source Code Listing

[JSP Version] jspdemo/gradientbar.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the bar chart
double[] data = {1350, 1600, 1950, 2300, 2700};

// The labels for the bar chart
String[] labels = {"2001", "2002", "2003", "2004", "2005"};

// The colors for the bars
int[] colors = {0xcc0000, 0x66aaee, 0xeebb22, 0xcccccc, 0xcc88ff};

// Create a PieChart object of size 600 x 380 pixels.
XYChart c = new XYChart(600, 380);

// Use the white on black palette, which means the default text and line colors are
// white
c.setColors(Chart.whiteOnBlackPalette);

// Use a vertical gradient color from blue (0000cc) to deep blue (000044) as
// background. Use rounded corners of 30 pixels radius for the top-left and
// bottom-right corners.
c.setBackground(c.linearGradientColor(0, 0, 0, c.getHeight(), 0x0000cc, 0x000044));
c.setRoundedFrame(0xffffff, 30, 0, 30, 0);

// Add a title using 18 pts Times New Roman Bold Italic font. Add 6 pixels top and
// bottom margins to the title.
TextBox title = c.addTitle("Annual Revenue for Star Tech",
    "Times New Roman Bold Italic", 18);
title.setMargin2(0, 0, 6, 6);

// Add a separator line in white color just under the title
c.addLine(20, title.getHeight(), c.getWidth() - 21, title.getHeight(), 0xffffff);

// Tentatively set the plotarea at (70, 80) and of 480 x 240 pixels in size. Use
// transparent border and white grid lines
c.setPlotArea(70, 80, 480, 240, -1, -1, Chart.Transparent, 0xffffff);

// Swap the axis so that the bars are drawn horizontally
c.swapXY();

// Add a multi-color bar chart layer using the supplied data. Use bar gradient
// lighting with the light intensity from 0.75 to 2.0
c.addBarLayer3(data, colors).setBorderColor(Chart.Transparent, Chart.barLighting(
    0.75, 2.0));

// 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 bottom y-axis title using 10pt Arial Bold font
c.yAxis().setTitle("USD (millions)", "Arial Bold", 10);

// Set y-axes to transparent
c.yAxis().setColors(Chart.Transparent);
c.yAxis2().setColors(Chart.Transparent);

// Disable ticks on the x-axis by setting the tick color to transparent
c.xAxis().setTickColor(Chart.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);

// Adjust the plot area size, such that the bounding box (inclusive of axes) is 30
// pixels from the left edge, 25 pixels below the title, 50 pixels from the right
// edge, and 25 pixels from the bottom edge.
c.packPlotArea(30, title.getHeight() + 25, c.getWidth() - 50, c.getHeight() - 25);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "", "title='Year {xLabel}: US$ {value}M'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Gradient Bar Shading
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/gradientbar.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class gradientbar implements DemoModule
{
    //Name of demo program
    public String toString() { return "Gradient Bar Shading"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the bar chart
        double[] data = {1350, 1600, 1950, 2300, 2700};

        // The labels for the bar chart
        String[] labels = {"2001", "2002", "2003", "2004", "2005"};

        // The colors for the bars
        int[] colors = {0xcc0000, 0x66aaee, 0xeebb22, 0xcccccc, 0xcc88ff};

        // Create a PieChart object of size 600 x 380 pixels.
        XYChart c = new XYChart(600, 380);

        // Use the white on black palette, which means the default text and line
        // colors are white
        c.setColors(Chart.whiteOnBlackPalette);

        // Use a vertical gradient color from blue (0000cc) to deep blue (000044) as
        // background. Use rounded corners of 30 pixels radius for the top-left and
        // bottom-right corners.
        c.setBackground(c.linearGradientColor(0, 0, 0, c.getHeight(), 0x0000cc,
            0x000044));
        c.setRoundedFrame(0xffffff, 30, 0, 30, 0);

        // Add a title using 18 pts Times New Roman Bold Italic font. Add 6 pixels
        // top and bottom margins to the title.
        TextBox title = c.addTitle("Annual Revenue for Star Tech",
            "Times New Roman Bold Italic", 18);
        title.setMargin2(0, 0, 6, 6);

        // Add a separator line in white color just under the title
        c.addLine(20, title.getHeight(), c.getWidth() - 21, title.getHeight(),
            0xffffff);

        // Tentatively set the plotarea at (70, 80) and of 480 x 240 pixels in size.
        // Use transparent border and white grid lines
        c.setPlotArea(70, 80, 480, 240, -1, -1, Chart.Transparent, 0xffffff);

        // Swap the axis so that the bars are drawn horizontally
        c.swapXY();

        // Add a multi-color bar chart layer using the supplied data. Use bar
        // gradient lighting with the light intensity from 0.75 to 2.0
        c.addBarLayer3(data, colors).setBorderColor(Chart.Transparent,
            Chart.barLighting(0.75, 2.0));

        // 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 bottom y-axis title using 10pt Arial Bold font
        c.yAxis().setTitle("USD (millions)", "Arial Bold", 10);

        // Set y-axes to transparent
        c.yAxis().setColors(Chart.Transparent);
        c.yAxis2().setColors(Chart.Transparent);

        // Disable ticks on the x-axis by setting the tick color to transparent
        c.xAxis().setTickColor(Chart.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);

        // Adjust the plot area size, such that the bounding box (inclusive of axes)
        // is 30 pixels from the left edge, 25 pixels below the title, 50 pixels from
        // the right edge, and 25 pixels from the bottom edge.
        c.packPlotArea(30, title.getHeight() + 25, c.getWidth() - 50, c.getHeight() -
            25);

        // Output the chart
        viewer.setChart(c);

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

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new gradientbar();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


Cylinder Bar Shading

Cylinder Bar Shading

This example demonstrates using cylinder shading effect for bars. It also demonstrates brushed metal background, rounded frame, and axis labels on both sides of the plot area.

  • The brushed silver background is achieved by using Chart.brushedSilverColor to create the brushed silver color, then use it in XYChart.XYChart as the chart background color.

  • The rounded frame is configured using BaseChart.setRoundedFrame.

  • The cylinder shading effect is configured by using BarLayer.setBarShape with CircleShape.

  • XYChart.syncYAxis is used to show two synchronized y-axes on both sides of the plot area.

  • Axis.setColors is used to set the y-axes to Transparent, so only the axis labels are visible.

  • The axis label font is set to Arial Bold using Axis.setLabelStyle.

Source Code Listing

[JSP Version] jspdemo/cylinderlightbar.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the bar chart
double[] data = {450, 560, 630, 800, 1100, 1350, 1600, 1950, 2300, 2700};

// The labels for the bar chart
String[] labels = {"1996", "1997", "1998", "1999", "2000", "2001", "2002", "2003",
    "2004", "2005"};

// Create a XYChart object of size 600 x 380 pixels. Set background color to brushed
// silver, with a 2 pixel 3D border. Use rounded corners of 20 pixels radius.
XYChart c = new XYChart(600, 380, Chart.brushedSilverColor(), Chart.Transparent, 2);

// Add a title to the chart using 18pts Times Bold Italic font. Set top/bottom
// margins to 8 pixels.
c.addTitle("Annual Revenue for Star Tech", "Times New Roman Bold Italic", 18
    ).setMargin2(0, 0, 8, 8);

// Set the plotarea at (70, 55) and of size 460 x 280 pixels. Use transparent border
// and black grid lines. Use rounded frame with radius of 20 pixels.
c.setPlotArea(70, 55, 460, 280, -1, -1, Chart.Transparent, 0x000000);
c.setRoundedFrame(0xffffff, 20);

// Add a multi-color bar chart layer using the supplied data. Set cylinder bar shape.
c.addBarLayer3(data).setBarShape(Chart.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 y-axes to transparent
c.yAxis().setColors(Chart.Transparent);
c.yAxis2().setColors(Chart.Transparent);

// Disable ticks on the x-axis by setting the tick color to transparent
c.xAxis().setTickColor(Chart.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
String chart1URL = c.makeSession(request, "chart1", Chart.JPG);

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "", "title='Year {xLabel}: US$ {value}M'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Cylinder Bar Shading
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/cylinderlightbar.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class cylinderlightbar implements DemoModule
{
    //Name of demo program
    public String toString() { return "Cylinder Bar Shading"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the bar chart
        double[] data = {450, 560, 630, 800, 1100, 1350, 1600, 1950, 2300, 2700};

        // The labels for the bar chart
        String[] labels = {"1996", "1997", "1998", "1999", "2000", "2001", "2002",
            "2003", "2004", "2005"};

        // Create a XYChart object of size 600 x 380 pixels. Set background color to
        // brushed silver, with a 2 pixel 3D border. Use rounded corners of 20 pixels
        // radius.
        XYChart c = new XYChart(600, 380, Chart.brushedSilverColor(),
            Chart.Transparent, 2);

        // Add a title to the chart using 18pts Times Bold Italic font. Set
        // top/bottom margins to 8 pixels.
        c.addTitle("Annual Revenue for Star Tech", "Times New Roman Bold Italic", 18
            ).setMargin2(0, 0, 8, 8);

        // Set the plotarea at (70, 55) and of size 460 x 280 pixels. Use transparent
        // border and black grid lines. Use rounded frame with radius of 20 pixels.
        c.setPlotArea(70, 55, 460, 280, -1, -1, Chart.Transparent, 0x000000);
        c.setRoundedFrame(0xffffff, 20);

        // Add a multi-color bar chart layer using the supplied data. Set cylinder
        // bar shape.
        c.addBarLayer3(data).setBarShape(Chart.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 y-axes to transparent
        c.yAxis().setColors(Chart.Transparent);
        c.yAxis2().setColors(Chart.Transparent);

        // Disable ticks on the x-axis by setting the tick color to transparent
        c.xAxis().setTickColor(Chart.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
        viewer.setChart(c);

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

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new cylinderlightbar();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


3D Bar Chart

3D Bar Chart

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

Source Code Listing

[JSP Version] jspdemo/threedbar.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the bar chart
double[] data = {85, 156, 179.5, 211, 123};

// The labels for the bar chart
String[] labels = {"Mon", "Tue", "Wed", "Thu", "Fri"};

// Create a XYChart object of size 300 x 280 pixels
XYChart c = new 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
String chart1URL = c.makeSession(request, "chart1");

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "", "title='{xLabel}: {value} MBytes'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    3D Bar Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/threedbar.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class threedbar implements DemoModule
{
    //Name of demo program
    public String toString() { return "3D Bar Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the bar chart
        double[] data = {85, 156, 179.5, 211, 123};

        // The labels for the bar chart
        String[] labels = {"Mon", "Tue", "Wed", "Thu", "Fri"};

        // Create a XYChart object of size 300 x 280 pixels
        XYChart c = new 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
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='{xLabel}: {value} MBytes'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new threedbar();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/cylinderbar.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the bar chart
double[] data = {85, 156, 179.5, 211, 123};

// The labels for the bar chart
String[] labels = {"Mon", "Tue", "Wed", "Thu", "Fri"};

// Create a XYChart object of size 400 x 240 pixels.
XYChart c = new 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
BarLayer layer = c.addBarLayer3(data);

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

// Set bar shape to circular (cylinder)
layer.setBarShape(Chart.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
String chart1URL = c.makeSession(request, "chart1");

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "", "title='{xLabel}: {value} MBytes'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Cylinder Bar Shape
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/cylinderbar.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class cylinderbar implements DemoModule
{
    //Name of demo program
    public String toString() { return "Cylinder Bar Shape"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the bar chart
        double[] data = {85, 156, 179.5, 211, 123};

        // The labels for the bar chart
        String[] labels = {"Mon", "Tue", "Wed", "Thu", "Fri"};

        // Create a XYChart object of size 400 x 240 pixels.
        XYChart c = new 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
        BarLayer layer = c.addBarLayer3(data);

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

        // Set bar shape to circular (cylinder)
        layer.setBarShape(Chart.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
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='{xLabel}: {value} MBytes'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new cylinderbar();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/polygonbar.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the bar chart
double[] data = {85, 156, 179.5, 211, 123, 176, 195};

// The labels for the bar chart
String[] labels = {"Square", "Star(8)", "Polygon(6)", "Cross", "Cross2", "Diamond",
    "Custom"};

// Create a XYChart object of size 500 x 280 pixels.
XYChart c = new 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
BarLayer layer = c.addBarLayer3(data);

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

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

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

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

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

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

// Set the last bar to a custom shape, specified as an array of (x, y) points in
// normalized coordinates
layer.setBarShape2(new int[]{-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
String chart1URL = c.makeSession(request, "chart1");

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "", "title='{xLabel}: {value}'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Polygon Bar Shapes
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/polygonbar.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class polygonbar implements DemoModule
{
    //Name of demo program
    public String toString() { return "Polygon Bar Shapes"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the bar chart
        double[] data = {85, 156, 179.5, 211, 123, 176, 195};

        // The labels for the bar chart
        String[] labels = {"Square", "Star(8)", "Polygon(6)", "Cross", "Cross2",
            "Diamond", "Custom"};

        // Create a XYChart object of size 500 x 280 pixels.
        XYChart c = new 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
        BarLayer layer = c.addBarLayer3(data);

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

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

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

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

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

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

        // Set the last bar to a custom shape, specified as an array of (x, y) points
        // in normalized coordinates
        layer.setBarShape2(new int[]{-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
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='{xLabel}: {value}'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new polygonbar();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/stackedbar.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the bar chart
double[] data0 = {100, 125, 245, 147, 67};
double[] data1 = {85, 156, 179, 211, 123};
double[] data2 = {97, 87, 56, 267, 157};

// The labels for the bar chart
String[] labels = {"Mon", "Tue", "Wed", "Thu", "Fri"};

// Create a XYChart object of size 500 x 320 pixels
XYChart c = new 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\nWorkload\n(MBytes\nPer 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
BarLayer layer = c.addBarLayer2(Chart.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
String chart1URL = c.makeSession(request, "chart1");

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName} on {xLabel}: {value} MBytes/hour'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Stacked Bar Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/stackedbar.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class stackedbar implements DemoModule
{
    //Name of demo program
    public String toString() { return "Stacked Bar Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the bar chart
        double[] data0 = {100, 125, 245, 147, 67};
        double[] data1 = {85, 156, 179, 211, 123};
        double[] data2 = {97, 87, 56, 267, 157};

        // The labels for the bar chart
        String[] labels = {"Mon", "Tue", "Wed", "Thu", "Fri"};

        // Create a XYChart object of size 500 x 320 pixels
        XYChart c = new 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\nWorkload\n(MBytes\nPer 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
        BarLayer layer = c.addBarLayer2(Chart.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
        viewer.setChart(c);

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

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new stackedbar();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


Percentage Bar Chart

Percentage Bar Chart

This example demonstrates creating a percentage bar chart with a legend box. It also demonstrates gradient background color, rounded frame, soft drop shadow, and using CDML to include custom icons in the legend box.

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

The key features demonstrated in this example are:

  • The gradient background is achieved by using BaseChart.linearGradientColor to define the gradient color, then use BaseChart.setBackground to set it as the chart background color.

  • The rounded frame is configured using BaseChart.setRoundedFrame.

  • The soft drop shadow is configured using BaseChart.setDropShadow.

  • The legend box is added using BaseChart.addLegend. The legend key (the color box to the right of each legend entry) is set to 16 x 32 pixels using LegendBox.setKeySize, so as to match the size of the custom icons.

  • The ordering of the legend entries is reversed using Layer.setLegend, so that the legend box shows the last data set name first. 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 on the top of the stacked bars. Reversing the ordering of the legend entries will make it visually consistent with the stacking order of the data set.

  • The percentage bar layer is added using XYChart.addBarLayer2 with the Percentage predefined constant.

  • Multiple data sets are added to the bar layer using Layer.addDataSet. CDML is used to include custom icons in the data set names.

  • Labels for the bar segments are added 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

[JSP Version] jspdemo/percentbar.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the bar chart
double[] data0 = {100, 125, 245, 147, 67};
double[] data1 = {85, 156, 179, 211, 123};
double[] data2 = {97, 87, 56, 267, 157};

// The labels for the bar chart
String[] labels = {"Mon", "Tue", "Wed", "Thu", "Fri"};

// Create a XYChart object of size 500 x 320 pixels. Use a vertical gradient color
// from pale blue (e8f0f8) to sky blue (aaccff) spanning half the chart height as
// background. Set border to blue (88aaee). Use rounded corners. Enable soft drop
// shadow.
XYChart c = new XYChart(500, 320);
c.setBackground(c.linearGradientColor(0, 0, 0, c.getHeight() / 2, 0xe8f0f8, 0xaaccff
    ), 0x88aaee);
c.setRoundedFrame();
c.setDropShadow();

//Set search path to current JSP directory for loading icon images
c.setSearchPath(getServletConfig().getServletContext(), request);

// Add a title to the chart using 15 points Arial Italic. Set top/bottom margins to
// 15 pixels.
TextBox title = c.addTitle("Weekly Product Sales", "Arial Italic", 15);
title.setMargin2(0, 0, 15, 15);

// Tentatively set the plotarea to 50 pixels from the left edge, and to just under
// the title. Set the width to 60% of the chart width, and the height to 50 pixels
// from the bottom edge. Use pale blue (e8f0f8) background, transparent border, and
// grey (aaaaaa) grid lines.
c.setPlotArea(50, title.getHeight(), c.getWidth() * 6 / 10, c.getHeight() -
    title.getHeight() - 50, 0xe8f0f8, -1, Chart.Transparent, 0xaaaaaa);

// Add a legend box where the top-right corner is anchored at 10 pixels from the
// right edge, and just under the title. Use vertical layout and 8 points Arial font.
LegendBox legendBox = c.addLegend(c.getWidth() - 10, title.getHeight(), true,
    "Arial", 8);
legendBox.setAlignment(Chart.TopRight);

// Set the legend box background and border to transparent
legendBox.setBackground(Chart.Transparent, Chart.Transparent);

// Set the legend box icon size to 16 x 32 pixels to match with custom icon size
legendBox.setKeySize(16, 32);

// Set axes to transparent
c.xAxis().setColors(Chart.Transparent);
c.yAxis().setColors(Chart.Transparent);

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

// Add a percentage bar layer
BarLayer layer = c.addBarLayer2(Chart.Percentage);

// Add the three data sets to the bar layer, using icons images with labels as data
// set names
layer.addDataSet(data0, 0x66aaee,
    "<*block,valign=absmiddle*><*img=service.png*> Service<*/*>");
layer.addDataSet(data1, 0xeebb22,
    "<*block,valign=absmiddle*><*img=software.png*> Software<*/*>");
layer.addDataSet(data2, 0xcc88ff,
    "<*block,valign=absmiddle*><*img=computer.png*> Hardware<*/*>");

// Use soft lighting effect with light direction from top
layer.setBorderColor(Chart.Transparent, Chart.softLighting(Chart.Top));

// Enable data label at the middle of the the bar
layer.setDataLabelStyle().setAlignment(Chart.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(Chart.ReverseLegend);

// Adjust the plot area size, such that the bounding box (inclusive of axes) is 15
// pixels from the left edge, just below the title, 10 pixels to the right of the
// legend box, and 15 pixels from the bottom edge.
c.packPlotArea(15, title.getHeight(), c.layoutLegend().getLeftX() - 10, c.getHeight()
     - 15);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName} revenue on {xLabel}: US${value}K ({percent}%)'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Percentage Bar Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/percentbar.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class percentbar implements DemoModule
{
    //Name of demo program
    public String toString() { return "Percentage Bar Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the bar chart
        double[] data0 = {100, 125, 245, 147, 67};
        double[] data1 = {85, 156, 179, 211, 123};
        double[] data2 = {97, 87, 56, 267, 157};

        // The labels for the bar chart
        String[] labels = {"Mon", "Tue", "Wed", "Thu", "Fri"};

        // Create a XYChart object of size 500 x 320 pixels. Use a vertical gradient
        // color from pale blue (e8f0f8) to sky blue (aaccff) spanning half the chart
        // height as background. Set border to blue (88aaee). Use rounded corners.
        // Enable soft drop shadow.
        XYChart c = new XYChart(500, 320);
        c.setBackground(c.linearGradientColor(0, 0, 0, c.getHeight() / 2, 0xe8f0f8,
            0xaaccff), 0x88aaee);
        c.setRoundedFrame();
        c.setDropShadow();

        // Add a title to the chart using 15 points Arial Italic. Set top/bottom
        // margins to 15 pixels.
        TextBox title = c.addTitle("Weekly Product Sales", "Arial Italic", 15);
        title.setMargin2(0, 0, 15, 15);

        // Tentatively set the plotarea to 50 pixels from the left edge, and to just
        // under the title. Set the width to 60% of the chart width, and the height
        // to 50 pixels from the bottom edge. Use pale blue (e8f0f8) background,
        // transparent border, and grey (aaaaaa) grid lines.
        c.setPlotArea(50, title.getHeight(), c.getWidth() * 6 / 10, c.getHeight() -
            title.getHeight() - 50, 0xe8f0f8, -1, Chart.Transparent, 0xaaaaaa);

        // Add a legend box where the top-right corner is anchored at 10 pixels from
        // the right edge, and just under the title. Use vertical layout and 8 points
        // Arial font.
        LegendBox legendBox = c.addLegend(c.getWidth() - 10, title.getHeight(), true,
            "Arial", 8);
        legendBox.setAlignment(Chart.TopRight);

        // Set the legend box background and border to transparent
        legendBox.setBackground(Chart.Transparent, Chart.Transparent);

        // Set the legend box icon size to 16 x 32 pixels to match with custom icon
        // size
        legendBox.setKeySize(16, 32);

        // Set axes to transparent
        c.xAxis().setColors(Chart.Transparent);
        c.yAxis().setColors(Chart.Transparent);

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

        // Add a percentage bar layer
        BarLayer layer = c.addBarLayer2(Chart.Percentage);

        // Add the three data sets to the bar layer, using icons images with labels
        // as data set names
        layer.addDataSet(data0, 0x66aaee,
            "<*block,valign=absmiddle*><*img=service.png*> Service<*/*>");
        layer.addDataSet(data1, 0xeebb22,
            "<*block,valign=absmiddle*><*img=software.png*> Software<*/*>");
        layer.addDataSet(data2, 0xcc88ff,
            "<*block,valign=absmiddle*><*img=computer.png*> Hardware<*/*>");

        // Use soft lighting effect with light direction from top
        layer.setBorderColor(Chart.Transparent, Chart.softLighting(Chart.Top));

        // Enable data label at the middle of the the bar
        layer.setDataLabelStyle().setAlignment(Chart.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(Chart.ReverseLegend);

        // Adjust the plot area size, such that the bounding box (inclusive of axes)
        // is 15 pixels from the left edge, just below the title, 10 pixels to the
        // right of the legend box, and 15 pixels from the bottom edge.
        c.packPlotArea(15, title.getHeight(), c.layoutLegend().getLeftX() - 10,
            c.getHeight() - 15);

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='{dataSetName} revenue on {xLabel}: US${value}K ({percent}%)'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new percentbar();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/multibar.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the bar chart
double[] data0 = {100, 125, 245, 147, 67};
double[] data1 = {85, 156, 179, 211, 123};
double[] data2 = {97, 87, 56, 267, 157};
String[] labels = {"Mon", "Tue", "Wed", "Thu", "Fri"};

// Create a XYChart object of size 400 x 240 pixels
XYChart c = new 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(Chart.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
BarLayer layer = c.addBarLayer2(Chart.Side, 3);
layer.addDataSet(data0, 0xff8080, "Server #1");
layer.addDataSet(data1, 0x80ff80, "Server #2");
layer.addDataSet(data2, 0x8080ff, "Server #3");

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName} on {xLabel}: {value} MBytes/hour'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Multi-Bar Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/multibar.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class multibar implements DemoModule
{
    //Name of demo program
    public String toString() { return "Multi-Bar Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the bar chart
        double[] data0 = {100, 125, 245, 147, 67};
        double[] data1 = {85, 156, 179, 211, 123};
        double[] data2 = {97, 87, 56, 267, 157};
        String[] labels = {"Mon", "Tue", "Wed", "Thu", "Fri"};

        // Create a XYChart object of size 400 x 240 pixels
        XYChart c = new 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(Chart.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
        BarLayer layer = c.addBarLayer2(Chart.Side, 3);
        layer.addDataSet(data0, 0xff8080, "Server #1");
        layer.addDataSet(data1, 0x80ff80, "Server #2");
        layer.addDataSet(data2, 0x8080ff, "Server #3");

        // Output the chart
        viewer.setChart(c);

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

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new multibar();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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 Chart.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

[JSP Version] jspdemo/softmultibar.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the bar chart
double[] data0 = {100, 125, 245, 147, 67};
double[] data1 = {85, 156, 179, 211, 123};
double[] data2 = {97, 87, 56, 267, 157};
String[] labels = {"Mon", "Tue", "Wed", "Thur", "Fri"};

// Create a XYChart object of size 540 x 375 pixels
XYChart c = new 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(Chart.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
BarLayer layer = c.addBarLayer2(Chart.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(Chart.Transparent, Chart.softLighting(Chart.Top));

// Configure the bars within a group to touch each others (no gap)
layer.setBarGap(0.2, Chart.TouchBar);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName} on {xLabel}: {value} MBytes/hour'");
%>
<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 color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/softmultibar.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class softmultibar implements DemoModule
{
    //Name of demo program
    public String toString() { return "Soft Multi-Bar Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the bar chart
        double[] data0 = {100, 125, 245, 147, 67};
        double[] data1 = {85, 156, 179, 211, 123};
        double[] data2 = {97, 87, 56, 267, 157};
        String[] labels = {"Mon", "Tue", "Wed", "Thur", "Fri"};

        // Create a XYChart object of size 540 x 375 pixels
        XYChart c = new 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(Chart.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
        BarLayer layer = c.addBarLayer2(Chart.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(Chart.Transparent, Chart.softLighting(Chart.Top));

        // Configure the bars within a group to touch each others (no gap)
        layer.setBarGap(0.2, Chart.TouchBar);

        // Output the chart
        viewer.setChart(c);

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

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new softmultibar();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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 Chart.glassEffect, then applied to the bars using Layer.setBorderColor.

Source Code Listing

[JSP Version] jspdemo/glassmultibar.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the bar chart
double[] data0 = {100, 125, 245, 147, 67};
double[] data1 = {85, 156, 179, 211, 123};
double[] data2 = {97, 87, 56, 267, 157};
String[] labels = {"Mon", "Tue", "Wed", "Thur", "Fri"};

// Create a XYChart object of size 540 x 375 pixels
XYChart c = new 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(Chart.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
BarLayer layer = c.addBarLayer2(Chart.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(Chart.Transparent, Chart.glassEffect(Chart.NormalGlare,
    Chart.Left));

// Configure the bars within a group to touch each others (no gap)
layer.setBarGap(0.2, Chart.TouchBar);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName} on {xLabel}: {value} MBytes/hour'");
%>
<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 color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/glassmultibar.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class glassmultibar implements DemoModule
{
    //Name of demo program
    public String toString() { return "Glass Multi-Bar Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the bar chart
        double[] data0 = {100, 125, 245, 147, 67};
        double[] data1 = {85, 156, 179, 211, 123};
        double[] data2 = {97, 87, 56, 267, 157};
        String[] labels = {"Mon", "Tue", "Wed", "Thur", "Fri"};

        // Create a XYChart object of size 540 x 375 pixels
        XYChart c = new 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(Chart.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
        BarLayer layer = c.addBarLayer2(Chart.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(Chart.Transparent, Chart.glassEffect(Chart.NormalGlare,
            Chart.Left));

        // Configure the bars within a group to touch each others (no gap)
        layer.setBarGap(0.2, Chart.TouchBar);

        // Output the chart
        viewer.setChart(c);

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

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new glassmultibar();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


Gradient Multi-Bar Chart

Gradient Multi-Bar Chart

This example demonstrates a multi-bar chart with bar gradient shading and 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.

  • The bar gradient effect is defined using Chart.barLighting, then applied to the bars using Layer.setBorderColor.

Source Code Listing

[JSP Version] jspdemo/gradientmultibar.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the bar chart
double[] data0 = {100, 125, 245, 147, 67};
double[] data1 = {85, 156, 179, 211, 123};
double[] data2 = {97, 87, 56, 267, 157};
String[] labels = {"Mon", "Tue", "Wed", "Thur", "Fri"};

// Create a XYChart object of size 540 x 375 pixels
XYChart c = new 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 grey (888888) to black (000000) as background. Set border and
// grid lines to white (ffffff).
c.setPlotArea(50, 55, 440, 280, c.linearGradientColor(0, 55, 0, 335, 0x888888,
    0x000000), -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(Chart.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
BarLayer layer = c.addBarLayer2(Chart.Side, 4);
layer.addDataSet(data0, 0x66aaee, "Server #1");
layer.addDataSet(data1, 0xeebb22, "Server #2");
layer.addDataSet(data2, 0xcc0000, "Server #3");

// Set bar border to transparent. Use bar gradient lighting with light intensity from
// 0.75 to 1.75.
layer.setBorderColor(Chart.Transparent, Chart.barLighting(0.75, 1.75));

// Configure the bars within a group to touch each others (no gap)
layer.setBarGap(0.2, Chart.TouchBar);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName} on {xLabel}: {value} MBytes/hour'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Gradient Multi-Bar Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/gradientmultibar.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class gradientmultibar implements DemoModule
{
    //Name of demo program
    public String toString() { return "Gradient Multi-Bar Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the bar chart
        double[] data0 = {100, 125, 245, 147, 67};
        double[] data1 = {85, 156, 179, 211, 123};
        double[] data2 = {97, 87, 56, 267, 157};
        String[] labels = {"Mon", "Tue", "Wed", "Thur", "Fri"};

        // Create a XYChart object of size 540 x 375 pixels
        XYChart c = new 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 grey (888888) to black (000000) as
        // background. Set border and grid lines to white (ffffff).
        c.setPlotArea(50, 55, 440, 280, c.linearGradientColor(0, 55, 0, 335,
            0x888888, 0x000000), -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(Chart.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
        BarLayer layer = c.addBarLayer2(Chart.Side, 4);
        layer.addDataSet(data0, 0x66aaee, "Server #1");
        layer.addDataSet(data1, 0xeebb22, "Server #2");
        layer.addDataSet(data2, 0xcc0000, "Server #3");

        // Set bar border to transparent. Use bar gradient lighting with light
        // intensity from 0.75 to 1.75.
        layer.setBorderColor(Chart.Transparent, Chart.barLighting(0.75, 1.75));

        // Configure the bars within a group to touch each others (no gap)
        layer.setBarGap(0.2, Chart.TouchBar);

        // Output the chart
        viewer.setChart(c);

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

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new gradientmultibar();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/multicylinder.jsp
<%@page import="ChartDirector.*" %>
<%
// Data for the chart
double[] data0 = {100, 125, 245, 147, 67, 96, 160, 145, 97, 167, 220, 125};
double[] data1 = {85, 156, 179, 211, 123, 225, 127, 99, 111, 260, 175, 156};
double[] data2 = {97, 87, 56, 267, 157, 157, 67, 156, 77, 87, 197, 87};
String[] labels = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept",
    "Oct", "Nov", "Dec"};

// Create a XYChart object of size 560 x 280 pixels.
XYChart c = new 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, Chart.Transparent,
    c.dashLineColor(0xcccccc, Chart.DotLine), c.dashLineColor(0xcccccc, Chart.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(Chart.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
BarLayer layer = c.addBarLayer2(Chart.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(Chart.CircleShape);

// Configure the bars within a group to touch each others (no gap)
layer.setBarGap(0.2, Chart.TouchBar);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName} on {xLabel}: {value} MBytes/hour'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Multi-Cylinder Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/multicylinder.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class multicylinder implements DemoModule
{
    //Name of demo program
    public String toString() { return "Multi-Cylinder Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // Data for the chart
        double[] data0 = {100, 125, 245, 147, 67, 96, 160, 145, 97, 167, 220, 125};
        double[] data1 = {85, 156, 179, 211, 123, 225, 127, 99, 111, 260, 175, 156};
        double[] data2 = {97, 87, 56, 267, 157, 157, 67, 156, 77, 87, 197, 87};
        String[] labels = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
            "Sept", "Oct", "Nov", "Dec"};

        // Create a XYChart object of size 560 x 280 pixels.
        XYChart c = new 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, Chart.Transparent,
            c.dashLineColor(0xcccccc, Chart.DotLine), c.dashLineColor(0xcccccc,
            Chart.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(
            Chart.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
        BarLayer layer = c.addBarLayer2(Chart.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(Chart.CircleShape);

        // Configure the bars within a group to touch each others (no gap)
        layer.setBarGap(0.2, Chart.TouchBar);

        // Output the chart
        viewer.setChart(c);

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

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new multicylinder();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/multishapebar.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the bar chart
double[] data0 = {100, 125, 245, 147};
double[] data1 = {85, 156, 179, 211};
double[] data2 = {97, 87, 56, 267};
String[] labels = {"1st Quarter", "2nd Quarter", "3rd Quarter", "4th Quarter"};

// Create a XYChart object of size 600 x 350 pixels
XYChart c = new 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(Chart.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
BarLayer layer = c.addBarLayer2(Chart.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(Chart.StarShape(6), 0);

// Set data set 2 to use a bar shapre of a 6-sided polygon
layer.setBarShape(Chart.PolygonShape(6), 1);

// Set data set 3 to use an X bar shape
layer.setBarShape(Chart.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
String chart1URL = c.makeSession(request, "chart1");

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName}: {xLabel} Revenue = {value} millions'");
%>
<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 color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/multishapebar.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class multishapebar implements DemoModule
{
    //Name of demo program
    public String toString() { return "Multi-Shape Bar Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the bar chart
        double[] data0 = {100, 125, 245, 147};
        double[] data1 = {85, 156, 179, 211};
        double[] data2 = {97, 87, 56, 267};
        String[] labels = {"1st Quarter", "2nd Quarter", "3rd Quarter", "4th Quarter"
            };

        // Create a XYChart object of size 600 x 350 pixels
        XYChart c = new 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(Chart.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
        BarLayer layer = c.addBarLayer2(Chart.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(Chart.StarShape(6), 0);

        // Set data set 2 to use a bar shapre of a 6-sided polygon
        layer.setBarShape(Chart.PolygonShape(6), 1);

        // Set data set 3 to use an X bar shape
        layer.setBarShape(Chart.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
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='{dataSetName}: {xLabel} Revenue = {value} millions'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new multishapebar();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/overlapbar.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the bar chart
double[] data0 = {100, 125, 156, 147, 87, 124, 178, 109, 140, 106, 192, 122};
double[] data1 = {122, 156, 179, 211, 198, 177, 160, 220, 190, 188, 220, 270};
double[] data2 = {167, 190, 213, 267, 250, 320, 212, 199, 245, 267, 240, 310};
String[] labels = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept",
    "Oct", "Nov", "Dec"};

// Create a XYChart object of size 580 x 280 pixels
XYChart c = new 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(Chart.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
BarLayer layer = c.addBarLayer2(Chart.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
String chart1URL = c.makeSession(request, "chart1");

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{xLabel} Revenue on {dataSetName}: {value} millions'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Overlapping Bar Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/overlapbar.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class overlapbar implements DemoModule
{
    //Name of demo program
    public String toString() { return "Overlapping Bar Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the bar chart
        double[] data0 = {100, 125, 156, 147, 87, 124, 178, 109, 140, 106, 192, 122};
        double[] data1 = {122, 156, 179, 211, 198, 177, 160, 220, 190, 188, 220, 270}
            ;
        double[] data2 = {167, 190, 213, 267, 250, 320, 212, 199, 245, 267, 240, 310}
            ;
        String[] labels = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
            "Sept", "Oct", "Nov", "Dec"};

        // Create a XYChart object of size 580 x 280 pixels
        XYChart c = new 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(Chart.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
        BarLayer layer = c.addBarLayer2(Chart.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
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='{xLabel} Revenue on {dataSetName}: {value} millions'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new overlapbar();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/multistackbar.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the bar chart
double[] data0 = {44, 55, 100};
double[] data1 = {97, 87, 167};
double[] data2 = {156, 78, 147};
double[] data3 = {125, 118, 211};

// The labels for the bar chart. The labels contains embedded images as icons.
String[] labels = {"<*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.
XYChart c = new XYChart(600, 350, 0xe0e0ff, 0xccccff, 1);

//Set search path to current JSP directory for loading icon images
c.setSearchPath(getServletConfig().getServletContext(), request);

// 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
BarLayer layer = c.addBarLayer2(Chart.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(Chart.Transparent);

// Set the aggregate label format
layer.setAggregateLabelFormat("Year {dataGroupName}\n{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 legendBox = c.addLegend2(310, 300, 2, "Arial Bold Italic", 8);
legendBox.setAlignment(Chart.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(Chart.Transparent, Chart.Transparent);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='Year {dataGroupName} {dataSetName} {xLabel} Revenue: {value} millions'");
%>
<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 color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/multistackbar.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class multistackbar implements DemoModule
{
    //Name of demo program
    public String toString() { return "Multi-Stacked Bar Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the bar chart
        double[] data0 = {44, 55, 100};
        double[] data1 = {97, 87, 167};
        double[] data2 = {156, 78, 147};
        double[] data3 = {125, 118, 211};

        // The labels for the bar chart. The labels contains embedded images as
        // icons.
        String[] labels = {"<*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.
        XYChart c = new XYChart(600, 350, 0xe0e0ff, 0xccccff, 1);

        // 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
        BarLayer layer = c.addBarLayer2(Chart.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(Chart.Transparent);

        // Set the aggregate label format
        layer.setAggregateLabelFormat("Year {dataGroupName}\n{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 legendBox = c.addLegend2(310, 300, 2, "Arial Bold Italic", 8);
        legendBox.setAlignment(Chart.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(Chart.Transparent, Chart.Transparent);

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='Year {dataGroupName} {dataSetName} {xLabel} Revenue: {value} " +
            "millions'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new multistackbar();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/depthbar.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the bar chart
double[] data0 = {100, 125, 245, 147, 67};
double[] data1 = {85, 156, 179, 211, 123};
double[] data2 = {97, 87, 56, 267, 157};

// The labels for the bar chart
String[] labels = {"Mon", "Tue", "Wed", "Thu", "Fri"};

// Create a XYChart object of size 500 x 320 pixels
XYChart c = new 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\nWorkload\n(MBytes\nPer 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
String chart1URL = c.makeSession(request, "chart1");

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName} on {xLabel}: {value} MBytes/hour'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Depth Bar Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/depthbar.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class depthbar implements DemoModule
{
    //Name of demo program
    public String toString() { return "Depth Bar Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the bar chart
        double[] data0 = {100, 125, 245, 147, 67};
        double[] data1 = {85, 156, 179, 211, 123};
        double[] data2 = {97, 87, 56, 267, 157};

        // The labels for the bar chart
        String[] labels = {"Mon", "Tue", "Wed", "Thu", "Fri"};

        // Create a XYChart object of size 500 x 320 pixels
        XYChart c = new 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\nWorkload\n(MBytes\nPer 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
        viewer.setChart(c);

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

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new depthbar();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/posnegbar.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the bar chart
double[] data = {-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
String[] labels = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
    "Oct", "Nov", "Dec"};

// Create a XYChart object of size 500 x 320 pixels
XYChart c = new 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
BarLayer layer = c.addBarLayer2(Chart.Overlay);

// Select positive data and add it as data set with blue (6666ff) color
layer.addDataSet(new ArrayMath(data).selectGEZ(null, Chart.NoValue).result(),
    0x6666ff);

// Select negative data and add it as data set with orange (ff6600) color
layer.addDataSet(new ArrayMath(data).selectLTZ(null, Chart.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
String chart1URL = c.makeSession(request, "chart1");

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "", "title='{xLabel}: {value}%'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Positive Negative Bars
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/posnegbar.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class posnegbar implements DemoModule
{
    //Name of demo program
    public String toString() { return "Positive Negative Bars"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the bar chart
        double[] data = {-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
        String[] labels = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
            "Sep", "Oct", "Nov", "Dec"};

        // Create a XYChart object of size 500 x 320 pixels
        XYChart c = new 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
        BarLayer layer = c.addBarLayer2(Chart.Overlay);

        // Select positive data and add it as data set with blue (6666ff) color
        layer.addDataSet(new ArrayMath(data).selectGEZ(null, Chart.NoValue).result(),
            0x6666ff);

        // Select negative data and add it as data set with orange (ff6600) color
        layer.addDataSet(new ArrayMath(data).selectLTZ(null, Chart.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
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='{xLabel}: {value}%'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new posnegbar();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/hbar.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the bar chart
double[] data = {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
String[] labels = {"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
XYChart c = new 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, Chart.Transparent, Chart.Transparent,
    Chart.Transparent, Chart.Transparent, Chart.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)
BarLayer 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 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(Chart.Transparent, 0x663300);

// Set the y axis and labels to Transparent
c.yAxis().setColors(Chart.Transparent, Chart.Transparent);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "", "title='{xLabel}: US${value} millions'")
    ;
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Borderless Bar Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/hbar.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class hbar implements DemoModule
{
    //Name of demo program
    public String toString() { return "Borderless Bar Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the bar chart
        double[] data = {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
        String[] labels = {"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
        XYChart c = new 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, Chart.Transparent, Chart.Transparent,
            Chart.Transparent, Chart.Transparent, Chart.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)
        BarLayer 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 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(Chart.Transparent, 0x663300);

        // Set the y axis and labels to Transparent
        c.yAxis().setColors(Chart.Transparent, Chart.Transparent);

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='{xLabel}: US${value} millions'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new hbar();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/dualhbar.jsp
<%@page import="ChartDirector.*" %>
<%
// The age groups
String[] labels = {"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)
double[] male = {215, 238, 225, 236, 235, 260, 286, 340, 363, 305, 259, 164, 135,
    127, 102, 68, 66};

// The female population (in thousands)
double[] female = {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
XYChart c = new 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(Chart.TopRight);

// Add the pink (0xf0c0c0) bar chart layer using the female data
BarLayer 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(Chart.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, Chart.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
TextBox 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(Chart.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.
XYChart c2 = new XYChart(280, 300, Chart.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
BarLayer 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(Chart.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, Chart.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, Chart.Transparent, -1, Chart.Transparent);

//=============================================================
//    Use a MultiChart to contain both bar charts
//=============================================================

// Create a MultiChart object of size 590 x 320 pixels.
MultiChart m = new 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(Chart.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
String chart1URL = m.makeSession(request, "chart1");

// Include tool tip for the chart
String imageMap1 = m.getHTMLImageMap("", "",
    "title='{dataSetName} (Age {xLabel}): Population {value}K'");
%>
<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 color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/dualhbar.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class dualhbar implements DemoModule
{
    //Name of demo program
    public String toString() { return "Dual Horizontal Bar Charts"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The age groups
        String[] labels = {"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)
        double[] male = {215, 238, 225, 236, 235, 260, 286, 340, 363, 305, 259, 164,
            135, 127, 102, 68, 66};

        // The female population (in thousands)
        double[] female = {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
        XYChart c = new 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(Chart.TopRight);

        // Add the pink (0xf0c0c0) bar chart layer using the female data
        BarLayer 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(Chart.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, Chart.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
        TextBox 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(Chart.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.
        XYChart c2 = new XYChart(280, 300, Chart.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
        BarLayer 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(Chart.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, Chart.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, Chart.Transparent, -1, Chart.Transparent);

        //=============================================================
        //    Use a MultiChart to contain both bar charts
        //=============================================================

        // Create a MultiChart object of size 590 x 320 pixels.
        MultiChart m = new 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(Chart.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
        viewer.setChart(m);

        //include tool tip for the chart
        viewer.setImageMap(m.getHTMLImageMap("clickable", "",
            "title='{dataSetName} (Age {xLabel}): Population {value}K'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new dualhbar();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


Bars with Marks

Bars with Marks

This example demonstrates combine a bar layer with a box-whisker layer to create bars with marks. It also demonstrates gradient background color, rounded frame, soft drop shadow, and automatic resizing of the plot area to fit the chart.

  • The gradient background is achieved by using BaseChart.linearGradientColor to define the gradient color, then use BaseChart.setBackground to set it as the chart background color.

  • The rounded frame is configured using BaseChart.setRoundedFrame.

  • The soft drop shadow is configured using BaseChart.setDropShadow.

  • The box-whisker layer is created using XYChart.addBoxWhiskerLayer. Only the middle data set is used, so the box- whisker symbol appears as a mark line. BaseBoxLayer.setDataGap is used to reduce the horizontal gap between the box- whisker symbols, so as to make the mark lines wider than the bars.

  • The bar layer is created using XYChart.addBarLayer.

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

  • After the entire chart is configured, the XYChart.packPlotArea method is used to adjust the plot area size, so as to fit the plot area and the axes in a given bounding box.

Source Code Listing

[JSP Version] jspdemo/markbar.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the bars and the marks
double[] barData = {100, 125, 245, 147, 67, 96, 160, 145, 97, 167, 220, 125};
double[] markData = {85, 156, 220, 120, 80, 110, 140, 130, 111, 180, 175, 100};

// The labels for the bar chart
String[] labels = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept",
    "Oct", "Nov", "Dec"};

// Create a XYChart object of size 480 x 360 pixels. Use a vertical gradient color
// from pale blue (e8f0f8) to sky blue (aaccff) spanning half the chart height as
// background. Set border to blue (88aaee). Use rounded corners. Enable soft drop
// shadow.
XYChart c = new XYChart(480, 360);
c.setBackground(c.linearGradientColor(0, 0, 0, c.getHeight() / 2, 0xe8f0f8, 0xaaccff
    ), 0x88aaee);
c.setRoundedFrame();
c.setDropShadow();

// Add a title to the chart using 15 points Arial Italic font. Set top/bottom margins
// to 12 pixels.
TextBox title = c.addTitle("Bars with Marks Demonstration", "Arial Italic", 15);
title.setMargin2(0, 0, 12, 12);

// Tentatively set the plotarea to 50 pixels from the left edge to allow for the
// y-axis, and to just under the title. Set the width to 65 pixels less than the
// chart width, and the height to reserve 90 pixels at the bottom for the x-axis and
// the legend box. Use pale blue (e8f0f8) background, transparent border, and grey
// (888888) dotted horizontal grid lines.
c.setPlotArea(50, title.getHeight(), c.getWidth() - 65, c.getHeight() -
    title.getHeight() - 90, 0xe8f0f8, -1, Chart.Transparent, c.dashLineColor(
    0x888888, Chart.DotLine));

// Add a legend box where the bottom-center is anchored to the 15 pixels above the
// bottom-center of the chart. Use horizontal layout and 8 points Arial font.
LegendBox legendBox = c.addLegend(c.getWidth() / 2, c.getHeight() - 15, false,
    "Arial", 8);
legendBox.setAlignment(Chart.BottomCenter);

// Set the legend box background and border to pale blue (e8f0f8) and bluish grey
// (445566)
legendBox.setBackground(0xe8f0f8, 0x445566);

// Use rounded corners of 5 pixel radius for the legend box
legendBox.setRoundedCorners(5);

// Use line style legend key
legendBox.setLineStyleKey();

// Set axes to transparent
c.xAxis().setColors(Chart.Transparent);
c.yAxis().setColors(Chart.Transparent);

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

// Add a box-whisker layer with just the middle mark visible for the marks. Use red
// (ff0000) color for the mark, with a line width of 2 pixels and 10% horizontal gap
BoxWhiskerLayer markLayer = c.addBoxWhiskerLayer(null, null, null, null, markData,
    -1, 0xff0000);
markLayer.setLineWidth(2);
markLayer.setDataGap(0.1);

// Add the legend key for the mark line
legendBox.addKey("Target", 0xff0000, 2);

// Tool tip for the mark layer
markLayer.setHTMLImageMap("", "", "title='Target at {xLabel}: {med}'");

// Add a blue (0066cc) bar layer using the given data.
BarLayer barLayer = c.addBarLayer(barData, 0x0066cc, "Actual");

// Use soft lighting effect for the bars with light direction from left.
barLayer.setBorderColor(Chart.Transparent, Chart.softLighting(Chart.Left));

// Tool tip for the bar layer
barLayer.setHTMLImageMap("", "", "title='{dataSetName} at {xLabel}: {value}'");

// Adjust the plot area size, such that the bounding box (inclusive of axes) is 10
// pixels from the left edge, just below the title, 15 pixels from the right edge,
// and 10 pixels above the legend box.
c.packPlotArea(10, title.getHeight(), c.getWidth() - 15, c.layoutLegend().getTopY() -
    10);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Bars with Marks
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/markbar.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class markbar implements DemoModule
{
    //Name of demo program
    public String toString() { return "Bars with Marks"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the bars and the marks
        double[] barData = {100, 125, 245, 147, 67, 96, 160, 145, 97, 167, 220, 125};
        double[] markData = {85, 156, 220, 120, 80, 110, 140, 130, 111, 180, 175, 100
            };

        // The labels for the bar chart
        String[] labels = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
            "Sept", "Oct", "Nov", "Dec"};

        // Create a XYChart object of size 480 x 360 pixels. Use a vertical gradient
        // color from pale blue (e8f0f8) to sky blue (aaccff) spanning half the chart
        // height as background. Set border to blue (88aaee). Use rounded corners.
        // Enable soft drop shadow.
        XYChart c = new XYChart(480, 360);
        c.setBackground(c.linearGradientColor(0, 0, 0, c.getHeight() / 2, 0xe8f0f8,
            0xaaccff), 0x88aaee);
        c.setRoundedFrame();
        c.setDropShadow();

        // Add a title to the chart using 15 points Arial Italic font. Set top/bottom
        // margins to 12 pixels.
        TextBox title = c.addTitle("Bars with Marks Demonstration", "Arial Italic",
            15);
        title.setMargin2(0, 0, 12, 12);

        // Tentatively set the plotarea to 50 pixels from the left edge to allow for
        // the y-axis, and to just under the title. Set the width to 65 pixels less
        // than the chart width, and the height to reserve 90 pixels at the bottom
        // for the x-axis and the legend box. Use pale blue (e8f0f8) background,
        // transparent border, and grey (888888) dotted horizontal grid lines.
        c.setPlotArea(50, title.getHeight(), c.getWidth() - 65, c.getHeight() -
            title.getHeight() - 90, 0xe8f0f8, -1, Chart.Transparent, c.dashLineColor(
            0x888888, Chart.DotLine));

        // Add a legend box where the bottom-center is anchored to the 15 pixels
        // above the bottom-center of the chart. Use horizontal layout and 8 points
        // Arial font.
        LegendBox legendBox = c.addLegend(c.getWidth() / 2, c.getHeight() - 15,
            false, "Arial", 8);
        legendBox.setAlignment(Chart.BottomCenter);

        // Set the legend box background and border to pale blue (e8f0f8) and bluish
        // grey (445566)
        legendBox.setBackground(0xe8f0f8, 0x445566);

        // Use rounded corners of 5 pixel radius for the legend box
        legendBox.setRoundedCorners(5);

        // Use line style legend key
        legendBox.setLineStyleKey();

        // Set axes to transparent
        c.xAxis().setColors(Chart.Transparent);
        c.yAxis().setColors(Chart.Transparent);

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

        // Add a box-whisker layer with just the middle mark visible for the marks.
        // Use red (ff0000) color for the mark, with a line width of 2 pixels and 10%
        // horizontal gap
        BoxWhiskerLayer markLayer = c.addBoxWhiskerLayer(null, null, null, null,
            markData, -1, 0xff0000);
        markLayer.setLineWidth(2);
        markLayer.setDataGap(0.1);

        // Add the legend key for the mark line
        legendBox.addKey("Target", 0xff0000, 2);

        // Tool tip for the mark layer
        markLayer.setHTMLImageMap("", "", "title='Target at {xLabel}: {med}'");

        // Add a blue (0066cc) bar layer using the given data.
        BarLayer barLayer = c.addBarLayer(barData, 0x0066cc, "Actual");

        // Use soft lighting effect for the bars with light direction from left.
        barLayer.setBorderColor(Chart.Transparent, Chart.softLighting(Chart.Left));

        // Tool tip for the bar layer
        barLayer.setHTMLImageMap("", "", "title='{dataSetName} at {xLabel}: {value}'"
            );

        // Adjust the plot area size, such that the bounding box (inclusive of axes)
        // is 10 pixels from the left edge, just below the title, 15 pixels from the
        // right edge, and 10 pixels above the legend box.
        c.packPlotArea(10, title.getHeight(), c.getWidth() - 15, c.layoutLegend(
            ).getTopY() - 10);

        // Output the chart
        viewer.setChart(c);

        // Include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new markbar();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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 Axis.syncAxis.

Source Code Listing

[JSP Version] jspdemo/pareto.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the chart
double[] data = {40, 15, 7, 5, 2};

// The labels for the chart
String[] labels = {"Hard Disk", "PCB", "Printer", "CDROM", "Keyboard"};

// In the pareto chart, the line data are just the accumulation of the raw data,
// scaled to a range of 0 - 100%
ArrayMath lineData = new ArrayMath(data);
lineData.acc();
double scaleFactor = lineData.max() / 100;
if (scaleFactor == 0) {
    // Avoid division by zero error for zero data
    scaleFactor = 1;
}
lineData.div2(scaleFactor);

// Create a XYChart object of size 480 x 300 pixels. Set background color to brushed
// silver, with a grey (bbbbbb) border and 2 pixel 3D raised effect. Use rounded
// corners. Enable soft drop shadow.
XYChart c = new XYChart(400, 300, Chart.brushedSilverColor(), 0xbbbbbb, 2);
c.setRoundedFrame();
c.setDropShadow();

// Add a title to the chart using 15 points Arial Italic. Set top/bottom margins to
// 12 pixels.
TextBox title = c.addTitle("Pareto Chart Demonstration", "Arial Italic", 15);
title.setMargin2(0, 0, 12, 12);

// Tentatively set the plotarea at (50, 40). Set the width to 100 pixels less than
// the chart width, and the height to 80 pixels less than the chart height. Use pale
// grey (f4f4f4) background, transparent border, and dark grey (444444) dotted grid
// lines.
c.setPlotArea(50, 40, c.getWidth() - 100, c.getHeight() - 80, 0xf4f4f4, -1,
    Chart.Transparent, c.dashLineColor(0x444444, Chart.DotLine));

// Add a line layer for the pareto line
LineLayer lineLayer = c.addLineLayer2();

// Add the pareto line using deep blue (0000ff) as the color, with circle symbols
lineLayer.addDataSet(lineData.result(), 0x0000ff).setDataSymbol(Chart.CircleShape, 9,
    0x0000ff, 0x0000ff);

// Set the line width to 2 pixel
lineLayer.setLineWidth(2);

// Bind the line layer to the secondary (right) y-axis.
lineLayer.setUseYAxis2();

// 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 barLayer = c.addBarLayer3(data);

// Set soft lighting for the bars with light direction from the right
barLayer.setBorderColor(Chart.Transparent, Chart.softLighting(Chart.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 secondary (right) y-axis scale as 0 - 100 with a tick every 20 units
c.yAxis2().setLinearScale(0, 100, 20);

// Set the format of the secondary (right) y-axis label to include a percentage sign
c.yAxis2().setLabelFormat("{value}%");

// Set the relationship between the two y-axes, which only differ by a scaling factor
c.yAxis().syncAxis(c.yAxis2(), scaleFactor);

// Set the format of the primary y-axis label foramt to show no decimal point
c.yAxis().setLabelFormat("{value|0}");

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

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

// Adjust the plot area size, such that the bounding box (inclusive of axes) is 10
// pixels from the left edge, just below the title, 10 pixels from the right edge,
// and 20 pixels from the bottom edge.
c.packPlotArea(10, title.getHeight(), c.getWidth() - 10, c.getHeight() - 20);

// Output the chart
String chart1URL = c.makeSession(request, "chart1", Chart.JPG);

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Pareto Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/pareto.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class pareto implements DemoModule
{
    //Name of demo program
    public String toString() { return "Pareto Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the chart
        double[] data = {40, 15, 7, 5, 2};

        // The labels for the chart
        String[] labels = {"Hard Disk", "PCB", "Printer", "CDROM", "Keyboard"};

        // In the pareto chart, the line data are just the accumulation of the raw
        // data, scaled to a range of 0 - 100%
        ArrayMath lineData = new ArrayMath(data);
        lineData.acc();
        double scaleFactor = lineData.max() / 100;
        if (scaleFactor == 0) {
            // Avoid division by zero error for zero data
            scaleFactor = 1;
        }
        lineData.div2(scaleFactor);

        // Create a XYChart object of size 480 x 300 pixels. Set background color to
        // brushed silver, with a grey (bbbbbb) border and 2 pixel 3D raised effect.
        // Use rounded corners. Enable soft drop shadow.
        XYChart c = new XYChart(400, 300, Chart.brushedSilverColor(), 0xbbbbbb, 2);
        c.setRoundedFrame();
        c.setDropShadow();

        // Add a title to the chart using 15 points Arial Italic. Set top/bottom
        // margins to 12 pixels.
        TextBox title = c.addTitle("Pareto Chart Demonstration", "Arial Italic", 15);
        title.setMargin2(0, 0, 12, 12);

        // Tentatively set the plotarea at (50, 40). Set the width to 100 pixels less
        // than the chart width, and the height to 80 pixels less than the chart
        // height. Use pale grey (f4f4f4) background, transparent border, and dark
        // grey (444444) dotted grid lines.
        c.setPlotArea(50, 40, c.getWidth() - 100, c.getHeight() - 80, 0xf4f4f4, -1,
            Chart.Transparent, c.dashLineColor(0x444444, Chart.DotLine));

        // Add a line layer for the pareto line
        LineLayer lineLayer = c.addLineLayer2();

        // Add the pareto line using deep blue (0000ff) as the color, with circle
        // symbols
        lineLayer.addDataSet(lineData.result(), 0x0000ff).setDataSymbol(
            Chart.CircleShape, 9, 0x0000ff, 0x0000ff);

        // Set the line width to 2 pixel
        lineLayer.setLineWidth(2);

        // Bind the line layer to the secondary (right) y-axis.
        lineLayer.setUseYAxis2();

        // 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 barLayer = c.addBarLayer3(data);

        // Set soft lighting for the bars with light direction from the right
        barLayer.setBorderColor(Chart.Transparent, Chart.softLighting(Chart.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 secondary (right) y-axis scale as 0 - 100 with a tick every 20
        // units
        c.yAxis2().setLinearScale(0, 100, 20);

        // Set the format of the secondary (right) y-axis label to include a
        // percentage sign
        c.yAxis2().setLabelFormat("{value}%");

        // Set the relationship between the two y-axes, which only differ by a
        // scaling factor
        c.yAxis().syncAxis(c.yAxis2(), scaleFactor);

        // Set the format of the primary y-axis label foramt to show no decimal point
        c.yAxis().setLabelFormat("{value|0}");

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

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

        // Adjust the plot area size, such that the bounding box (inclusive of axes)
        // is 10 pixels from the left edge, just below the title, 10 pixels from the
        // right edge, and 20 pixels from the bottom edge.
        c.packPlotArea(10, title.getHeight(), c.getWidth() - 10, c.getHeight() - 20);

        // Output the chart
        viewer.setChart(c);

        // Include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new pareto();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


Variable Width Bar Chart

Variable Width Bar Chart

This example demonstrates a bar chart with variable bar widths.

ChartDirector does not really have a bar layer for variable width bars. However, an area layer can be used to create the same effect.

The variable width bars in this example are actually 4 areas, created by 4 area layers. The data set for each area layer consists of 4 points for the 4 corners of a bar.

Source Code Listing

[JSP Version] jspdemo/varwidthbar.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the chart
double[] data = {800, 600, 1000, 1400};
double[] widths = {250, 500, 960, 460};
String[] labels = {"Wind", "Hydro", "Coal", "Natural Gas"};

// The colors to use
int[] colors = {0x00aa00, 0x66aaee, 0xee6622, 0xffbb00};

// Create a XYChart object of size 500 x 350 pixels
XYChart c = new XYChart(500, 350);

// Add a title to the chart using 15 pts Arial Italic font
c.addTitle("Energy Generation Breakdown", "Arial Italic", 15);

// Set the plotarea at (60, 60) and of (chart_width - 90) x (chart_height - 100) in
// size. Use a vertical gradient color from light blue (f9f9ff) to sky blue (aaccff)
// as background. Set grid lines to white (ffffff).
int plotAreaBgColor = c.linearGradientColor(0, 60, 0, c.getHeight() - 40, 0xaaccff,
    0xf9fcff);
c.setPlotArea(60, 60, c.getWidth() - 90, c.getHeight() - 100, plotAreaBgColor, -1,
    -1, 0xffffff);

// Add a legend box at (50, 30) using horizontal layout and transparent background.
c.addLegend(55, 30, false).setBackground(Chart.Transparent);

// Add titles to x/y axes with 10 points Arial Bold font
c.xAxis().setTitle("Mega Watts", "Arial Bold", 10);
c.yAxis().setTitle("Cost per MWh (dollars)", "Arial Bold", 10);

// Set the x axis rounding to false, so that the x-axis will fit the data exactly
c.xAxis().setRounding(false, false);

// In ChartDirector, there is no bar layer that can have variable bar widths, but you
// may create a bar using an area layer. (A bar can be considered as the area under a
// rectangular outline.) So by using a loop to create one bar per area layer, we can
// achieve a variable width bar chart.

// starting position of current bar
double currentX = 0;

for (int i = 0; i < data.length; ++i) {
    // ending position of current bar
    double nextX = currentX + widths[i];

    // outline of the bar
    double[] dataX = {currentX, currentX, nextX, nextX};
    double[] dataY = {0, data[i], data[i], 0};

    // create the area layer to fill the bar
    AreaLayer layer = c.addAreaLayer(dataY, colors[i], labels[i]);
    layer.setXData(dataX);

    // Tool tip for the layer
    layer.setHTMLImageMap("", "", "title='" + labels[i] + ": " + widths[i] +
        " MW at $" + data[i] + " per MWh'");

    // the ending position becomes the starting position of the next bar
    currentX = nextX;
}

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Variable Width Bar Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/varwidthbar.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class varwidthbar implements DemoModule
{
    //Name of demo program
    public String toString() { return "Variable Width Bar Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the chart
        double[] data = {800, 600, 1000, 1400};
        double[] widths = {250, 500, 960, 460};
        String[] labels = {"Wind", "Hydro", "Coal", "Natural Gas"};

        // The colors to use
        int[] colors = {0x00aa00, 0x66aaee, 0xee6622, 0xffbb00};

        // Create a XYChart object of size 500 x 350 pixels
        XYChart c = new XYChart(500, 350);

        // Add a title to the chart using 15 pts Arial Italic font
        c.addTitle("Energy Generation Breakdown", "Arial Italic", 15);

        // Set the plotarea at (60, 60) and of (chart_width - 90) x (chart_height -
        // 100) in size. Use a vertical gradient color from light blue (f9f9ff) to
        // sky blue (aaccff) as background. Set grid lines to white (ffffff).
        int plotAreaBgColor = c.linearGradientColor(0, 60, 0, c.getHeight() - 40,
            0xaaccff, 0xf9fcff);
        c.setPlotArea(60, 60, c.getWidth() - 90, c.getHeight() - 100,
            plotAreaBgColor, -1, -1, 0xffffff);

        // Add a legend box at (50, 30) using horizontal layout and transparent
        // background.
        c.addLegend(55, 30, false).setBackground(Chart.Transparent);

        // Add titles to x/y axes with 10 points Arial Bold font
        c.xAxis().setTitle("Mega Watts", "Arial Bold", 10);
        c.yAxis().setTitle("Cost per MWh (dollars)", "Arial Bold", 10);

        // Set the x axis rounding to false, so that the x-axis will fit the data
        // exactly
        c.xAxis().setRounding(false, false);

        // In ChartDirector, there is no bar layer that can have variable bar widths,
        // but you may create a bar using an area layer. (A bar can be considered as
        // the area under a rectangular outline.) So by using a loop to create one
        // bar per area layer, we can achieve a variable width bar chart.

        // starting position of current bar
        double currentX = 0;

        for (int i = 0; i < data.length; ++i) {
            // ending position of current bar
            double nextX = currentX + widths[i];

            // outline of the bar
            double[] dataX = {currentX, currentX, nextX, nextX};
            double[] dataY = {0, data[i], data[i], 0};

            // create the area layer to fill the bar
            AreaLayer layer = c.addAreaLayer(dataY, colors[i], labels[i]);
            layer.setXData(dataX);

            // Tool tip for the layer
            layer.setHTMLImageMap("", "", "title='" + labels[i] + ": " + widths[i] +
                " MW at $" + data[i] + " per MWh'");

            // the ending position becomes the starting position of the next bar
            currentX = nextX;
        }

        // Output the chart
        viewer.setChart(c);

        // Include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new varwidthbar();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


Bar Gap

Bar Gap

This example demonstrates the effects of different bar gaps configured using BarLayer.setBarGap.

Source Code Listing

[JSP Version] jspdemo/gapbar.jsp
<%@page import="ChartDirector.*" %>
<%@page import="javax.servlet.http.*" %>
<%!
// A simple structure to represent a chart image with an image map
private static class ImageWithHotSpot
{
    String imageURL;
    String imageMap;
}

// Function to create the demo charts
ImageWithHotSpot createChart(HttpServletRequest request, int index)
{
    double bargap = index * 0.25 - 0.25;

    // The data for the bar chart
    double[] data = {100, 125, 245, 147, 67};

    // The labels for the bar chart
    String[] labels = {"Mon", "Tue", "Wed", "Thu", "Fri"};

    // Create a XYChart object of size 150 x 150 pixels
    XYChart c = new 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 >= 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 = Chart.TouchBar;
    }

    // Add a bar chart layer using the given data and set the bar gap
    c.addBarLayer(data).setBarGap(bargap);

    // Output the chart
    ImageWithHotSpot ret = new ImageWithHotSpot();
    ret.imageURL = c.makeSession(request, "chart" + index);

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

    return ret;
}
%>
<%
ImageWithHotSpot chart0 = createChart(request, 0);
ImageWithHotSpot chart1 = createChart(request, 1);
ImageWithHotSpot chart2 = createChart(request, 2);
ImageWithHotSpot chart3 = createChart(request, 3);
ImageWithHotSpot chart4 = createChart(request, 4);
ImageWithHotSpot chart5 = createChart(request, 5);
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Bar Gap
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart0.imageURL)%>'
    usemap="#map0" border="0">
<map name="map0"><%=chart0.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1.imageURL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=chart1.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart2.imageURL)%>'
    usemap="#map2" border="0">
<map name="map2"><%=chart2.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart3.imageURL)%>'
    usemap="#map3" border="0">
<map name="map3"><%=chart3.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart4.imageURL)%>'
    usemap="#map4" border="0">
<map name="map4"><%=chart4.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart5.imageURL)%>'
    usemap="#map5" border="0">
<map name="map5"><%=chart5.imageMap%></map>
</body>
</html>

[Java Version] javademo/gapbar.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class gapbar implements DemoModule
{
    //Name of demo program
    public String toString() { return "Bar Gap"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 6; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        double bargap = index * 0.25 - 0.25;

        // The data for the bar chart
        double[] data = {100, 125, 245, 147, 67};

        // The labels for the bar chart
        String[] labels = {"Mon", "Tue", "Wed", "Thu", "Fri"};

        // Create a XYChart object of size 150 x 150 pixels
        XYChart c = new 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 >= 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 = Chart.TouchBar;
        }

        // Add a bar chart layer using the given data and set the bar gap
        c.addBarLayer(data).setBarGap(bargap);

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='Production on {xLabel}: {value} kg'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new gapbar();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);
        frame.getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
        frame.setSize(800, 450);

        // Create the charts and put them in the content pane
        for (int i = 0; i < demo.getNoOfCharts(); ++i)
        {
            ChartViewer viewer = new ChartViewer();
            demo.createChart(viewer, i);
            frame.getContentPane().add(viewer);
        }

        // Display the window
        frame.setVisible(true);
    }
}


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.
Missing Data Points | Demonstrates various methods to representing missing data points. Also demonstrates automatic resizing of the plot area to fit the chart.
Uneven Data Points | Demonstrates data series that are unevenly spaced in the x dimension.
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.
Inter-Line Coloring | Demonstrates filling the area between two lines or curves.
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 unevenly spaced data points on an auto-scaled true date/time axis, and automatic resizing of the plot area to fit the chart.
Binary Data Series | Demonstrates a chart representing binary data series.
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.


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 (JSP version) or BaseChart.makeImage (Java version).

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

Source Code Listing

[JSP Version] jspdemo/simpleline.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the line chart
double[] data = {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
String[] labels = {"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
XYChart c = new 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
String chart1URL = c.makeSession(request, "chart1");

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='Hour {xLabel}: Traffic {value} GBytes'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Simple Line Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/simpleline.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class simpleline implements DemoModule
{
    //Name of demo program
    public String toString() { return "Simple Line Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the line chart
        double[] data = {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
        String[] labels = {"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
        XYChart c = new 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
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='Hour {xLabel}: Traffic {value} GBytes'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new simpleline();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/compactline.jsp
<%@page import="ChartDirector.*" %>
<%
//
//    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)
//
int 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 rantable = new 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
double[] data = rantable.getCol(0);

// The x-axis labels for the chart
String[] labels = {"-", "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)
XYChart c = new 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(Chart.Top, "STAR TECH INDEX  2003-01-28", "Arial", 7.5, 0xffffff,
    0x31319c);
c.addTitle2(Chart.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(Chart.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
String chart1URL = c.makeSession(request, "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.
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{={x}*240+9.5*3600|h:nna}: {value|2}'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Compact Line Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/compactline.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class compactline implements DemoModule
{
    //Name of demo program
    public String toString() { return "Compact Line Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        //
        //    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)
        //
        int 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 rantable = new 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
        double[] data = rantable.getCol(0);

        // The x-axis labels for the chart
        String[] labels = {"-", "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)
        XYChart c = new 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(Chart.Top, "STAR TECH INDEX  2003-01-28", "Arial", 7.5, 0xffffff,
            0x31319c);
        c.addTitle2(Chart.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(Chart.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
        viewer.setChart(c);

        // 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.
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='{={x}*240+9.5*3600|h:nna}: {value|2}'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new compactline();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


3D Line Chart

3D Line Chart

This example demonstrates setting the line to 3D by using Layer.set3D.

Source Code Listing

[JSP Version] jspdemo/threedline.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the line chart
double[] data = {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
String[] labels = {"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
XYChart c = new 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
String chart1URL = c.makeSession(request, "chart1");

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "", "title='Hour {xLabel}: {value} MBytes'")
    ;
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    3D Line Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/threedline.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class threedline implements DemoModule
{
    //Name of demo program
    public String toString() { return "3D Line Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the line chart
        double[] data = {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
        String[] labels = {"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
        XYChart c = new 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
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='Hour {xLabel}: {value} MBytes'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new threedline();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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 Chart.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

[JSP Version] jspdemo/multiline.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the line chart
double[] data0 = {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};
double[] data1 = {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};
double[] data2 = {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
String[] labels = {"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
XYChart c = new 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(Chart.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, Chart.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
LineLayer 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, Chart.DashLine), "Server #3");

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='[{dataSetName}] Hour {xLabel}: {value} MBytes'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Multi-Line Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/multiline.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class multiline implements DemoModule
{
    //Name of demo program
    public String toString() { return "Multi-Line Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the line chart
        double[] data0 = {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};
        double[] data1 = {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};
        double[] data2 = {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
        String[] labels = {"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
        XYChart c = new 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(Chart.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, Chart.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
        LineLayer 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, Chart.DashLine),
            "Server #3");

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='[{dataSetName}] Hour {xLabel}: {value} MBytes'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new multiline();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/symbolline.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the line chart
double[] data0 = {60.2, 51.7, 81.3, 48.6, 56.2, 68.9, 52.8};
double[] data1 = {30.0, 32.7, 33.9, 29.5, 32.2, 28.4, 29.8};
String[] labels = {"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.
XYChart c = new 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(Chart.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(new int[]{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
LineLayer layer = c.addLineLayer();

// Add the first line. Plot the points with a 7 pixel square symbol
layer.addDataSet(data0, 0xcf4040, "Peak").setDataSymbol(Chart.SquareSymbol, 7);

// Add the second line. Plot the points with a 9 pixel dismond symbol
layer.addDataSet(data1, 0x40cf40, "Average").setDataSymbol(Chart.DiamondSymbol, 9);

// Enable data label on the data points. Set the label format to nn%.
layer.setDataLabelFormat("{value|0}%");

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{xLabel}: {dataSetName} {value}%'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Symbol Line Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/symbolline.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class symbolline implements DemoModule
{
    //Name of demo program
    public String toString() { return "Symbol Line Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the line chart
        double[] data0 = {60.2, 51.7, 81.3, 48.6, 56.2, 68.9, 52.8};
        double[] data1 = {30.0, 32.7, 33.9, 29.5, 32.2, 28.4, 29.8};
        String[] labels = {"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.
        XYChart c = new 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(Chart.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(new int[]{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
        LineLayer layer = c.addLineLayer();

        // Add the first line. Plot the points with a 7 pixel square symbol
        layer.addDataSet(data0, 0xcf4040, "Peak").setDataSymbol(Chart.SquareSymbol, 7
            );

        // Add the second line. Plot the points with a 9 pixel dismond symbol
        layer.addDataSet(data1, 0x40cf40, "Average").setDataSymbol(
            Chart.DiamondSymbol, 9);

        // Enable data label on the data points. Set the label format to nn%.
        layer.setDataLabelFormat("{value|0}%");

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='{xLabel}: {dataSetName} {value}%'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new symbolline();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/symbolline2.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the line chart
double[] data0 = {42, 49, 33, 38, 64, 56, 29, 41, 44, 57, 59, 42};
double[] data1 = {65, 75, 47, 34, 42, 49, 73, 62, 90, 69, 66, 78};
double[] data2 = {36, 28, 25, 28, 38, 20, 22, 30, 25, 33, 30, 24};
String[] labels = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
    "Oct", "Nov", "Dec"};

// Create a XYChart object of size 600 x 375 pixels
XYChart c = new 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, Chart.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(Chart.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 USD millions", "Arial Bold Italic", 10);

// Add a line layer to the chart
LineLayer 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(
    Chart.CircleSymbol, 9);
layer.addDataSet(data1, 0x00ff00, "Atom Synthesizer").setDataSymbol(
    Chart.DiamondSymbol, 11);
layer.addDataSet(data2, 0xff6600, "Proton Cannon").setDataSymbol(Chart.Cross2Shape(),
    11);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='Revenue of {dataSetName} in {xLabel}: US$ {value}M'");
%>
<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 color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/symbolline2.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class symbolline2 implements DemoModule
{
    //Name of demo program
    public String toString() { return "Symbol Line Chart (2)"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the line chart
        double[] data0 = {42, 49, 33, 38, 64, 56, 29, 41, 44, 57, 59, 42};
        double[] data1 = {65, 75, 47, 34, 42, 49, 73, 62, 90, 69, 66, 78};
        double[] data2 = {36, 28, 25, 28, 38, 20, 22, 30, 25, 33, 30, 24};
        String[] labels = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
            "Sep", "Oct", "Nov", "Dec"};

        // Create a XYChart object of size 600 x 375 pixels
        XYChart c = new 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, Chart.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(Chart.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 USD millions", "Arial Bold Italic", 10);

        // Add a line layer to the chart
        LineLayer 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(
            Chart.CircleSymbol, 9);
        layer.addDataSet(data1, 0x00ff00, "Atom Synthesizer").setDataSymbol(
            Chart.DiamondSymbol, 11);
        layer.addDataSet(data2, 0xff6600, "Proton Cannon").setDataSymbol(
            Chart.Cross2Shape(), 11);

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='Revenue of {dataSetName} in {xLabel}: US$ {value}M'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new symbolline2();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


Missing Data Points

Missing Data Points

This example demonstrates various methods to representing missing data points. It also demonstrates automatic resizing of the plot area to fit the chart.

In ChartDirector, a data series may contain missing values, represented using the NoValue predefined constant. In a line layer, by default, a missing value is represented as a gap in the line. In other words, the line will be broken. LineLayer.setGapColor can be used to configure the line layer to join through the NoValue point instead, using a line segment that can be of a different color and/or style.

In this example, the three data series all contain NoValue points. The red line demonstrates the default behaviour of using a gap to representing the NoValue point. The green line demonstrates joining through the NoValue point with a dash line. The orange line demonstrates joining through the NoValue point with the same line style as for joining normal data points.

After the entire chart is configured, the XYChart.packPlotArea method is used to adjust the plot area size, so as to fit the plot area and the axes in a given bounding box.

Source Code Listing

[JSP Version] jspdemo/missingpoints.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the chart
double[] data0 = {42, 49, Chart.NoValue, 38, 64, 56, 29, 41, 44, 57};
double[] data1 = {65, 75, 47, 34, 42, 49, 73, Chart.NoValue, 90, 69, 66, 78};
double[] data2 = {Chart.NoValue, Chart.NoValue, 25, 28, 38, 20, 22, Chart.NoValue,
    25, 33, 30, 24};
String[] labels = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
    "Oct", "Nov", "Dec"};

// Create a XYChart object of size 600 x 360 pixels. Set background color to brushed
// silver, with a 2 pixel 3D border. Use rounded corners.
XYChart c = new XYChart(600, 360, Chart.brushedSilverColor(), Chart.Transparent, 2);
c.setRoundedFrame();

// Add a title using 18 pts Times New Roman Bold Italic font. #Set top/bottom margins
// to 6 pixels.
TextBox title = c.addTitle("Product Line Global Revenue",
    "Times New Roman Bold Italic", 18);
title.setMargin2(0, 0, 6, 6);

// Add a separator line just under the title
c.addLine(10, title.getHeight(), c.getWidth() - 11, title.getHeight(),
    Chart.LineColor);

// Add a legend box where the top-center is anchored to the horizontal center of the
// chart, just under the title. Use horizontal layout and 10 points Arial Bold font,
// and transparent background and border.
LegendBox legendBox = c.addLegend(c.getWidth() / 2, title.getHeight(), false,
    "Arial Bold", 10);
legendBox.setAlignment(Chart.TopCenter);
legendBox.setBackground(Chart.Transparent, Chart.Transparent);

// Tentatively set the plotarea at (70, 75) and of 460 x 240 pixels in size. Use
// transparent border and black (000000) grid lines
c.setPlotArea(70, 75, 460, 240, -1, -1, Chart.Transparent, 0x000000, -1);

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

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

// 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 all axes to transparent
c.xAxis().setColors(Chart.Transparent);
c.yAxis().setColors(Chart.Transparent);
c.yAxis2().setColors(Chart.Transparent);

// Set the x-axis margins to 15 pixels, so that the horizontal grid lines can extend
// beyond the leftmost and rightmost vertical grid lines
c.xAxis().setMargin(15, 15);

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

// Add axis title using 10pts Arial Bold Italic font
c.yAxis().setTitle("Revenue in USD millions", "Arial Bold Italic", 10);
c.yAxis2().setTitle("Revenue in USD millions", "Arial Bold Italic", 10);

// Add the first line. The missing data will be represented as gaps in the line (the
// default behaviour)
LineLayer layer0 = c.addLineLayer2();
layer0.addDataSet(data0, 0xff0000, "Quantum Computer").setDataSymbol(
    Chart.GlassSphere2Shape, 11);
layer0.setLineWidth(3);

// Add the second line. The missing data will be represented by using dash lines to
// bridge the gap
LineLayer layer1 = c.addLineLayer2();
layer1.addDataSet(data1, 0x00ff00, "Atom Synthesizer").setDataSymbol(
    Chart.GlassSphere2Shape, 11);
layer1.setLineWidth(3);
layer1.setGapColor(c.dashLineColor(0x00ff00));

// Add the third line. The missing data will be ignored - just join the gap with the
// original line style.
LineLayer layer2 = c.addLineLayer2();
layer2.addDataSet(data2, 0xff6600, "Proton Cannon").setDataSymbol(
    Chart.GlassSphere2Shape, 11);
layer2.setLineWidth(3);
layer2.setGapColor(Chart.SameAsMainColor);

// layout the legend so we can get the height of the legend box
c.layoutLegend();

// Adjust the plot area size, such that the bounding box (inclusive of axes) is 15
// pixels from the left edge, just under the legend box, 16 pixels from the right
// edge, and 25 pixels from the bottom edge.
c.packPlotArea(15, legendBox.getTopY() + legendBox.getHeight(), c.getWidth() - 16,
    c.getHeight() - 25);

// Output the chart
String chart1URL = c.makeSession(request, "chart1", Chart.JPG);

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='Revenue of {dataSetName} in {xLabel}: US$ {value}M'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Missing Data Points
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/missingpoints.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class missingpoints implements DemoModule
{
    //Name of demo program
    public String toString() { return "Missing Data Points"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the chart
        double[] data0 = {42, 49, Chart.NoValue, 38, 64, 56, 29, 41, 44, 57};
        double[] data1 = {65, 75, 47, 34, 42, 49, 73, Chart.NoValue, 90, 69, 66, 78};
        double[] data2 = {Chart.NoValue, Chart.NoValue, 25, 28, 38, 20, 22,
            Chart.NoValue, 25, 33, 30, 24};
        String[] labels = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
            "Sep", "Oct", "Nov", "Dec"};

        // Create a XYChart object of size 600 x 360 pixels. Set background color to
        // brushed silver, with a 2 pixel 3D border. Use rounded corners.
        XYChart c = new XYChart(600, 360, Chart.brushedSilverColor(),
            Chart.Transparent, 2);
        c.setRoundedFrame();

        // Add a title using 18 pts Times New Roman Bold Italic font. #Set top/bottom
        // margins to 6 pixels.
        TextBox title = c.addTitle("Product Line Global Revenue",
            "Times New Roman Bold Italic", 18);
        title.setMargin2(0, 0, 6, 6);

        // Add a separator line just under the title
        c.addLine(10, title.getHeight(), c.getWidth() - 11, title.getHeight(),
            Chart.LineColor);

        // Add a legend box where the top-center is anchored to the horizontal center
        // of the chart, just under the title. Use horizontal layout and 10 points
        // Arial Bold font, and transparent background and border.
        LegendBox legendBox = c.addLegend(c.getWidth() / 2, title.getHeight(), false,
            "Arial Bold", 10);
        legendBox.setAlignment(Chart.TopCenter);
        legendBox.setBackground(Chart.Transparent, Chart.Transparent);

        // Tentatively set the plotarea at (70, 75) and of 460 x 240 pixels in size.
        // Use transparent border and black (000000) grid lines
        c.setPlotArea(70, 75, 460, 240, -1, -1, Chart.Transparent, 0x000000, -1);

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

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

        // 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 all axes to transparent
        c.xAxis().setColors(Chart.Transparent);
        c.yAxis().setColors(Chart.Transparent);
        c.yAxis2().setColors(Chart.Transparent);

        // Set the x-axis margins to 15 pixels, so that the horizontal grid lines can
        // extend beyond the leftmost and rightmost vertical grid lines
        c.xAxis().setMargin(15, 15);

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

        // Add axis title using 10pts Arial Bold Italic font
        c.yAxis().setTitle("Revenue in USD millions", "Arial Bold Italic", 10);
        c.yAxis2().setTitle("Revenue in USD millions", "Arial Bold Italic", 10);

        // Add the first line. The missing data will be represented as gaps in the
        // line (the default behaviour)
        LineLayer layer0 = c.addLineLayer2();
        layer0.addDataSet(data0, 0xff0000, "Quantum Computer").setDataSymbol(
            Chart.GlassSphere2Shape, 11);
        layer0.setLineWidth(3);

        // Add the second line. The missing data will be represented by using dash
        // lines to bridge the gap
        LineLayer layer1 = c.addLineLayer2();
        layer1.addDataSet(data1, 0x00ff00, "Atom Synthesizer").setDataSymbol(
            Chart.GlassSphere2Shape, 11);
        layer1.setLineWidth(3);
        layer1.setGapColor(c.dashLineColor(0x00ff00));

        // Add the third line. The missing data will be ignored - just join the gap
        // with the original line style.
        LineLayer layer2 = c.addLineLayer2();
        layer2.addDataSet(data2, 0xff6600, "Proton Cannon").setDataSymbol(
            Chart.GlassSphere2Shape, 11);
        layer2.setLineWidth(3);
        layer2.setGapColor(Chart.SameAsMainColor);

        // layout the legend so we can get the height of the legend box
        c.layoutLegend();

        // Adjust the plot area size, such that the bounding box (inclusive of axes)
        // is 15 pixels from the left edge, just under the legend box, 16 pixels from
        // the right edge, and 25 pixels from the bottom edge.
        c.packPlotArea(15, legendBox.getTopY() + legendBox.getHeight(), c.getWidth()
             - 16, c.getHeight() - 25);

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='Revenue of {dataSetName} in {xLabel}: US$ {value}M'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new missingpoints();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


Uneven Data Points

Uneven Data Points

This example demonstrates data series that are unevenly spaced in the x dimension.

In ChartDirector, it is only necessarily to provide the y coordinates (the data values) to plot a line. The x coordinates are optional. If no x coordinates are provided, the data points are assumed to be evenly spaced on the x dimension. In such case, the x-axis can be used to label the data points, with the labels configured using Axis.setLabels or Axis.setLabels2. The labels are only for human reading and will not affect the positioning of the data points.

On the other hand, if the data points are unevenly spaced, or if there are multiple data series with different spacing in the x dimension, it is necessary to provide the x coordinates of the data series. They can be provided using Layer.setXData or Layer.setXData2. In such case, the x-axis can be automatically scaled, with labels generated by ChartDirector. Alternatively, Axis.setLinearScale, Axis.setLogScale, Axis.setDateScale, etc., can be used to explicitly set a scale of the x-axis. Axis.setLabels or Axis.setLabels2 should not be used for charts that use real x coordinates.

In this example, the red line has unevenly spaced x coordinates, set using Layer.setXData. Both the green line and the orange line has evenly spaced x coordinates, but the spacing in the x dimension differs between the lines. Their x coordinates are set using Layer.setXData2. Note that the lines start and end at different x coordinates, and they do not need to span the entire x-axis range. The x-axis in this example is automatically scaled.

Source Code Listing

[JSP Version] jspdemo/unevenpoints.jsp
<%@page import="ChartDirector.*" %>
<%@page import="java.util.*" %>
<%
// Data points which more unevenly spaced in time
double[] data0Y = {62, 69, 53, 58, 84, 76, 49, 61, 64, 77, 79};
Date[] data0X = {new GregorianCalendar(2007, 0, 1).getTime(), new GregorianCalendar(
    2007, 0, 2).getTime(), new GregorianCalendar(2007, 0, 5).getTime(),
    new GregorianCalendar(2007, 0, 7).getTime(), new GregorianCalendar(2007, 0, 10
    ).getTime(), new GregorianCalendar(2007, 0, 14).getTime(), new GregorianCalendar(
    2007, 0, 17).getTime(), new GregorianCalendar(2007, 0, 18).getTime(),
    new GregorianCalendar(2007, 0, 19).getTime(), new GregorianCalendar(2007, 0, 20
    ).getTime(), new GregorianCalendar(2007, 0, 21).getTime()};

// Data points which are evenly spaced in a certain time range
double[] data1Y = {36, 25, 28, 38, 20, 30, 27, 35, 65, 60, 40, 73, 62, 90, 75, 72};
Date data1Start = new GregorianCalendar(2007, 0, 1).getTime();
Date data1End = new GregorianCalendar(2007, 0, 16).getTime();

// Data points which are evenly spaced in another time range, in which the spacing is
// different from the above series
double[] data2Y = {25, 15, 30, 23, 32, 55, 45};
Date data2Start = new GregorianCalendar(2007, 0, 9).getTime();
Date data2End = new GregorianCalendar(2007, 0, 21).getTime();

// Create a XYChart object of size 600 x 400 pixels. Use a vertical gradient color
// from light blue (99ccff) to white (ffffff) spanning the top 100 pixels as
// background. Set border to grey (888888). Use rounded corners. Enable soft drop
// shadow.
XYChart c = new XYChart(600, 400);
c.setBackground(c.linearGradientColor(0, 0, 0, 100, 0x99ccff, 0xffffff), 0x888888);
c.setRoundedFrame();
c.setDropShadow();

// Add a title using 18 pts Times New Roman Bold Italic font. Set top margin to 16
// pixels.
c.addTitle("Product Line Order Backlog", "Times New Roman Bold Italic", 18
    ).setMargin2(0, 0, 16, 0);

// Set the plotarea at (60, 80) and of 510 x 275 pixels in size. Use transparent
// border and dark grey (444444) dotted grid lines
PlotArea plotArea = c.setPlotArea(60, 80, 510, 275, -1, -1, Chart.Transparent,
    c.dashLineColor(0x444444, 0x0101), -1);

// Add a legend box where the top-center is anchored to the horizontal center of the
// plot area at y = 45. Use horizontal layout and 10 points Arial Bold font, and
// transparent background and border.
LegendBox legendBox = c.addLegend(plotArea.getLeftX() + plotArea.getWidth() / 2, 45,
    false, "Arial Bold", 10);
legendBox.setAlignment(Chart.TopCenter);
legendBox.setBackground(Chart.Transparent, Chart.Transparent);

// Set x-axis tick density to 75 pixels and y-axis tick density to 30 pixels.
// ChartDirector auto-scaling will use this as the guidelines when putting ticks on
// the x-axis and y-axis.
c.yAxis().setTickDensity(30);
c.xAxis().setTickDensity(75);

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

// Set the x-axis margins to 15 pixels, so that the horizontal grid lines can extend
// beyond the leftmost and rightmost vertical grid lines
c.xAxis().setMargin(15, 15);

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

// Add axis title using 10pts Arial Bold Italic font
c.yAxis().setTitle("Backlog in USD millions", "Arial Bold Italic", 10);

// Add the first data series
LineLayer layer0 = c.addLineLayer2();
layer0.addDataSet(data0Y, 0xff0000, "Quantum Computer").setDataSymbol(
    Chart.GlassSphere2Shape, 11);
layer0.setXData(data0X);
layer0.setLineWidth(3);

// Add the second data series
LineLayer layer1 = c.addLineLayer2();
layer1.addDataSet(data1Y, 0x00ff00, "Atom Synthesizer").setDataSymbol(
    Chart.GlassSphere2Shape, 11);
layer1.setXData2(data1Start, data1End);
layer1.setLineWidth(3);

// Add the third data series
LineLayer layer2 = c.addLineLayer2();
layer2.addDataSet(data2Y, 0xff6600, "Proton Cannon").setDataSymbol(
    Chart.GlassSphere2Shape, 11);
layer2.setXData2(data2Start, data2End);
layer2.setLineWidth(3);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='Backlog of {dataSetName} at {x|mm/dd/yyyy}: US$ {value}M'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Uneven Data Points
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/unevenpoints.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import ChartDirector.*;

public class unevenpoints implements DemoModule
{
    //Name of demo program
    public String toString() { return "Uneven Data Points "; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // Data points which more unevenly spaced in time
        double[] data0Y = {62, 69, 53, 58, 84, 76, 49, 61, 64, 77, 79};
        Date[] data0X = {new GregorianCalendar(2007, 0, 1).getTime(),
            new GregorianCalendar(2007, 0, 2).getTime(), new GregorianCalendar(2007,
            0, 5).getTime(), new GregorianCalendar(2007, 0, 7).getTime(),
            new GregorianCalendar(2007, 0, 10).getTime(), new GregorianCalendar(2007,
            0, 14).getTime(), new GregorianCalendar(2007, 0, 17).getTime(),
            new GregorianCalendar(2007, 0, 18).getTime(), new GregorianCalendar(2007,
            0, 19).getTime(), new GregorianCalendar(2007, 0, 20).getTime(),
            new GregorianCalendar(2007, 0, 21).getTime()};

        // Data points which are evenly spaced in a certain time range
        double[] data1Y = {36, 25, 28, 38, 20, 30, 27, 35, 65, 60, 40, 73, 62, 90,
            75, 72};
        Date data1Start = new GregorianCalendar(2007, 0, 1).getTime();
        Date data1End = new GregorianCalendar(2007, 0, 16).getTime();

        // Data points which are evenly spaced in another time range, in which the
        // spacing is different from the above series
        double[] data2Y = {25, 15, 30, 23, 32, 55, 45};
        Date data2Start = new GregorianCalendar(2007, 0, 9).getTime();
        Date data2End = new GregorianCalendar(2007, 0, 21).getTime();

        // Create a XYChart object of size 600 x 400 pixels. Use a vertical gradient
        // color from light blue (99ccff) to white (ffffff) spanning the top 100
        // pixels as background. Set border to grey (888888). Use rounded corners.
        // Enable soft drop shadow.
        XYChart c = new XYChart(600, 400);
        c.setBackground(c.linearGradientColor(0, 0, 0, 100, 0x99ccff, 0xffffff),
            0x888888);
        c.setRoundedFrame();
        c.setDropShadow();

        // Add a title using 18 pts Times New Roman Bold Italic font. Set top margin
        // to 16 pixels.
        c.addTitle("Product Line Order Backlog", "Times New Roman Bold Italic", 18
            ).setMargin2(0, 0, 16, 0);

        // Set the plotarea at (60, 80) and of 510 x 275 pixels in size. Use
        // transparent border and dark grey (444444) dotted grid lines
        PlotArea plotArea = c.setPlotArea(60, 80, 510, 275, -1, -1,
            Chart.Transparent, c.dashLineColor(0x444444, 0x0101), -1);

        // Add a legend box where the top-center is anchored to the horizontal center
        // of the plot area at y = 45. Use horizontal layout and 10 points Arial Bold
        // font, and transparent background and border.
        LegendBox legendBox = c.addLegend(plotArea.getLeftX() + plotArea.getWidth() /
            2, 45, false, "Arial Bold", 10);
        legendBox.setAlignment(Chart.TopCenter);
        legendBox.setBackground(Chart.Transparent, Chart.Transparent);

        // Set x-axis tick density to 75 pixels and y-axis tick density to 30 pixels.
        // ChartDirector auto-scaling will use this as the guidelines when putting
        // ticks on the x-axis and y-axis.
        c.yAxis().setTickDensity(30);
        c.xAxis().setTickDensity(75);

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

        // Set the x-axis margins to 15 pixels, so that the horizontal grid lines can
        // extend beyond the leftmost and rightmost vertical grid lines
        c.xAxis().setMargin(15, 15);

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

        // Add axis title using 10pts Arial Bold Italic font
        c.yAxis().setTitle("Backlog in USD millions", "Arial Bold Italic", 10);

        // Add the first data series
        LineLayer layer0 = c.addLineLayer2();
        layer0.addDataSet(data0Y, 0xff0000, "Quantum Computer").setDataSymbol(
            Chart.GlassSphere2Shape, 11);
        layer0.setXData(data0X);
        layer0.setLineWidth(3);

        // Add the second data series
        LineLayer layer1 = c.addLineLayer2();
        layer1.addDataSet(data1Y, 0x00ff00, "Atom Synthesizer").setDataSymbol(
            Chart.GlassSphere2Shape, 11);
        layer1.setXData2(data1Start, data1End);
        layer1.setLineWidth(3);

        // Add the third data series
        LineLayer layer2 = c.addLineLayer2();
        layer2.addDataSet(data2Y, 0xff6600, "Proton Cannon").setDataSymbol(
            Chart.GlassSphere2Shape, 11);
        layer2.setXData2(data2Start, data2End);
        layer2.setLineWidth(3);

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='Backlog of {dataSetName} at {x|mm/dd/yyyy}: US$ {value}M'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new unevenpoints();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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 Chart.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

[JSP Version] jspdemo/splineline.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the chart
double[] data0 = {32, 39, 23, 28, 41, 38, 26, 35, 29};
double[] data1 = {50, 55, 47, 34, 47, 53, 38, 40, 51};

// The labels for the chart
String[] labels = {"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.
XYChart c = new XYChart(600, 300, 0xffdddd, 0x000000, 1);
c.setRoundedFrame();

//Set search path to current JSP directory for loading icon images
c.setSearchPath(getServletConfig().getServletContext(), request);

// 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(Chart.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, Chart.softLighting(Chart.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
SplineLayer 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(Chart.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(Chart.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\nEngineering<*/*>"
    ).setAlignment(Chart.BottomRight);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName} at t = {xLabel} hour: {value} KJ/liter'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Spline Line Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/splineline.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class splineline implements DemoModule
{
    //Name of demo program
    public String toString() { return "Spline Line Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the chart
        double[] data0 = {32, 39, 23, 28, 41, 38, 26, 35, 29};
        double[] data1 = {50, 55, 47, 34, 47, 53, 38, 40, 51};

        // The labels for the chart
        String[] labels = {"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.
        XYChart c = new XYChart(600, 300, 0xffdddd, 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, 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(Chart.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,
            Chart.softLighting(Chart.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
        SplineLayer 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(
            Chart.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(
            Chart.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\n" +
            "Engineering<*/*>").setAlignment(Chart.BottomRight);

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='{dataSetName} at t = {xLabel} hour: {value} KJ/liter'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new splineline();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/stepline.jsp
<%@page import="ChartDirector.*" %>
<%@page import="java.util.*" %>
<%
// The data for the chart
double[] dataY0 = {4, 4.5, 5, 5.25, 5.75, 5.25, 5, 4.5, 4, 3, 2.5, 2.5};
Date[] dataX0 = {new GregorianCalendar(1997, 0, 1).getTime(), new GregorianCalendar(
    1998, 5, 25).getTime(), new GregorianCalendar(1999, 8, 6).getTime(),
    new GregorianCalendar(2000, 1, 6).getTime(), new GregorianCalendar(2000, 8, 21
    ).getTime(), new GregorianCalendar(2001, 2, 4).getTime(), new GregorianCalendar(
    2001, 5, 8).getTime(), new GregorianCalendar(2002, 1, 4).getTime(),
    new GregorianCalendar(2002, 4, 19).getTime(), new GregorianCalendar(2002, 7, 16
    ).getTime(), new GregorianCalendar(2002, 11, 1).getTime(), new GregorianCalendar(
    2003, 0, 1).getTime()};

double[] dataY1 = {7, 6.5, 6, 5, 6.5, 7, 6, 5.5, 5, 4, 3.5, 3.5};
Date[] dataX1 = {new GregorianCalendar(1997, 0, 1).getTime(), new GregorianCalendar(
    1997, 6, 1).getTime(), new GregorianCalendar(1997, 11, 1).getTime(),
    new GregorianCalendar(1999, 0, 15).getTime(), new GregorianCalendar(1999, 5, 9
    ).getTime(), new GregorianCalendar(2000, 2, 3).getTime(), new GregorianCalendar(
    2000, 7, 13).getTime(), new GregorianCalendar(2001, 4, 5).getTime(),
    new GregorianCalendar(2001, 8, 16).getTime(), new GregorianCalendar(2002, 2, 16
    ).getTime(), new GregorianCalendar(2002, 5, 1).getTime(), new GregorianCalendar(
    2003, 0, 1).getTime()};

// 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
XYChart c = new 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(Chart.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, Chart.softLighting(Chart.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
StepLineLayer 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
StepLineLayer layer1 = c.addStepLineLayer(dataY1, 0x0000ff, "Country BBB");
layer1.setXData(dataX1);
layer1.setLineWidth(2);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName} change to {value}% on {x|mmm dd, yyyy}'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Step Line Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/stepline.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import ChartDirector.*;

public class stepline implements DemoModule
{
    //Name of demo program
    public String toString() { return "Step Line Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the chart
        double[] dataY0 = {4, 4.5, 5, 5.25, 5.75, 5.25, 5, 4.5, 4, 3, 2.5, 2.5};
        Date[] dataX0 = {new GregorianCalendar(1997, 0, 1).getTime(),
            new GregorianCalendar(1998, 5, 25).getTime(), new GregorianCalendar(1999,
            8, 6).getTime(), new GregorianCalendar(2000, 1, 6).getTime(),
            new GregorianCalendar(2000, 8, 21).getTime(), new GregorianCalendar(2001,
            2, 4).getTime(), new GregorianCalendar(2001, 5, 8).getTime(),
            new GregorianCalendar(2002, 1, 4).getTime(), new GregorianCalendar(2002,
            4, 19).getTime(), new GregorianCalendar(2002, 7, 16).getTime(),
            new GregorianCalendar(2002, 11, 1).getTime(), new GregorianCalendar(2003,
            0, 1).getTime()};

        double[] dataY1 = {7, 6.5, 6, 5, 6.5, 7, 6, 5.5, 5, 4, 3.5, 3.5};
        Date[] dataX1 = {new GregorianCalendar(1997, 0, 1).getTime(),
            new GregorianCalendar(1997, 6, 1).getTime(), new GregorianCalendar(1997,
            11, 1).getTime(), new GregorianCalendar(1999, 0, 15).getTime(),
            new GregorianCalendar(1999, 5, 9).getTime(), new GregorianCalendar(2000,
            2, 3).getTime(), new GregorianCalendar(2000, 7, 13).getTime(),
            new GregorianCalendar(2001, 4, 5).getTime(), new GregorianCalendar(2001,
            8, 16).getTime(), new GregorianCalendar(2002, 2, 16).getTime(),
            new GregorianCalendar(2002, 5, 1).getTime(), new GregorianCalendar(2003,
            0, 1).getTime()};

        // 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
        XYChart c = new 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(Chart.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, Chart.softLighting(Chart.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
        StepLineLayer 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
        StepLineLayer layer1 = c.addStepLineLayer(dataY1, 0x0000ff, "Country BBB");
        layer1.setXData(dataX1);
        layer1.setLineWidth(2);

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='{dataSetName} change to {value}% on {x|mmm dd, yyyy}'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new stepline();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


Inter-Line Coloring

Inter-Line Coloring

This example demonstrates filling the area between two lines or curves.

In ChartDirector, an InterLineLayer can be used to fill the region between any two lines. The lines can be from a LineLayer, StepLineLayer, SplineLayer, TrendLayer, or from an axis Mark. Two colors can be used for filling, depending on which line is on top.

In this example, an InterLineLayer is used to fill the region between a normal line and a spline curve. Another InterLineLayer is used to fill the region between a normal line and a mark line. The fill color differs depending on which line is on top.

Source Code Listing

[JSP Version] jspdemo/linefill.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the line chart
double[] data0 = {70, 73, 80, 90, 95, 93, 82, 77, 82, 101, 111, 115};
double[] data1 = {90, 96, 89, 77, 82, 96, 109, 109, 99, 108, 96, 91};
double[] data2 = {58, 34, 25, 49, 64, 10, 16, 40, 25, 49, 40, 22};

// The labels for the line chart
String[] labels = {"2008-01", "2008-02", "2008-03", "2008-04", "2008-05", "2008-06",
    "2008-07", "2008-08", "2008-09", "2008-10", "2008-11", "2008-12"};

// Create a XYChart object of size 450 x 450 pixels
XYChart c = new XYChart(450, 450);

// Add a title to the chart using 15 pts Arial Italic font.
TextBox title = c.addTitle("Inter-line Coloring", "Arial Italic", 15);

// Add a legend box where the top-center is anchored to the horizontal center of the
// chart, just under the title. Use horizontal layout and 10 points Arial Bold font,
// and transparent background and border. Use line style legend key.
LegendBox legendBox = c.addLegend(c.getWidth() / 2, title.getHeight(), false,
    "Arial Bold Italic", 10);
legendBox.setBackground(Chart.Transparent, Chart.Transparent);
legendBox.setAlignment(Chart.TopCenter);
legendBox.setLineStyleKey();

// Tentatively set the plotarea at (70, 65) and of (chart_width - 100) x
// (chart_height - 110) in size. Use light grey (c0c0c0) border and horizontal and
// vertical grid lines.
PlotArea plotArea = c.setPlotArea(70, 65, c.getWidth() - 100, c.getHeight() - 110,
    -1, -1, 0xc0c0c0, 0xc0c0c0, -1);

// Add a title to the y axis using 12 pts Arial Bold Italic font
c.yAxis().setTitle("Axis Title Placeholder", "Arial Bold Italic", 12);

// Add a title to the x axis using 12 pts Arial Bold Italic font
c.xAxis().setTitle("Axis Title Placeholder", "Arial Bold Italic", 12);

// Set the axes line width to 3 pixels
c.xAxis().setWidth(3);
c.yAxis().setWidth(3);

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

// Use 8 points Arial rotated by 90 degrees as the x-axis label font
c.xAxis().setLabelStyle("Arial", 8, Chart.TextColor, 90);

// Add a spline curve to the chart
SplineLayer layer0 = c.addSplineLayer(data0, 0xff0000, "Data Set 0");
layer0.setLineWidth(2);

// Add a normal line to the chart
LineLayer layer1 = c.addLineLayer(data1, 0x008800, "Data Set 1");
layer1.setLineWidth(2);

// Color the region between the above spline curve and normal line. Use the
// semi-transparent red (80ff000000) if the spline curve is higher than the normal
// line, otherwise use semi-transparent green (80008800)
c.addInterLineLayer(layer0.getLine(), layer1.getLine(), 0x80ff0000, 0x80008800);

// Add another normal line to the chart
LineLayer layer2 = c.addLineLayer(data2, 0x0000ff, "Data Set 2");
layer2.setLineWidth(2);

// Add a horizontal mark line to the chart at y = 40
Mark mark = c.yAxis().addMark(40, -1, "Threshold");
mark.setLineWidth(2);

// Set the mark line to purple (880088) dash line. Use white (ffffff) for the mark
// label.
mark.setMarkColor(c.dashLineColor(0x880088), 0xffffff);

// Put the mark label at the left side of the mark, with a purple (880088)
// background.
mark.setAlignment(Chart.Left);
mark.setBackground(0x880088);

// Color the region between the above normal line and mark line. Use the
// semi-transparent blue (800000ff) if the normal line is higher than the mark line,
// otherwise use semi-transparent purple (80880088)
c.addInterLineLayer(layer2.getLine(), mark.getLine(), 0x800000ff, 0x80880088);

// Layout the legend box, so we can get its height
c.layoutLegend();

// Adjust the plot area size, such that the bounding box (inclusive of axes) is 10
// pixels from the left edge, just under the legend box, 25 pixels from the right
// edge, and 10 pixels from the bottom edge.
c.packPlotArea(10, legendBox.getTopY() + legendBox.getHeight(), c.getWidth() - 25,
    c.getHeight() - 10);

// After determining the exact plot area position, we may adjust the legend box and
// the title positions so that they are centered relative to the plot area (instead
// of the chart)
legendBox.setPos(plotArea.getLeftX() + (plotArea.getWidth() - legendBox.getWidth()) /
    2, legendBox.getTopY());
title.setPos(plotArea.getLeftX() + (plotArea.getWidth() - title.getWidth()) / 2,
    title.getTopY());

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName} in {xLabel}: {value}'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Inter-Line Coloring
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/linefill.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class linefill implements DemoModule
{
    //Name of demo program
    public String toString() { return "Inter-Line Coloring"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the line chart
        double[] data0 = {70, 73, 80, 90, 95, 93, 82, 77, 82, 101, 111, 115};
        double[] data1 = {90, 96, 89, 77, 82, 96, 109, 109, 99, 108, 96, 91};
        double[] data2 = {58, 34, 25, 49, 64, 10, 16, 40, 25, 49, 40, 22};

        // The labels for the line chart
        String[] labels = {"2008-01", "2008-02", "2008-03", "2008-04", "2008-05",
            "2008-06", "2008-07", "2008-08", "2008-09", "2008-10", "2008-11",
            "2008-12"};

        // Create a XYChart object of size 450 x 450 pixels
        XYChart c = new XYChart(450, 450);

        // Add a title to the chart using 15 pts Arial Italic font.
        TextBox title = c.addTitle("Inter-line Coloring", "Arial Italic", 15);

        // Add a legend box where the top-center is anchored to the horizontal center
        // of the chart, just under the title. Use horizontal layout and 10 points
        // Arial Bold font, and transparent background and border. Use line style
        // legend key.
        LegendBox legendBox = c.addLegend(c.getWidth() / 2, title.getHeight(), false,
            "Arial Bold Italic", 10);
        legendBox.setBackground(Chart.Transparent, Chart.Transparent);
        legendBox.setAlignment(Chart.TopCenter);
        legendBox.setLineStyleKey();

        // Tentatively set the plotarea at (70, 65) and of (chart_width - 100) x
        // (chart_height - 110) in size. Use light grey (c0c0c0) border and
        // horizontal and vertical grid lines.
        PlotArea plotArea = c.setPlotArea(70, 65, c.getWidth() - 100, c.getHeight() -
            110, -1, -1, 0xc0c0c0, 0xc0c0c0, -1);

        // Add a title to the y axis using 12 pts Arial Bold Italic font
        c.yAxis().setTitle("Axis Title Placeholder", "Arial Bold Italic", 12);

        // Add a title to the x axis using 12 pts Arial Bold Italic font
        c.xAxis().setTitle("Axis Title Placeholder", "Arial Bold Italic", 12);

        // Set the axes line width to 3 pixels
        c.xAxis().setWidth(3);
        c.yAxis().setWidth(3);

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

        // Use 8 points Arial rotated by 90 degrees as the x-axis label font
        c.xAxis().setLabelStyle("Arial", 8, Chart.TextColor, 90);

        // Add a spline curve to the chart
        SplineLayer layer0 = c.addSplineLayer(data0, 0xff0000, "Data Set 0");
        layer0.setLineWidth(2);

        // Add a normal line to the chart
        LineLayer layer1 = c.addLineLayer(data1, 0x008800, "Data Set 1");
        layer1.setLineWidth(2);

        // Color the region between the above spline curve and normal line. Use the
        // semi-transparent red (80ff000000) if the spline curve is higher than the
        // normal line, otherwise use semi-transparent green (80008800)
        c.addInterLineLayer(layer0.getLine(), layer1.getLine(), 0x80ff0000,
            0x80008800);

        // Add another normal line to the chart
        LineLayer layer2 = c.addLineLayer(data2, 0x0000ff, "Data Set 2");
        layer2.setLineWidth(2);

        // Add a horizontal mark line to the chart at y = 40
        Mark mark = c.yAxis().addMark(40, -1, "Threshold");
        mark.setLineWidth(2);

        // Set the mark line to purple (880088) dash line. Use white (ffffff) for the
        // mark label.
        mark.setMarkColor(c.dashLineColor(0x880088), 0xffffff);

        // Put the mark label at the left side of the mark, with a purple (880088)
        // background.
        mark.setAlignment(Chart.Left);
        mark.setBackground(0x880088);

        // Color the region between the above normal line and mark line. Use the
        // semi-transparent blue (800000ff) if the normal line is higher than the
        // mark line, otherwise use semi-transparent purple (80880088)
        c.addInterLineLayer(layer2.getLine(), mark.getLine(), 0x800000ff, 0x80880088)
            ;

        // Layout the legend box, so we can get its height
        c.layoutLegend();

        // Adjust the plot area size, such that the bounding box (inclusive of axes)
        // is 10 pixels from the left edge, just under the legend box, 25 pixels from
        // the right edge, and 10 pixels from the bottom edge.
        c.packPlotArea(10, legendBox.getTopY() + legendBox.getHeight(), c.getWidth()
             - 25, c.getHeight() - 10);

        // After determining the exact plot area position, we may adjust the legend
        // box and the title positions so that they are centered relative to the plot
        // area (instead of the chart)
        legendBox.setPos(plotArea.getLeftX() + (plotArea.getWidth() -
            legendBox.getWidth()) / 2, legendBox.getTopY());
        title.setPos(plotArea.getLeftX() + (plotArea.getWidth() - title.getWidth()) /
            2, title.getTopY());

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='{dataSetName} in {xLabel}: {value}'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new linefill();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/linecompare.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the upper and lower bounding lines
double[] upperY = {60, 60, 100, 100, 60, 60};
double[] lowerY = {40, 40, 80, 80, 40, 40};
double[] zoneX = {0, 2.5, 3.5, 5.5, 6.5, 10};

// The data for the spline curve
double[] curveY = {50, 44, 54, 48, 58, 50, 90, 85, 104, 82, 96, 90, 74, 52, 35, 58,
    46, 54, 48, 52, 50};
double[] curveX = {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.
XYChart c = new XYChart(600, 300, 0xcccccc, 0x000000, 1);

//Set search path to current JSP directory for loading icon images
c.setSearchPath(getServletConfig().getServletContext(), request);

// 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(Chart.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 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 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,
    Chart.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), Chart.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\nEngineering<*/*>"
    ).setAlignment(Chart.BottomRight);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='Temperature at hour {x}: {value} C'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Line with Target Zone
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/linecompare.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class linecompare implements DemoModule
{
    //Name of demo program
    public String toString() { return "Line with Target Zone"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the upper and lower bounding lines
        double[] upperY = {60, 60, 100, 100, 60, 60};
        double[] lowerY = {40, 40, 80, 80, 40, 40};
        double[] zoneX = {0, 2.5, 3.5, 5.5, 6.5, 10};

        // The data for the spline curve
        double[] curveY = {50, 44, 54, 48, 58, 50, 90, 85, 104, 82, 96, 90, 74, 52,
            35, 58, 46, 54, 48, 52, 50};
        double[] curveX = {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.
        XYChart c = new XYChart(600, 300, 0xcccccc, 0x000000, 1);

        // 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(Chart.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 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 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,
            Chart.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),
            Chart.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\n" +
            "Engineering<*/*>").setAlignment(Chart.BottomRight);

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='Temperature at hour {x}: {value} C'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new linecompare();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/errline.jsp
<%@page import="ChartDirector.*" %>
<%
// The data with error information
double[] data = {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};
double[] errData = {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
String[] labels = {"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.
XYChart c = new XYChart(600, 300, 0xeeeeee, 0x000000, 1);
c.setRoundedFrame();

//Set search path to current JSP directory for loading icon images
c.setSearchPath(getServletConfig().getServletContext(), request);

// 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, Chart.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 lineLayer = c.addLineLayer2();

// Add a blue (0xff) data set to the line layer, with yellow (0xffff80) diamond
// symbols
lineLayer.addDataSet(data, 0x0000ff).setDataSymbol(Chart.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.
BoxWhiskerLayer errLayer = c.addBoxWhiskerLayer(null, null, new ArrayMath(data).add(
    errData).result(), new ArrayMath(data).sub(errData).result(), data,
    Chart.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\nEngineering<*/*>"
    ).setAlignment(Chart.BottomRight);

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

// Include tool tip for the chart. We only need to show the tool tip for the box
// whisker layer.
String imageMap1 = errLayer.getHTMLImageMap("", "",
    "title='Temperature at hour {xLabel}: {med} +/- {={med}-{min}} C'");
%>
<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 color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/errline.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class errline implements DemoModule
{
    //Name of demo program
    public String toString() { return "Line with Error Symbols"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data with error information
        double[] data = {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};
        double[] errData = {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
        String[] labels = {"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.
        XYChart c = new XYChart(600, 300, 0xeeeeee, 0x000000, 1);
        c.setRoundedFrame();

        // 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,
            Chart.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 lineLayer = c.addLineLayer2();

        // Add a blue (0xff) data set to the line layer, with yellow (0xffff80)
        // diamond symbols
        lineLayer.addDataSet(data, 0x0000ff).setDataSymbol(Chart.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.
        BoxWhiskerLayer errLayer = c.addBoxWhiskerLayer(null, null, new ArrayMath(
            data).add(errData).result(), new ArrayMath(data).sub(errData).result(),
            data, Chart.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\n" +
            "Engineering<*/*>").setAlignment(Chart.BottomRight);

        // Output the chart
        viewer.setChart(c);

        // Include tool tip for the chart. We only need to show the tool tip for the
        // box whisker layer.
        viewer.setImageMap(errLayer.getHTMLImageMap("clickable", "",
            "title='Temperature at hour {xLabel}: {med} +/- {={med}-{min}} C'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new errline();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


Multi-Symbol Line Chart

Multi-Symbol Line Chart

This example demonstrates a line with different symbols for different data points. It also demonstrates unevenly spaced data points on an auto-scaled true date/time axis, and automatic resizing of the plot area to fit the chart.

The chart in this example 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, followed by the line layer using XYChart.addLineLayer. This ensures the symbols stays on top of the line.

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 unevenly spaced, and the x coordinates are real date/time. The x coordinates are set into the scatter layer as the first argument to 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.

After the entire chart is configured, the XYChart.packPlotArea method is used to adjust the plot area size, so as to fit the plot area and the axes in a given bounding box.

Source Code Listing

[JSP Version] jspdemo/multisymbolline.jsp
<%@page import="ChartDirector.*" %>
<%@page import="java.util.*" %>
<%
// In this example, the data points are unevenly spaced on the x-axis
double[] dataY = {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};
Date[] dataX = {new GregorianCalendar(1999, 6, 1).getTime(), new GregorianCalendar(
    2000, 0, 1).getTime(), new GregorianCalendar(2000, 1, 1).getTime(),
    new GregorianCalendar(2000, 3, 1).getTime(), new GregorianCalendar(2000, 4, 8
    ).getTime(), new GregorianCalendar(2000, 6, 5).getTime(), new GregorianCalendar(
    2001, 2, 5).getTime(), new GregorianCalendar(2001, 3, 7).getTime(),
    new GregorianCalendar(2001, 4, 9).getTime(), new GregorianCalendar(2002, 1, 4
    ).getTime(), new GregorianCalendar(2002, 3, 4).getTime(), new GregorianCalendar(
    2002, 4, 8).getTime(), new GregorianCalendar(2002, 6, 7).getTime(),
    new GregorianCalendar(2002, 7, 30).getTime(), new GregorianCalendar(2003, 0, 2
    ).getTime(), new GregorianCalendar(2003, 1, 16).getTime(), new GregorianCalendar(
    2003, 10, 6).getTime(), new GregorianCalendar(2004, 0, 4).getTime()};

// Data points are assigned different symbols based on point type
double[] pointType = {0, 1, 0, 1, 2, 1, 0, 0, 1, 1, 2, 2, 1, 0, 2, 1, 2, 0};

// Create a XYChart object of size 480 x 320 pixels. Use a vertical gradient color
// from pale blue (e8f0f8) to sky blue (aaccff) spanning half the chart height as
// background. Set border to blue (88aaee). Use rounded corners. Enable soft drop
// shadow.
XYChart c = new XYChart(480, 320);
c.setBackground(c.linearGradientColor(0, 0, 0, c.getHeight() / 2, 0xe8f0f8, 0xaaccff
    ), 0x88aaee);
c.setRoundedFrame();
c.setDropShadow();

// Add a title to the chart using 15 points Arial Italic font. Set top/bottom margins
// to 12 pixels.
TextBox title = c.addTitle("Multi-Symbol Line Chart Demo", "Arial Italic", 15);
title.setMargin2(0, 0, 12, 12);

// Tentatively set the plotarea to 50 pixels from the left edge to allow for the
// y-axis, and to just under the title. Set the width to 65 pixels less than the
// chart width, and the height to reserve 90 pixels at the bottom for the x-axis and
// the legend box. Use pale blue (e8f0f8) background, transparent border, and grey
// (888888) dotted horizontal and vertical grid lines.
c.setPlotArea(50, title.getHeight(), c.getWidth() - 65, c.getHeight() -
    title.getHeight() - 90, 0xe8f0f8, -1, Chart.Transparent, c.dashLineColor(
    0x888888, Chart.DotLine), -1);

// Add a legend box where the bottom-center is anchored to the 12 pixels above the
// bottom-center of the chart. Use horizontal layout and 8 points Arial font.
LegendBox legendBox = c.addLegend(c.getWidth() / 2, c.getHeight() - 12, false,
    "Arial Bold", 8);
legendBox.setAlignment(Chart.BottomCenter);

// Set the legend box background and border to pale blue (e8f0f8) and bluish grey
// (445566)
legendBox.setBackground(0xe8f0f8, 0x445566);

// Use rounded corners of 5 pixel radius for the legend box
legendBox.setRoundedCorners(5);

// Set the y axis label format to display a percentage sign
c.yAxis().setLabelFormat("{value}%");

// Set y-axis title to use 10 points Arial Bold Italic font
c.yAxis().setTitle("Axis Title Placeholder", "Arial Bold Italic", 10);

// 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(Chart.CTime(dataX), new ArrayMath(dataY).selectEQZ(pointType,
    Chart.NoValue).result(), "Point Type 0", Chart.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(Chart.CTime(dataX), new ArrayMath(dataY).selectEQZ(new ArrayMath(
    pointType).sub(1).result(), Chart.NoValue).result(), "Point Type 1",
    Chart.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(Chart.CTime(dataX), new ArrayMath(dataY).selectEQZ(new ArrayMath(
    pointType).sub(2).result(), Chart.NoValue).result(), "Point Type 2",
    Chart.Cross2Shape(), 13, 0xff0000);

// Finally, add a blue (0000ff) line layer with line width of 2 pixels
LineLayer layer = c.addLineLayer(dataY, 0x0000ff);
layer.setXData(Chart.CTime(dataX));
layer.setLineWidth(2);

// Adjust the plot area size, such that the bounding box (inclusive of axes) is 10
// pixels from the left edge, just below the title, 25 pixels from the right edge,
// and 8 pixels above the legend box.
c.packPlotArea(10, title.getHeight(), c.getWidth() - 25, c.layoutLegend().getTopY() -
    8);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "", "title='{x|mmm dd, yyyy}: {value}%'");
%>
<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 color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/multisymbolline.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import ChartDirector.*;

public class multisymbolline implements DemoModule
{
    //Name of demo program
    public String toString() { return "Multi-Symbol Line Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // In this example, the data points are unevenly spaced on the x-axis
        double[] dataY = {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};
        Date[] dataX = {new GregorianCalendar(1999, 6, 1).getTime(),
            new GregorianCalendar(2000, 0, 1).getTime(), new GregorianCalendar(2000,
            1, 1).getTime(), new GregorianCalendar(2000, 3, 1).getTime(),
            new GregorianCalendar(2000, 4, 8).getTime(), new GregorianCalendar(2000,
            6, 5).getTime(), new GregorianCalendar(2001, 2, 5).getTime(),
            new GregorianCalendar(2001, 3, 7).getTime(), new GregorianCalendar(2001,
            4, 9).getTime(), new GregorianCalendar(2002, 1, 4).getTime(),
            new GregorianCalendar(2002, 3, 4).getTime(), new GregorianCalendar(2002,
            4, 8).getTime(), new GregorianCalendar(2002, 6, 7).getTime(),
            new GregorianCalendar(2002, 7, 30).getTime(), new GregorianCalendar(2003,
            0, 2).getTime(), new GregorianCalendar(2003, 1, 16).getTime(),
            new GregorianCalendar(2003, 10, 6).getTime(), new GregorianCalendar(2004,
            0, 4).getTime()};

        // Data points are assigned different symbols based on point type
        double[] pointType = {0, 1, 0, 1, 2, 1, 0, 0, 1, 1, 2, 2, 1, 0, 2, 1, 2, 0};

        // Create a XYChart object of size 480 x 320 pixels. Use a vertical gradient
        // color from pale blue (e8f0f8) to sky blue (aaccff) spanning half the chart
        // height as background. Set border to blue (88aaee). Use rounded corners.
        // Enable soft drop shadow.
        XYChart c = new XYChart(480, 320);
        c.setBackground(c.linearGradientColor(0, 0, 0, c.getHeight() / 2, 0xe8f0f8,
            0xaaccff), 0x88aaee);
        c.setRoundedFrame();
        c.setDropShadow();

        // Add a title to the chart using 15 points Arial Italic font. Set top/bottom
        // margins to 12 pixels.
        TextBox title = c.addTitle("Multi-Symbol Line Chart Demo", "Arial Italic", 15
            );
        title.setMargin2(0, 0, 12, 12);

        // Tentatively set the plotarea to 50 pixels from the left edge to allow for
        // the y-axis, and to just under the title. Set the width to 65 pixels less
        // than the chart width, and the height to reserve 90 pixels at the bottom
        // for the x-axis and the legend box. Use pale blue (e8f0f8) background,
        // transparent border, and grey (888888) dotted horizontal and vertical grid
        // lines.
        c.setPlotArea(50, title.getHeight(), c.getWidth() - 65, c.getHeight() -
            title.getHeight() - 90, 0xe8f0f8, -1, Chart.Transparent, c.dashLineColor(
            0x888888, Chart.DotLine), -1);

        // Add a legend box where the bottom-center is anchored to the 12 pixels
        // above the bottom-center of the chart. Use horizontal layout and 8 points
        // Arial font.
        LegendBox legendBox = c.addLegend(c.getWidth() / 2, c.getHeight() - 12,
            false, "Arial Bold", 8);
        legendBox.setAlignment(Chart.BottomCenter);

        // Set the legend box background and border to pale blue (e8f0f8) and bluish
        // grey (445566)
        legendBox.setBackground(0xe8f0f8, 0x445566);

        // Use rounded corners of 5 pixel radius for the legend box
        legendBox.setRoundedCorners(5);

        // Set the y axis label format to display a percentage sign
        c.yAxis().setLabelFormat("{value}%");

        // Set y-axis title to use 10 points Arial Bold Italic font
        c.yAxis().setTitle("Axis Title Placeholder", "Arial Bold Italic", 10);

        // 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(Chart.CTime(dataX), new ArrayMath(dataY).selectEQZ(
            pointType, Chart.NoValue).result(), "Point Type 0", Chart.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(Chart.CTime(dataX), new ArrayMath(dataY).selectEQZ(
            new ArrayMath(pointType).sub(1).result(), Chart.NoValue).result(),
            "Point Type 1", Chart.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(Chart.CTime(dataX), new ArrayMath(dataY).selectEQZ(
            new ArrayMath(pointType).sub(2).result(), Chart.NoValue).result(),
            "Point Type 2", Chart.Cross2Shape(), 13, 0xff0000);

        // Finally, add a blue (0000ff) line layer with line width of 2 pixels
        LineLayer layer = c.addLineLayer(dataY, 0x0000ff);
        layer.setXData(Chart.CTime(dataX));
        layer.setLineWidth(2);

        // Adjust the plot area size, such that the bounding box (inclusive of axes)
        // is 10 pixels from the left edge, just below the title, 25 pixels from the
        // right edge, and 8 pixels above the legend box.
        c.packPlotArea(10, title.getHeight(), c.getWidth() - 25, c.layoutLegend(
            ).getTopY() - 8);

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='{x|mmm dd, yyyy}: {value}%'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new multisymbolline();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


Binary Data Series

Binary Data Series

This example demonstrates a chart representing binary data series.

A binary data series is a series with elements that can only assume two values. In this example, 0 and 1 are used to represent the two values.

There are plenty of methods to represent binary data series in a chart. In this example, three methods are demonstrated.

  • The "Logic Line" is created by using a step line layer to represent the binary series as a step line. The step line layer is added using XYChart.addStepLineLayer.

  • The "ON/OFF Filling" is created by using two complementary logic lines (that is, one line is always the reverse of the other line). An InterLineLayer is used to fill the region between the two lines, with the fill color dependent on which line is on top.

  • The "ON Only Filling" is the same as the "ON/OFF Filling", except that one of the fill colors is set to Transparent.

Source Code Listing

[JSP Version] jspdemo/binaryseries.jsp
<%@page import="ChartDirector.*" %>
<%@page import="java.util.*" %>
<%
// The data for the chart
double[] dataY = {1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1};
Date[] dataX = {new GregorianCalendar(2008, 6, 1, 0, 0, 0).getTime(),
    new GregorianCalendar(2008, 6, 1, 2, 17, 2).getTime(), new GregorianCalendar(
    2008, 6, 1, 8, 5, 30).getTime(), new GregorianCalendar(2008, 6, 1, 10, 54, 10
    ).getTime(), new GregorianCalendar(2008, 6, 1, 15, 40, 0).getTime(),
    new GregorianCalendar(2008, 6, 1, 18, 22, 20).getTime(), new GregorianCalendar(
    2008, 6, 1, 22, 17, 14).getTime(), new GregorianCalendar(2008, 6, 2, 2, 55, 50
    ).getTime(), new GregorianCalendar(2008, 6, 2, 8, 17, 14).getTime(),
    new GregorianCalendar(2008, 6, 2, 11, 55, 50).getTime(), new GregorianCalendar(
    2008, 6, 2, 13, 17, 14).getTime(), new GregorianCalendar(2008, 6, 2, 17, 55, 50
    ).getTime(), new GregorianCalendar(2008, 6, 2, 20, 17, 14).getTime(),
    new GregorianCalendar(2008, 6, 3, 0, 0, 0).getTime()};

// In this example, we only use position 1, 3, 5 for the data series. Positions 0, 2,
// 4, 6 are empty and serve as gaps.
String[] labels = {"", "ON Only Filling", "",
    "<*font,color=cc2200*>ON<*/font*> / <*font,color=00aa22*>OFF<*/font*> Filling",
    "", "Logic Line", ""};

// Create a XYChart object of size 600 x 180 pixels
XYChart c = new XYChart(600, 180);

// Add a title to the chart using 10 points Arial Bold font. Set top/bottom margins
// to 12 pixels.
TextBox title = c.addTitle("Binary Data Series Demonstration", "Arial Bold", 10);

// Tentatively set the plotarea at (100, 30) and of size 470 x 120 pixels. Use
// transparent border. Use grey (888888) solid line and light grey (ccccc) dotted
// line as major and minor vertical grid lines.
c.setPlotArea(100, 30, 470, 120, -1, -1, Chart.Transparent).setGridColor(
    Chart.Transparent, 0x888888, Chart.Transparent, c.dashLineColor(0xcccccc,
    Chart.DotLine));

// Set axes to transparent
c.xAxis().setColors(Chart.Transparent);
c.yAxis().setColors(Chart.Transparent);

// Set the y axis labels
c.yAxis().setLabels(labels);

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

// Set x-axis major and minor tick density to 50 and 5 pixels. ChartDirector
// auto-scaling will use this as the guideline when putting ticks on the x-axis.
c.xAxis().setTickDensity(50, 5);

// Use "<*font=Arial Bold*>{value|mmm dd}" for the first label of an hour, and
// "{value|hh:nn}" for all other labels.
c.xAxis().setMultiFormat(Chart.StartOfDayFilter(),
    "<*font=Arial Bold*>{value|mmm dd}", Chart.AllPassFilter(), "{value|hh:nn}");

//
// A Logic Line can be achieved using a StepLineLayer in ChartDirector
//

// Shift the data by 4.5, so instead of 0 - 1, it is now 4.5 to 5.5, or fluctuate
// around the y = 5 (Logic Line label) position.
double[] shiftedLine0 = new ArrayMath(dataY).add(4.5).result();

// Add step lines using the original and the reversed data
StepLineLayer layer0 = c.addStepLineLayer(shiftedLine0, 255);
layer0.setXData(dataX);

//
// To perform ON/OFF filling, we draw the logic line, and its reverse, and fill the
// region in between
//

// Shift the data by 2.5, so instead of 0 - 1, it is now 2.5 to 3.5, or fluctuate
// around the y = 3 (ON/OFF Filing label) position.
double[] shiftedLine1 = new ArrayMath(dataY).add(2.5).result();
// Reverse the data, so the 0 becomes 1 and 1 becomes 0, and shift it as well.
double[] reverseShiftedLine1 = new ArrayMath(dataY).mul(-1).add(3.5).result();

// Add step lines using the original and the reversed data
StepLineLayer layer1 = c.addStepLineLayer(shiftedLine1, Chart.Transparent);
layer1.addDataSet(reverseShiftedLine1, Chart.Transparent);
layer1.setXData(dataX);

// Fill the region between the two step lines with green (00aa22) or red (cc2200),
// depending on whether the original or the reserve is higher.
c.addInterLineLayer(layer1.getLine(0), layer1.getLine(1), 0x00aa22, 0xcc2200);

//
// The ON Only filling is the same as ON/OFF filling, except the OFF filling color is
// transparent
//

// Shift the data by 0.5, so instead of 0 - 1, it is now 0.5 to 1.5, or fluctuate
// around the y = 1 (ON Only Filing label) position.
double[] shiftedLine2 = new ArrayMath(dataY).add(0.5).result();
// Reverse the data, so the 0 becomes 1 and 1 becomes 0, and shift it as well.
double[] reverseShiftedLine2 = new ArrayMath(dataY).mul(-1).add(1.5).result();

// Add step lines using the original and the reversed data
StepLineLayer layer2 = c.addStepLineLayer(shiftedLine2, Chart.Transparent);
layer2.addDataSet(reverseShiftedLine2, Chart.Transparent);
layer2.setXData(dataX);

// Fill the region between the two step lines with green (00aa22) or transparent,
// depending on whether the original or the reserve is higher.
c.addInterLineLayer(layer2.getLine(0), layer2.getLine(1), 0x00aa22, Chart.Transparent
    );

// Adjust the plot area size, such that the bounding box (inclusive of axes) is 10
// pixels from the left edge, 10 pixels  below the title, 30 pixels from the right
// edge, and 10 pixels above the bottom edge.
c.packPlotArea(10, title.getHeight() + 10, c.getWidth() - 30, c.getHeight() - 10);

// Output the chart
String chart1URL = c.makeSession(request, "chart1");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Binary Data Series
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'>
</body>
</html>

[Java Version] javademo/binaryseries.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import ChartDirector.*;

public class binaryseries implements DemoModule
{
    //Name of demo program
    public String toString() { return "Binary Data Series"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the chart
        double[] dataY = {1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1};
        Date[] dataX = {new GregorianCalendar(2008, 6, 1, 0, 0, 0).getTime(),
            new GregorianCalendar(2008, 6, 1, 2, 17, 2).getTime(),
            new GregorianCalendar(2008, 6, 1, 8, 5, 30).getTime(),
            new GregorianCalendar(2008, 6, 1, 10, 54, 10).getTime(),
            new GregorianCalendar(2008, 6, 1, 15, 40, 0).getTime(),
            new GregorianCalendar(2008, 6, 1, 18, 22, 20).getTime(),
            new GregorianCalendar(2008, 6, 1, 22, 17, 14).getTime(),
            new GregorianCalendar(2008, 6, 2, 2, 55, 50).getTime(),
            new GregorianCalendar(2008, 6, 2, 8, 17, 14).getTime(),
            new GregorianCalendar(2008, 6, 2, 11, 55, 50).getTime(),
            new GregorianCalendar(2008, 6, 2, 13, 17, 14).getTime(),
            new GregorianCalendar(2008, 6, 2, 17, 55, 50).getTime(),
            new GregorianCalendar(2008, 6, 2, 20, 17, 14).getTime(),
            new GregorianCalendar(2008, 6, 3, 0, 0, 0).getTime()};

        // In this example, we only use position 1, 3, 5 for the data series.
        // Positions 0, 2, 4, 6 are empty and serve as gaps.
        String[] labels = {"", "ON Only Filling", "",
            "<*font,color=cc2200*>ON<*/font*> / <*font,color=00aa22*>OFF<*/font*> " +
            "Filling", "", "Logic Line", ""};

        // Create a XYChart object of size 600 x 180 pixels
        XYChart c = new XYChart(600, 180);

        // Add a title to the chart using 10 points Arial Bold font. Set top/bottom
        // margins to 12 pixels.
        TextBox title = c.addTitle("Binary Data Series Demonstration", "Arial Bold",
            10);

        // Tentatively set the plotarea at (100, 30) and of size 470 x 120 pixels.
        // Use transparent border. Use grey (888888) solid line and light grey
        // (ccccc) dotted line as major and minor vertical grid lines.
        c.setPlotArea(100, 30, 470, 120, -1, -1, Chart.Transparent).setGridColor(
            Chart.Transparent, 0x888888, Chart.Transparent, c.dashLineColor(0xcccccc,
            Chart.DotLine));

        // Set axes to transparent
        c.xAxis().setColors(Chart.Transparent);
        c.yAxis().setColors(Chart.Transparent);

        // Set the y axis labels
        c.yAxis().setLabels(labels);

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

        // Set x-axis major and minor tick density to 50 and 5 pixels. ChartDirector
        // auto-scaling will use this as the guideline when putting ticks on the
        // x-axis.
        c.xAxis().setTickDensity(50, 5);

        // Use "<*font=Arial Bold*>{value|mmm dd}" for the first label of an hour,
        // and "{value|hh:nn}" for all other labels.
        c.xAxis().setMultiFormat(Chart.StartOfDayFilter(),
            "<*font=Arial Bold*>{value|mmm dd}", Chart.AllPassFilter(),
            "{value|hh:nn}");

        //
        // A Logic Line can be achieved using a StepLineLayer in ChartDirector
        //

        // Shift the data by 4.5, so instead of 0 - 1, it is now 4.5 to 5.5, or
        // fluctuate around the y = 5 (Logic Line label) position.
        double[] shiftedLine0 = new ArrayMath(dataY).add(4.5).result();

        // Add step lines using the original and the reversed data
        StepLineLayer layer0 = c.addStepLineLayer(shiftedLine0, 255);
        layer0.setXData(dataX);

        //
        // To perform ON/OFF filling, we draw the logic line, and its reverse, and
        // fill the region in between
        //

        // Shift the data by 2.5, so instead of 0 - 1, it is now 2.5 to 3.5, or
        // fluctuate around the y = 3 (ON/OFF Filing label) position.
        double[] shiftedLine1 = new ArrayMath(dataY).add(2.5).result();
        // Reverse the data, so the 0 becomes 1 and 1 becomes 0, and shift it as
        // well.
        double[] reverseShiftedLine1 = new ArrayMath(dataY).mul(-1).add(3.5).result()
            ;

        // Add step lines using the original and the reversed data
        StepLineLayer layer1 = c.addStepLineLayer(shiftedLine1, Chart.Transparent);
        layer1.addDataSet(reverseShiftedLine1, Chart.Transparent);
        layer1.setXData(dataX);

        // Fill the region between the two step lines with green (00aa22) or red
        // (cc2200), depending on whether the original or the reserve is higher.
        c.addInterLineLayer(layer1.getLine(0), layer1.getLine(1), 0x00aa22, 0xcc2200)
            ;

        //
        // The ON Only filling is the same as ON/OFF filling, except the OFF filling
        // color is transparent
        //

        // Shift the data by 0.5, so instead of 0 - 1, it is now 0.5 to 1.5, or
        // fluctuate around the y = 1 (ON Only Filing label) position.
        double[] shiftedLine2 = new ArrayMath(dataY).add(0.5).result();
        // Reverse the data, so the 0 becomes 1 and 1 becomes 0, and shift it as
        // well.
        double[] reverseShiftedLine2 = new ArrayMath(dataY).mul(-1).add(1.5).result()
            ;

        // Add step lines using the original and the reversed data
        StepLineLayer layer2 = c.addStepLineLayer(shiftedLine2, Chart.Transparent);
        layer2.addDataSet(reverseShiftedLine2, Chart.Transparent);
        layer2.setXData(dataX);

        // Fill the region between the two step lines with green (00aa22) or
        // transparent, depending on whether the original or the reserve is higher.
        c.addInterLineLayer(layer2.getLine(0), layer2.getLine(1), 0x00aa22,
            Chart.Transparent);

        // Adjust the plot area size, such that the bounding box (inclusive of axes)
        // is 10 pixels from the left edge, 10 pixels  below the title, 30 pixels
        // from the right edge, and 10 pixels above the bottom edge.
        c.packPlotArea(10, title.getHeight() + 10, c.getWidth() - 30, c.getHeight() -
            10);

        // Output the chart
        viewer.setChart(c);
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new binaryseries();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


Custom Symbols

Custom Symbols

This example demonstrates loading external image files as data symbols by using DataSet.setDataSymbol2.

Source Code Listing

[JSP Version] jspdemo/customsymbolline.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the chart
double[] data0 = {600, 800, 1200, 1500, 1800, 1900, 2000, 1950};
double[] data1 = {300, 450, 500, 1000, 1500, 1600, 1650, 1600};

// The labels for the chart
String[] labels = {"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.
XYChart c = new XYChart(450, 250, 0xffffc0, 0, 1);

//Set search path to current JSP directory for loading icon images
c.setSearchPath(getServletConfig().getServletContext(), request);

// 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(Chart.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(new int[]{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
LineLayer 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
String chart1URL = c.makeSession(request, "chart1");

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='Number of {dataSetName} at {xLabel}: {value}'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Custom Symbols
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/customsymbolline.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class customsymbolline implements DemoModule
{
    //Name of demo program
    public String toString() { return "Custom Symbols"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the chart
        double[] data0 = {600, 800, 1200, 1500, 1800, 1900, 2000, 1950};
        double[] data1 = {300, 450, 500, 1000, 1500, 1600, 1650, 1600};

        // The labels for the chart
        String[] labels = {"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.
        XYChart c = new XYChart(450, 250, 0xffffc0, 0, 1);

        // 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(Chart.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(new int[]{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
        LineLayer 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
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='Number of {dataSetName} at {xLabel}: {value}'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new customsymbolline();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/rotatedline.jsp
<%@page import="ChartDirector.*" %>
<%@page import="java.util.*" %>
<%
//
//    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 rantable = new RanTable(3, 4, 12);

// Set the 1st column to be the 12 months of year 2002
rantable.setDateCol(0, new GregorianCalendar(2002, 0, 1).getTime(), 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
double[] dataX = rantable.getCol(0);

// Get the 2nd, 3rd and 4th columns as 3 data sets
double[] dataY0 = rantable.getCol(1);
double[] dataY1 = rantable.getCol(2);
double[] dataY2 = rantable.getCol(3);

// Create a XYChart object of size 360 x 400 pixels
XYChart c = new 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
LineLayer 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
String chart1URL = c.makeSession(request, "chart1");

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='[{dataSetName}] {x|mm/yyyy}: {value|0} MByte'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Rotated Line Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/rotatedline.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import ChartDirector.*;

public class rotatedline implements DemoModule
{
    //Name of demo program
    public String toString() { return "Rotated Line Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        //
        //    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 rantable = new RanTable(3, 4, 12);

        // Set the 1st column to be the 12 months of year 2002
        rantable.setDateCol(0, new GregorianCalendar(2002, 0, 1).getTime(), 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
        double[] dataX = rantable.getCol(0);

        // Get the 2nd, 3rd and 4th columns as 3 data sets
        double[] dataY0 = rantable.getCol(1);
        double[] dataY1 = rantable.getCol(2);
        double[] dataY2 = rantable.getCol(3);

        // Create a XYChart object of size 360 x 400 pixels
        XYChart c = new 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
        LineLayer 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
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='[{dataSetName}] {x|mm/yyyy}: {value|0} MByte'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new rotatedline();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/xyline.jsp
<%@page import="ChartDirector.*" %>
<%
// The (x, y) data for the first line
double[] dataX0 = {20, 90, 40, 30, 12};
double[] dataY0 = {10, 40, 75, 54, 20};

// The (x, y) data for the second line
double[] dataX1 = {10, 40, 75, 54, 60};
double[] dataY1 = {50, 90, 40, 30, 10};

// Create a XYChart object of size 450 x 450 pixels
XYChart c = new 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(
    Chart.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
LineLayer 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(Chart.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
LineLayer 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(Chart.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
String chart1URL = c.makeSession(request, "chart1");

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='[{dataSetName}] Pressure = {x} Pa, Temperature = {value} C'");
%>
<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 color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/xyline.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class xyline implements DemoModule
{
    //Name of demo program
    public String toString() { return "Arbitrary XY Line Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The (x, y) data for the first line
        double[] dataX0 = {20, 90, 40, 30, 12};
        double[] dataY0 = {10, 40, 75, 54, 20};

        // The (x, y) data for the second line
        double[] dataX1 = {10, 40, 75, 54, 60};
        double[] dataY1 = {50, 90, 40, 30, 10};

        // Create a XYChart object of size 450 x 450 pixels
        XYChart c = new 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(
            Chart.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
        LineLayer 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(Chart.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
        LineLayer 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(Chart.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
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='[{dataSetName}] Pressure = {x} Pa, Temperature = {value} C'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new xyline();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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.
Parametric Curve Fitting | Demonstrates parametric curve fitting.
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 best fit certain data points. A trend line is computed using linear regression (the least square method).

In ChartDirector, trend lines are created by using XYChart.addTrendLayer or XYChart.addTrendLayer2. A trend layer only shows the trend line, not the data points. Another layer, such as a line or scatter layer, can be used to show the data points.

In this example, two layers are used. A line layer displays the data points as symbols and draws a line that joins them. A trend layer draws a trend line that best fit the same data points.

Note that the x-axis labels 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

[JSP Version] jspdemo/trendline.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the line chart
double[] data = {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
String[] labels = {"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.
XYChart c = new 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(Chart.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 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(
    Chart.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 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
String chart1URL = c.makeSession(request, "chart1");

// include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Trend Line Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/trendline.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class trendline implements DemoModule
{
    //Name of demo program
    public String toString() { return "Trend Line Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the line chart
        double[] data = {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
        String[] labels = {"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.
        XYChart c = new 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(Chart.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 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(
            Chart.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 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
        viewer.setChart(c);

        // include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new trendline();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


Scatter Trend Chart

Scatter Trend Chart

This example demonstrates linear regression trend line fitting together with scatter layers.

The chart in this example has 4 layers - 2 scatter layers created using XYChart.addScatterLayer to show the data points, and two trend layers created using XYChart.addTrendLayer2 for the two trend lines.

Source Code Listing

[JSP Version] jspdemo/scattertrend.jsp
<%@page import="ChartDirector.*" %>
<%
// The XY data of the first data series
double[] dataX0 = {50, 55, 37, 24, 42, 49, 63, 72, 83, 59};
double[] dataY0 = {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
double[] dataX1 = {50, 55, 37, 24, 42, 49, 63, 72, 83, 59};
double[] dataY1 = {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
String scatterToolTip =
    "title='{dataSetName}: Response time at {x} TPS: {value} sec'";
String trendToolTip =
    "title='Slope = {slope|4} sec/TPS; Intercept = {intercept|4} sec'";

// Create a XYChart object of size 450 x 420 pixels
XYChart c = new 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(
    Chart.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 titles to the axes using 12 pts Arial Bold Italic font
c.yAxis().setTitle("Response Time (sec)", "Arial Bold Italic", 12);
c.xAxis().setTitle("Server Load (TPS)", "Arial Bold Italic", 12);

// Set the axes line width to 3 pixels
c.yAxis().setWidth(3);
c.xAxis().setWidth(3);

// Add a scatter layer using (dataX0, dataY0)
ScatterLayer scatter1 = c.addScatterLayer(dataX0, dataY0, "Server AAA",
    Chart.DiamondSymbol, 11, 0x008000);
scatter1.setHTMLImageMap("", "", scatterToolTip);

// Add a trend line layer for (dataX0, dataY0)
TrendLayer trend1 = c.addTrendLayer2(dataX0, dataY0, 0x008000);
trend1.setLineWidth(3);
trend1.setHTMLImageMap("", "", trendToolTip);

// Add a scatter layer for (dataX1, dataY1)
ScatterLayer scatter2 = c.addScatterLayer(dataX1, dataY1, "Server BBB",
    Chart.TriangleSymbol, 9, 0x6666ff);
scatter2.setHTMLImageMap("", "", scatterToolTip);

// Add a trend line layer for (dataX1, dataY1)
TrendLayer trend2 = c.addTrendLayer2(dataX1, dataY1, 0x6666ff);
trend2.setLineWidth(3);
trend2.setHTMLImageMap("", "", trendToolTip);

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

// include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Scatter Trend Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/scattertrend.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class scattertrend implements DemoModule
{
    //Name of demo program
    public String toString() { return "Scatter Trend Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The XY data of the first data series
        double[] dataX0 = {50, 55, 37, 24, 42, 49, 63, 72, 83, 59};
        double[] dataY0 = {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
        double[] dataX1 = {50, 55, 37, 24, 42, 49, 63, 72, 83, 59};
        double[] dataY1 = {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
        String scatterToolTip =
            "title='{dataSetName}: Response time at {x} TPS: {value} sec'";
        String trendToolTip =
            "title='Slope = {slope|4} sec/TPS; Intercept = {intercept|4} sec'";

        // Create a XYChart object of size 450 x 420 pixels
        XYChart c = new 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(
            Chart.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 titles to the axes using 12 pts Arial Bold Italic font
        c.yAxis().setTitle("Response Time (sec)", "Arial Bold Italic", 12);
        c.xAxis().setTitle("Server Load (TPS)", "Arial Bold Italic", 12);

        // Set the axes line width to 3 pixels
        c.yAxis().setWidth(3);
        c.xAxis().setWidth(3);

        // Add a scatter layer using (dataX0, dataY0)
        ScatterLayer scatter1 = c.addScatterLayer(dataX0, dataY0, "Server AAA",
            Chart.DiamondSymbol, 11, 0x008000);
        scatter1.setHTMLImageMap("", "", scatterToolTip);

        // Add a trend line layer for (dataX0, dataY0)
        TrendLayer trend1 = c.addTrendLayer2(dataX0, dataY0, 0x008000);
        trend1.setLineWidth(3);
        trend1.setHTMLImageMap("", "", trendToolTip);

        // Add a scatter layer for (dataX1, dataY1)
        ScatterLayer scatter2 = c.addScatterLayer(dataX1, dataY1, "Server BBB",
            Chart.TriangleSymbol, 9, 0x6666ff);
        scatter2.setHTMLImageMap("", "", scatterToolTip);

        // Add a trend line layer for (dataX1, dataY1)
        TrendLayer trend2 = c.addTrendLayer2(dataX1, dataY1, 0x6666ff);
        trend2.setLineWidth(3);
        trend2.setHTMLImageMap("", "", trendToolTip);

        // Output the chart
        viewer.setChart(c);

        // include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new scattertrend();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/confidenceband.jsp
<%@page import="ChartDirector.*" %>
<%
// The XY data of the first data series
double[] dataX = {50, 55, 37, 24, 42, 49, 63, 72, 83, 59};
double[] dataY = {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
XYChart c = new 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 titles to the axes using 12 pts Arial Bold Italic font
c.yAxis().setTitle("Response Time (sec)", "Arial Bold Italic", 12);
c.xAxis().setTitle("Server Load (TPS)", "Arial Bold Italic", 12);

// Set the axes line width to 3 pixels
c.yAxis().setWidth(3);
c.xAxis().setWidth(3);

// Add a scatter layer using (dataX, dataY)
ScatterLayer scatterLayer = c.addScatterLayer(dataX, dataY, "", Chart.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 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 legendBox = c.addLegend(50, 30, false, "Arial Bold Italic", 10);
legendBox.setBackground(Chart.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 textbox = c.addText(56, 65, java.text.MessageFormat.format(
    "<*block*>Slope\nIntercept\nCorrelation\nStd Error<*/*>   <*block*>" +
    "{0,number,#.####} sec/tps\n{1,number,#.####} sec\n{2,number,#.####}\n" +
    "{3,number,#.####} sec<*/*>", new Object[]{new Double(trendLayer.getSlope()),
    new Double(trendLayer.getIntercept()), new Double(trendLayer.getCorrelation()),
    new Double(trendLayer.getStdError())}), "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
String chart1URL = c.makeSession(request, "chart1");

// include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Confidence Band
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/confidenceband.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class confidenceband implements DemoModule
{
    //Name of demo program
    public String toString() { return "Confidence Band"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The XY data of the first data series
        double[] dataX = {50, 55, 37, 24, 42, 49, 63, 72, 83, 59};
        double[] dataY = {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
        XYChart c = new 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 titles to the axes using 12 pts Arial Bold Italic font
        c.yAxis().setTitle("Response Time (sec)", "Arial Bold Italic", 12);
        c.xAxis().setTitle("Server Load (TPS)", "Arial Bold Italic", 12);

        // Set the axes line width to 3 pixels
        c.yAxis().setWidth(3);
        c.xAxis().setWidth(3);

        // Add a scatter layer using (dataX, dataY)
        ScatterLayer scatterLayer = c.addScatterLayer(dataX, dataY, "",
            Chart.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 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 legendBox = c.addLegend(50, 30, false, "Arial Bold Italic", 10);
        legendBox.setBackground(Chart.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 textbox = c.addText(56, 65, java.text.MessageFormat.format(
            "<*block*>Slope\nIntercept\nCorrelation\nStd Error<*/*>   <*block*>" +
            "{0,number,#.####} sec/tps\n{1,number,#.####} sec\n{2,number,#.####}\n" +
            "{3,number,#.####} sec<*/*>", new Object[]{new Double(
            trendLayer.getSlope()), new Double(trendLayer.getIntercept()),
            new Double(trendLayer.getCorrelation()), new Double(
            trendLayer.getStdError())}), "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
        viewer.setChart(c);

        // include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new confidenceband();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


Parametric Curve Fitting

Parametric Curve Fitting

This example demonstrates parametric curve fitting.

In addition to linear regression, ChartDirector also supports polynomial, exponential and logarithmic regression. To create these curves, a TrendLayer object is created using XYChart.addTrendLayer, and the regressive type is set using TrendLayer.setRegressionType.

Source Code Listing

[JSP Version] jspdemo/paramcurve.jsp
<%@page import="ChartDirector.*" %>
<%
// The XY data of the first data series
double[] dataX0 = {10, 35, 17, 4, 22, 29, 45, 52, 63, 39};
double[] dataY0 = {2.0, 3.2, 2.7, 1.2, 2.8, 2.9, 3.1, 3.0, 2.3, 3.3};

// The XY data of the second data series
double[] dataX1 = {30, 35, 17, 4, 22, 59, 43, 52, 63, 39};
double[] dataY1 = {1.0, 1.3, 0.7, 0.6, 0.8, 3.0, 1.8, 2.3, 3.4, 1.5};

// The XY data of the third data series
double[] dataX2 = {28, 35, 15, 10, 22, 60, 46, 64, 39};
double[] dataY2 = {2.0, 2.2, 1.2, 0.4, 1.8, 2.7, 2.4, 2.8, 2.4};

// Create a XYChart object of size 540 x 480 pixels
XYChart c = new XYChart(540, 480);

// Set the plotarea at (70, 65) and of size 400 x 350 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(70, 65, 400, 350, 0xffffff, -1, 0xc0c0c0, 0xc0c0c0, -1);

// Add a legend box with the top center point anchored at (270, 30). Use horizontal
// layout. Use 10 pts Arial Bold Italic font. Set the background and border color to
// Transparent.
LegendBox legendBox = c.addLegend(270, 30, false, "Arial Bold Italic", 10);
legendBox.setAlignment(Chart.TopCenter);
legendBox.setBackground(Chart.Transparent, Chart.Transparent);

// Add a title to the chart using 18 point Times Bold Itatic font.
c.addTitle("Parametric Curve Fitting", "Times New Roman Bold Italic", 18);

// Add titles to the axes using 12 pts Arial Bold Italic font
c.yAxis().setTitle("Axis Title Placeholder", "Arial Bold Italic", 12);
c.xAxis().setTitle("Axis Title Placeholder", "Arial Bold Italic", 12);

// Set the axes line width to 3 pixels
c.yAxis().setWidth(3);
c.xAxis().setWidth(3);

// Add a scatter layer using (dataX0, dataY0)
c.addScatterLayer(dataX0, dataY0, "Polynomial", Chart.GlassSphere2Shape, 11, 0xff0000
    );

// Add a degree 2 polynomial trend line layer for (dataX0, dataY0)
TrendLayer trend0 = c.addTrendLayer2(dataX0, dataY0, 0xff0000);
trend0.setLineWidth(3);
trend0.setRegressionType(Chart.PolynomialRegression(2));
trend0.setHTMLImageMap("{disable}");

// Add a scatter layer for (dataX1, dataY1)
c.addScatterLayer(dataX1, dataY1, "Exponential", Chart.GlassSphere2Shape, 11,
    0x00aa00);

// Add an exponential trend line layer for (dataX1, dataY1)
TrendLayer trend1 = c.addTrendLayer2(dataX1, dataY1, 0x00aa00);
trend1.setLineWidth(3);
trend1.setRegressionType(Chart.ExponentialRegression);
trend1.setHTMLImageMap("{disable}");

// Add a scatter layer using (dataX2, dataY2)
c.addScatterLayer(dataX2, dataY2, "Logarithmic", Chart.GlassSphere2Shape, 11,
    0x0000ff);

// Add a logarithmic trend line layer for (dataX2, dataY2)
TrendLayer trend2 = c.addTrendLayer2(dataX2, dataY2, 0x0000ff);
trend2.setLineWidth(3);
trend2.setRegressionType(Chart.LogarithmicRegression);
trend2.setHTMLImageMap("{disable}");

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "", "title='[{dataSetName}] ({x}, {value})'"
    );
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Parametric Curve Fitting
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/paramcurve.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class paramcurve implements DemoModule
{
    //Name of demo program
    public String toString() { return "Parametric Curve Fitting"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The XY data of the first data series
        double[] dataX0 = {10, 35, 17, 4, 22, 29, 45, 52, 63, 39};
        double[] dataY0 = {2.0, 3.2, 2.7, 1.2, 2.8, 2.9, 3.1, 3.0, 2.3, 3.3};

        // The XY data of the second data series
        double[] dataX1 = {30, 35, 17, 4, 22, 59, 43, 52, 63, 39};
        double[] dataY1 = {1.0, 1.3, 0.7, 0.6, 0.8, 3.0, 1.8, 2.3, 3.4, 1.5};

        // The XY data of the third data series
        double[] dataX2 = {28, 35, 15, 10, 22, 60, 46, 64, 39};
        double[] dataY2 = {2.0, 2.2, 1.2, 0.4, 1.8, 2.7, 2.4, 2.8, 2.4};

        // Create a XYChart object of size 540 x 480 pixels
        XYChart c = new XYChart(540, 480);

        // Set the plotarea at (70, 65) and of size 400 x 350 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(70, 65, 400, 350, 0xffffff, -1, 0xc0c0c0, 0xc0c0c0, -1);

        // Add a legend box with the top center point anchored at (270, 30). Use
        // horizontal layout. Use 10 pts Arial Bold Italic font. Set the background
        // and border color to Transparent.
        LegendBox legendBox = c.addLegend(270, 30, false, "Arial Bold Italic", 10);
        legendBox.setAlignment(Chart.TopCenter);
        legendBox.setBackground(Chart.Transparent, Chart.Transparent);

        // Add a title to the chart using 18 point Times Bold Itatic font.
        c.addTitle("Parametric Curve Fitting", "Times New Roman Bold Italic", 18);

        // Add titles to the axes using 12 pts Arial Bold Italic font
        c.yAxis().setTitle("Axis Title Placeholder", "Arial Bold Italic", 12);
        c.xAxis().setTitle("Axis Title Placeholder", "Arial Bold Italic", 12);

        // Set the axes line width to 3 pixels
        c.yAxis().setWidth(3);
        c.xAxis().setWidth(3);

        // Add a scatter layer using (dataX0, dataY0)
        c.addScatterLayer(dataX0, dataY0, "Polynomial", Chart.GlassSphere2Shape, 11,
            0xff0000);

        // Add a degree 2 polynomial trend line layer for (dataX0, dataY0)
        TrendLayer trend0 = c.addTrendLayer2(dataX0, dataY0, 0xff0000);
        trend0.setLineWidth(3);
        trend0.setRegressionType(Chart.PolynomialRegression(2));
        trend0.setHTMLImageMap("{disable}");

        // Add a scatter layer for (dataX1, dataY1)
        c.addScatterLayer(dataX1, dataY1, "Exponential", Chart.GlassSphere2Shape, 11,
            0x00aa00);

        // Add an exponential trend line layer for (dataX1, dataY1)
        TrendLayer trend1 = c.addTrendLayer2(dataX1, dataY1, 0x00aa00);
        trend1.setLineWidth(3);
        trend1.setRegressionType(Chart.ExponentialRegression);
        trend1.setHTMLImageMap("{disable}");

        // Add a scatter layer using (dataX2, dataY2)
        c.addScatterLayer(dataX2, dataY2, "Logarithmic", Chart.GlassSphere2Shape, 11,
            0x0000ff);

        // Add a logarithmic trend line layer for (dataX2, dataY2)
        TrendLayer trend2 = c.addTrendLayer2(dataX2, dataY2, 0x0000ff);
        trend2.setLineWidth(3);
        trend2.setRegressionType(Chart.LogarithmicRegression);
        trend2.setHTMLImageMap("{disable}");

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='[{dataSetName}] ({x}, {value})'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new paramcurve();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


General Curve Fitting

General Curve Fitting

This example demonstrates the LOWESS general purpose curve fitting that is built into ChartDirector.

In regression curve fitting, a function type have to be chosen first, and the data are used to compute the best parameters of that function. For example, in polynomial regression, the function type is a polynomial of a given degree, and the data are used to determine the optimal polynomial coefficients.

However, in many applications, the function type is not known or not expressible in algebraic form. To handle these cases, ChartDirector supports a general curve fitting algorithm known as LOWESS. For details, please refer to ArrayMath.lowess and ArrayMath.lowess2.

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

[JSP Version] jspdemo/curvefitting.jsp
<%@page import="ChartDirector.*" %>
<%
// 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 rantable = new 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
double[] data = rantable.getCol(0);

// Create a XYChart object of size 600 x 300 pixels
XYChart c = new 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
LineLayer layer = c.addLineLayer2();

// Add a red (0x80ff0000) data set to the chart with square symbols
layer.addDataSet(data, 0x80ff0000).setDataSymbol(Chart.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(new 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
String chart1URL = c.makeSession(request, "chart1");

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "", "title='({x}, {value|2})'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    General Curve Fitting
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/curvefitting.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class curvefitting implements DemoModule
{
    //Name of demo program
    public String toString() { return "General Curve Fitting"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // 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 rantable = new 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
        double[] data = rantable.getCol(0);

        // Create a XYChart object of size 600 x 300 pixels
        XYChart c = new 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
        LineLayer layer = c.addLineLayer2();

        // Add a red (0x80ff0000) data set to the chart with square symbols
        layer.addDataSet(data, 0x80ff0000).setDataSymbol(Chart.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(new 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
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='({x}, {value|2})'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new curvefitting();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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.
3D Bubble Chart (1) | This examples demonstrates a bubble chart using glass spheres as bubbles.
3D Bubble Chart (2) | This examples demonstrates a bubble chart using brighter glass spheres as bubbles.
3D Bubble Chart (3) | This examples demonstrates a bubble chart using solid spheres as bubbles.
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

[JSP Version] jspdemo/scatter.jsp
<%@page import="ChartDirector.*" %>
<%
// The XY points for the scatter chart
double[] dataX0 = {10, 15, 6, 12, 14, 8, 13, 13, 16, 12, 10.5};
double[] dataY0 = {130, 150, 80, 110, 110, 105, 130, 115, 170, 125, 125};

double[] dataX1 = {6, 12, 4, 3.5, 7, 8, 9, 10, 12, 11, 8};
double[] dataY1 = {65, 80, 40, 45, 70, 80, 80, 90, 100, 105, 60};

// Create a XYChart object of size 450 x 420 pixels
XYChart c = new 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(
    Chart.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", Chart.DiamondSymbol, 13,
    0xff9933);

// Add a green (0x33ff33) scatter chart layer, using 11 pixel triangles as symbols
c.addScatterLayer(dataX1, dataY1, "Natural", Chart.TriangleSymbol, 11, 0x33ff33);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='[{dataSetName}] Weight = {x} kg, Length = {value} cm'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Scatter Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/scatter.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class scatter implements DemoModule
{
    //Name of demo program
    public String toString() { return "Scatter Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The XY points for the scatter chart
        double[] dataX0 = {10, 15, 6, 12, 14, 8, 13, 13, 16, 12, 10.5};
        double[] dataY0 = {130, 150, 80, 110, 110, 105, 130, 115, 170, 125, 125};

        double[] dataX1 = {6, 12, 4, 3.5, 7, 8, 9, 10, 12, 11, 8};
        double[] dataY1 = {65, 80, 40, 45, 70, 80, 80, 90, 100, 105, 60};

        // Create a XYChart object of size 450 x 420 pixels
        XYChart c = new 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(
            Chart.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",
            Chart.DiamondSymbol, 13, 0xff9933);

        // Add a green (0x33ff33) scatter chart layer, using 11 pixel triangles as
        // symbols
        c.addScatterLayer(dataX1, dataY1, "Natural", Chart.TriangleSymbol, 11,
            0x33ff33);

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='[{dataSetName}] Weight = {x} kg, Length = {value} cm'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new scatter();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


Built-In Symbols

Built-In Symbols

This example demonstrates the built-in symbols supported by ChartDirector.

Source Code Listing

[JSP Version] jspdemo/builtinsymbols.jsp
<%@page import="ChartDirector.*" %>
<%
// Some ChartDirector built-in symbols
int[] symbols = {Chart.CircleShape, Chart.GlassSphereShape, Chart.GlassSphere2Shape,
    Chart.SolidSphereShape, Chart.SquareShape, Chart.DiamondShape,
    Chart.TriangleShape, Chart.RightTriangleShape, Chart.LeftTriangleShape,
    Chart.InvertedTriangleShape, Chart.StarShape(3), Chart.StarShape(4),
    Chart.StarShape(5), Chart.StarShape(6), Chart.StarShape(7), Chart.StarShape(8),
    Chart.StarShape(9), Chart.StarShape(10), Chart.PolygonShape(5),
    Chart.Polygon2Shape(5), Chart.PolygonShape(6), Chart.Polygon2Shape(6),
    Chart.CrossShape(0.1), Chart.CrossShape(0.2), Chart.CrossShape(0.3),
    Chart.CrossShape(0.4), Chart.CrossShape(0.5), Chart.CrossShape(0.6),
    Chart.CrossShape(0.7), Chart.Cross2Shape(0.1), Chart.Cross2Shape(0.2),
    Chart.Cross2Shape(0.3), Chart.Cross2Shape(0.4), Chart.Cross2Shape(0.5),
    Chart.Cross2Shape(0.6), Chart.Cross2Shape(0.7)};

// Create a XYChart object of size 450 x 400 pixels
XYChart c = new XYChart(450, 400);

//Set search path to current JSP directory for loading icon images
c.setSearchPath(getServletConfig().getServletContext(), request);

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

// Ensure the ticks are at least 1 unit part (integer ticks)
c.xAxis().setMinTickInc(1);
c.yAxis().setMinTickInc(1);

// Add each symbol as a separate scatter layer.
for (int i = 0; i < symbols.length; ++i) {
    c.addScatterLayer(new double[]{i % 6 + 1}, new double[]{(int)(i / 6 + 1)}, "",
        symbols[i], 15);
}

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "", "title='(x, y) = ({x}, {value})'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Built-in Symbols
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/builtinsymbols.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class builtinsymbols implements DemoModule
{
    //Name of demo program
    public String toString() { return "Built-in Symbols"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // Some ChartDirector built-in symbols
        int[] symbols = {Chart.CircleShape, Chart.GlassSphereShape,
            Chart.GlassSphere2Shape, Chart.SolidSphereShape, Chart.SquareShape,
            Chart.DiamondShape, Chart.TriangleShape, Chart.RightTriangleShape,
            Chart.LeftTriangleShape, Chart.InvertedTriangleShape, Chart.StarShape(3),
            Chart.StarShape(4), Chart.StarShape(5), Chart.StarShape(6),
            Chart.StarShape(7), Chart.StarShape(8), Chart.StarShape(9),
            Chart.StarShape(10), Chart.PolygonShape(5), Chart.Polygon2Shape(5),
            Chart.PolygonShape(6), Chart.Polygon2Shape(6), Chart.CrossShape(0.1),
            Chart.CrossShape(0.2), Chart.CrossShape(0.3), Chart.CrossShape(0.4),
            Chart.CrossShape(0.5), Chart.CrossShape(0.6), Chart.CrossShape(0.7),
            Chart.Cross2Shape(0.1), Chart.Cross2Shape(0.2), Chart.Cross2Shape(0.3),
            Chart.Cross2Shape(0.4), Chart.Cross2Shape(0.5), Chart.Cross2Shape(0.6),
            Chart.Cross2Shape(0.7)};

        // Create a XYChart object of size 450 x 400 pixels
        XYChart c = new 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, -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);

        // Ensure the ticks are at least 1 unit part (integer ticks)
        c.xAxis().setMinTickInc(1);
        c.yAxis().setMinTickInc(1);

        // Add each symbol as a separate scatter layer.
        for (int i = 0; i < symbols.length; ++i) {
            c.addScatterLayer(new double[]{i % 6 + 1}, new double[]{(int)(i / 6 + 1)
                }, "", symbols[i], 15);
        }

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='(x, y) = ({x}, {value})'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new builtinsymbols();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/scattersymbols.jsp
<%@page import="ChartDirector.*" %>
<%
// The XY points for the scatter chart
double[] dataX = {200, 400, 300, 250, 500};
double[] dataY = {40, 100, 50, 150, 250};

// The custom symbols for the points
String[] symbols = {"robot1.png", "robot2.png", "robot3.png", "robot4.png",
    "robot5.png"};

// Create a XYChart object of size 450 x 400 pixels
XYChart c = new XYChart(450, 400);

//Set search path to current JSP directory for loading icon images
c.setSearchPath(getServletConfig().getServletContext(), request);

// 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 (int i = 0; i < dataX.length; ++i) {
    c.addScatterLayer(new double[]{dataX[i]}, new double[]{dataY[i]}).getDataSet(0
        ).setDataSymbol2(symbols[i]);
}

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='Range = {x} km, Speed = {value} km/s'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Custom Scatter Symbols
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/scattersymbols.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class scattersymbols implements DemoModule
{
    //Name of demo program
    public String toString() { return "Custom Scatter Symbols"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The XY points for the scatter chart
        double[] dataX = {200, 400, 300, 250, 500};
        double[] dataY = {40, 100, 50, 150, 250};

        // The custom symbols for the points
        String[] symbols = {"robot1.png", "robot2.png", "robot3.png", "robot4.png",
            "robot5.png"};

        // Create a XYChart object of size 450 x 400 pixels
        XYChart c = new 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, -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 (int i = 0; i < dataX.length; ++i) {
            c.addScatterLayer(new double[]{dataX[i]}, new double[]{dataY[i]}
                ).getDataSet(0).setDataSymbol2(symbols[i]);
        }

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='Range = {x} km, Speed = {value} km/s'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new scattersymbols();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


Custom Scatter Labels

Custom Scatter Labels

This example demonstrates adding custom labels to data points.

  • The red glassy spheres in this example come 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

[JSP Version] jspdemo/scatterlabels.jsp
<%@page import="ChartDirector.*" %>
<%
// The XY points for the scatter chart
double[] dataX = {150, 400, 300, 1500, 800};
double[] dataY = {0.6, 8, 5.4, 2, 4};

// The labels for the points
String[] labels = {"Nano\n100", "SpeedTron\n200 Lite", "SpeedTron\n200",
    "Marathon\nExtra", "Marathon\n2000"};

// Create a XYChart object of size 450 x 400 pixels
XYChart c = new 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
ScatterLayer layer = c.addScatterLayer(dataX, dataY, "", Chart.GlassSphereShape, 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 textbox = layer.setDataLabelStyle("Arial Bold", 8);

// Set the background to purple with a 1 pixel 3D border
textbox.setBackground(0xcc99ff, Chart.Transparent, 1);

// Put the text box 4 pixels to the right of the data point
textbox.setAlignment(Chart.Left);
textbox.setPos(4, 0);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='Range = {x} miles, Capacity = {value} tons'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Custom Scatter Labels
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/scatterlabels.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class scatterlabels implements DemoModule
{
    //Name of demo program
    public String toString() { return "Custom Scatter Labels"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The XY points for the scatter chart
        double[] dataX = {150, 400, 300, 1500, 800};
        double[] dataY = {0.6, 8, 5.4, 2, 4};

        // The labels for the points
        String[] labels = {"Nano\n100", "SpeedTron\n200 Lite", "SpeedTron\n200",
            "Marathon\nExtra", "Marathon\n2000"};

        // Create a XYChart object of size 450 x 400 pixels
        XYChart c = new 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
        ScatterLayer layer = c.addScatterLayer(dataX, dataY, "",
            Chart.GlassSphereShape, 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 textbox = layer.setDataLabelStyle("Arial Bold", 8);

        // Set the background to purple with a 1 pixel 3D border
        textbox.setBackground(0xcc99ff, Chart.Transparent, 1);

        // Put the text box 4 pixels to the right of the data point
        textbox.setAlignment(Chart.Left);
        textbox.setPos(4, 0);

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='Range = {x} miles, Capacity = {value} tons'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new scatterlabels();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/bubble.jsp
<%@page import="ChartDirector.*" %>
<%
// The XYZ points for the bubble chart
double[] dataX0 = {150, 300, 1000, 1700};
double[] dataY0 = {12, 60, 25, 65};
double[] dataZ0 = {20, 50, 50, 85};

double[] dataX1 = {500, 1000, 1300};
double[] dataY1 = {35, 50, 75};
double[] dataZ1 = {30, 55, 95};

// Create a XYChart object of size 450 x 420 pixels
XYChart c = new 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(
    Chart.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", Chart.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", Chart.CircleSymbol, 9,
    0x803333ff, 0x803333ff).setSymbolScale(dataZ1);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='[{dataSetName}] Range = {x} miles, Capacity = {value} tons, Length = " +
    "{z} meters'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Bubble Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/bubble.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class bubble implements DemoModule
{
    //Name of demo program
    public String toString() { return "Bubble Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The XYZ points for the bubble chart
        double[] dataX0 = {150, 300, 1000, 1700};
        double[] dataY0 = {12, 60, 25, 65};
        double[] dataZ0 = {20, 50, 50, 85};

        double[] dataX1 = {500, 1000, 1300};
        double[] dataY1 = {35, 50, 75};
        double[] dataZ1 = {30, 55, 95};

        // Create a XYChart object of size 450 x 420 pixels
        XYChart c = new 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(
            Chart.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", Chart.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", Chart.CircleSymbol, 9,
            0x803333ff, 0x803333ff).setSymbolScale(dataZ1);

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='[{dataSetName}] Range = {x} miles, Capacity = {value} tons, " +
            "Length = {z} meters'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new bubble();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


3D Bubble Chart (1)

3D Bubble Chart (1)

This examples demonstrates a bubble chart using glass spheres as bubbles.

Source Code Listing

[JSP Version] jspdemo/threedbubble.jsp
<%@page import="ChartDirector.*" %>
<%
// The XYZ points for the bubble chart
double[] dataX0 = {170, 300, 1000, 1700};
double[] dataY0 = {16, 69, 16, 75};
double[] dataZ0 = {52, 105, 88, 140};

double[] dataX1 = {500, 1000, 1300};
double[] dataY1 = {40, 58, 85};
double[] dataZ1 = {140, 202, 84};

// Create a XYChart object of size 540 x 480 pixels
XYChart c = new XYChart(540, 480);

// Set the plotarea at (70, 65) and of size 400 x 350 pixels. Turn on both horizontal
// and vertical grid lines with light grey color (0xc0c0c0)
c.setPlotArea(70, 65, 400, 350, -1, -1, Chart.Transparent, 0xc0c0c0, -1);

// Add a legend box at (70, 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(70, 30, false, "Times New Roman Bold Italic", 12).setBackground(
    Chart.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 titles to the axes using 12 pts Arial Bold Italic font
c.yAxis().setTitle("Capacity (tons)", "Arial Bold Italic", 12);
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 red (ff3333) glass spheres, where the
// sphere size is modulated by dataZ0. This creates a bubble effect.
c.addScatterLayer(dataX0, dataY0, "Technology AAA", Chart.GlassSphereShape, 15,
    0xff3333).setSymbolScale(dataZ0);

// Add (dataX1, dataY1) as a scatter layer with blue (0000ff) glass spheres, where
// the sphere size is modulated by dataZ1. This creates a bubble effect.
c.addScatterLayer(dataX1, dataY1, "Technology BBB", Chart.GlassSphereShape, 15,
    0x0000ff).setSymbolScale(dataZ1);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='[{dataSetName}] Range = {x} miles, Capacity = {value} tons, Length = " +
    "{z} meters'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    3D Bubble Chart (1)
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/threedbubble.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class threedbubble implements DemoModule
{
    //Name of demo program
    public String toString() { return "3D Bubble Chart (1)"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The XYZ points for the bubble chart
        double[] dataX0 = {170, 300, 1000, 1700};
        double[] dataY0 = {16, 69, 16, 75};
        double[] dataZ0 = {52, 105, 88, 140};

        double[] dataX1 = {500, 1000, 1300};
        double[] dataY1 = {40, 58, 85};
        double[] dataZ1 = {140, 202, 84};

        // Create a XYChart object of size 540 x 480 pixels
        XYChart c = new XYChart(540, 480);

        // Set the plotarea at (70, 65) and of size 400 x 350 pixels. Turn on both
        // horizontal and vertical grid lines with light grey color (0xc0c0c0)
        c.setPlotArea(70, 65, 400, 350, -1, -1, Chart.Transparent, 0xc0c0c0, -1);

        // Add a legend box at (70, 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(70, 30, false, "Times New Roman Bold Italic", 12).setBackground(
            Chart.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 titles to the axes using 12 pts Arial Bold Italic font
        c.yAxis().setTitle("Capacity (tons)", "Arial Bold Italic", 12);
        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 red (ff3333) glass spheres,
        // where the sphere size is modulated by dataZ0. This creates a bubble
        // effect.
        c.addScatterLayer(dataX0, dataY0, "Technology AAA", Chart.GlassSphereShape,
            15, 0xff3333).setSymbolScale(dataZ0);

        // Add (dataX1, dataY1) as a scatter layer with blue (0000ff) glass spheres,
        // where the sphere size is modulated by dataZ1. This creates a bubble
        // effect.
        c.addScatterLayer(dataX1, dataY1, "Technology BBB", Chart.GlassSphereShape,
            15, 0x0000ff).setSymbolScale(dataZ1);

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='[{dataSetName}] Range = {x} miles, Capacity = {value} tons, " +
            "Length = {z} meters'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new threedbubble();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


3D Bubble Chart (2)

3D Bubble Chart (2)

This examples demonstrates a bubble chart using brighter glass spheres as bubbles.

Source Code Listing

[JSP Version] jspdemo/threedbubble2.jsp
<%@page import="ChartDirector.*" %>
<%
// The XYZ points for the bubble chart
double[] dataX0 = {170, 300, 1000, 1700};
double[] dataY0 = {16, 69, 16, 75};
double[] dataZ0 = {52, 105, 88, 140};

double[] dataX1 = {500, 1000, 1300};
double[] dataY1 = {40, 58, 85};
double[] dataZ1 = {140, 202, 84};

// Create a XYChart object of size 540 x 480 pixels
XYChart c = new XYChart(540, 480);

// Set the plotarea at (70, 65) and of size 400 x 350 pixels. Turn on both horizontal
// and vertical grid lines with light grey color (0xc0c0c0)
c.setPlotArea(70, 65, 400, 350, -1, -1, Chart.Transparent, 0xc0c0c0, -1);

// Add a legend box at (70, 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(70, 30, false, "Times New Roman Bold Italic", 12).setBackground(
    Chart.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 titles to the axes using 12 pts Arial Bold Italic font
c.yAxis().setTitle("Capacity (tons)", "Arial Bold Italic", 12);
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 red (ff3333) glass spheres, where the
// sphere size is modulated by dataZ0. This creates a bubble effect.
c.addScatterLayer(dataX0, dataY0, "Technology AAA", Chart.GlassSphere2Shape, 15,
    0xff3333).setSymbolScale(dataZ0);

// Add (dataX1, dataY1) as a scatter layer with blue (0000ff) glass spheres, where
// the sphere size is modulated by dataZ1. This creates a bubble effect.
c.addScatterLayer(dataX1, dataY1, "Technology BBB", Chart.GlassSphere2Shape, 15,
    0x0000ff).setSymbolScale(dataZ1);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='[{dataSetName}] Range = {x} miles, Capacity = {value} tons, Length = " +
    "{z} meters'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    3D Bubble Chart (2)
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/threedbubble2.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class threedbubble2 implements DemoModule
{
    //Name of demo program
    public String toString() { return "3D Bubble Chart (2)"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The XYZ points for the bubble chart
        double[] dataX0 = {170, 300, 1000, 1700};
        double[] dataY0 = {16, 69, 16, 75};
        double[] dataZ0 = {52, 105, 88, 140};

        double[] dataX1 = {500, 1000, 1300};
        double[] dataY1 = {40, 58, 85};
        double[] dataZ1 = {140, 202, 84};

        // Create a XYChart object of size 540 x 480 pixels
        XYChart c = new XYChart(540, 480);

        // Set the plotarea at (70, 65) and of size 400 x 350 pixels. Turn on both
        // horizontal and vertical grid lines with light grey color (0xc0c0c0)
        c.setPlotArea(70, 65, 400, 350, -1, -1, Chart.Transparent, 0xc0c0c0, -1);

        // Add a legend box at (70, 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(70, 30, false, "Times New Roman Bold Italic", 12).setBackground(
            Chart.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 titles to the axes using 12 pts Arial Bold Italic font
        c.yAxis().setTitle("Capacity (tons)", "Arial Bold Italic", 12);
        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 red (ff3333) glass spheres,
        // where the sphere size is modulated by dataZ0. This creates a bubble
        // effect.
        c.addScatterLayer(dataX0, dataY0, "Technology AAA", Chart.GlassSphere2Shape,
            15, 0xff3333).setSymbolScale(dataZ0);

        // Add (dataX1, dataY1) as a scatter layer with blue (0000ff) glass spheres,
        // where the sphere size is modulated by dataZ1. This creates a bubble
        // effect.
        c.addScatterLayer(dataX1, dataY1, "Technology BBB", Chart.GlassSphere2Shape,
            15, 0x0000ff).setSymbolScale(dataZ1);

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='[{dataSetName}] Range = {x} miles, Capacity = {value} tons, " +
            "Length = {z} meters'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new threedbubble2();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


3D Bubble Chart (3)

3D Bubble Chart (3)

This examples demonstrates a bubble chart using solid spheres as bubbles.

Source Code Listing

[JSP Version] jspdemo/threedbubble3.jsp
<%@page import="ChartDirector.*" %>
<%
// The XYZ points for the bubble chart
double[] dataX0 = {170, 300, 1000, 1700};
double[] dataY0 = {16, 69, 16, 75};
double[] dataZ0 = {52, 105, 88, 140};

double[] dataX1 = {500, 1000, 1300};
double[] dataY1 = {40, 58, 85};
double[] dataZ1 = {140, 202, 84};

// Create a XYChart object of size 540 x 480 pixels
XYChart c = new XYChart(540, 480);

// Set the plotarea at (70, 65) and of size 400 x 350 pixels. Turn on both horizontal
// and vertical grid lines with light grey color (0xc0c0c0)
c.setPlotArea(70, 65, 400, 350, -1, -1, Chart.Transparent, 0xc0c0c0, -1);

// Add a legend box at (70, 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(70, 30, false, "Times New Roman Bold Italic", 12).setBackground(
    Chart.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 titles to the axes using 12 pts Arial Bold Italic font
c.yAxis().setTitle("Capacity (tons)", "Arial Bold Italic", 12);
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 red (ff3333) spheres, where the
// sphere size is modulated by dataZ0. This creates a bubble effect.
c.addScatterLayer(dataX0, dataY0, "Technology AAA", Chart.SolidSphereShape, 15,
    0xff3333).setSymbolScale(dataZ0);

// Add (dataX1, dataY1) as a scatter layer with blue (0000ff) spheres, where the
// sphere size is modulated by dataZ1. This creates a bubble effect.
c.addScatterLayer(dataX1, dataY1, "Technology BBB", Chart.SolidSphereShape, 15,
    0x0000ff).setSymbolScale(dataZ1);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='[{dataSetName}] Range = {x} miles, Capacity = {value} tons, Length = " +
    "{z} meters'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    3D Bubble Chart (3)
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/threedbubble3.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class threedbubble3 implements DemoModule
{
    //Name of demo program
    public String toString() { return "3D Bubble Chart (3)"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The XYZ points for the bubble chart
        double[] dataX0 = {170, 300, 1000, 1700};
        double[] dataY0 = {16, 69, 16, 75};
        double[] dataZ0 = {52, 105, 88, 140};

        double[] dataX1 = {500, 1000, 1300};
        double[] dataY1 = {40, 58, 85};
        double[] dataZ1 = {140, 202, 84};

        // Create a XYChart object of size 540 x 480 pixels
        XYChart c = new XYChart(540, 480);

        // Set the plotarea at (70, 65) and of size 400 x 350 pixels. Turn on both
        // horizontal and vertical grid lines with light grey color (0xc0c0c0)
        c.setPlotArea(70, 65, 400, 350, -1, -1, Chart.Transparent, 0xc0c0c0, -1);

        // Add a legend box at (70, 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(70, 30, false, "Times New Roman Bold Italic", 12).setBackground(
            Chart.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 titles to the axes using 12 pts Arial Bold Italic font
        c.yAxis().setTitle("Capacity (tons)", "Arial Bold Italic", 12);
        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 red (ff3333) spheres, where
        // the sphere size is modulated by dataZ0. This creates a bubble effect.
        c.addScatterLayer(dataX0, dataY0, "Technology AAA", Chart.SolidSphereShape,
            15, 0xff3333).setSymbolScale(dataZ0);

        // Add (dataX1, dataY1) as a scatter layer with blue (0000ff) spheres, where
        // the sphere size is modulated by dataZ1. This creates a bubble effect.
        c.addScatterLayer(dataX1, dataY1, "Technology BBB", Chart.SolidSphereShape,
            15, 0x0000ff).setSymbolScale(dataZ1);

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='[{dataSetName}] Range = {x} miles, Capacity = {value} tons, " +
            "Length = {z} meters'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new threedbubble3();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/bubblescale.jsp
<%@page import="ChartDirector.*" %>
<%
// The XY points for the bubble chart. The bubble chart has independent bubble size
// on the X and Y direction.
double[] dataX0 = {1000, 1500, 1700};
double[] dataY0 = {25, 20, 65};
double[] dataZX0 = {500, 200, 600};
double[] dataZY0 = {15, 30, 20};

double[] dataX1 = {500, 1000, 1300};
double[] dataY1 = {35, 50, 75};
double[] dataZX1 = {800, 300, 500};
double[] dataZY1 = {8, 27, 25};

double[] dataX2 = {150, 300};
double[] dataY2 = {20, 60};
double[] dataZX2 = {160, 400};
double[] dataZY2 = {30, 20};

// Create a XYChart object of size 450 x 420 pixels
XYChart c = new 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(
    Chart.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", Chart.CircleSymbol, 9, 0xff3333,
    0xff3333);
c.addScatterLayer(dataX0, dataY0, "", Chart.CircleSymbol, 9, 0x80ff3333, 0x80ff3333
    ).setSymbolScale(dataZX0, Chart.XAxisScale, dataZY0, Chart.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", Chart.SquareSymbol, 7, 0x3333ff,
    0x3333ff);
c.addScatterLayer(dataX1, dataY1, "", Chart.SquareSymbol, 9, 0x803333ff, 0x803333ff
    ).setSymbolScale(dataZX1, Chart.XAxisScale, dataZY1, Chart.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", Chart.DiamondSymbol, 9, 0x00ff00,
    0x00ff00);
c.addScatterLayer(dataX2, dataY2, "", Chart.DiamondSymbol, 9, 0x8033ff33, 0x8033ff33
    ).setSymbolScale(dataZX2, Chart.XAxisScale, dataZY2, Chart.YAxisScale);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='Voltage = {x} +/- {={zx}/2} V, Current = {value} +/- {={zy}/2} A'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Bubble XY Scaling
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/bubblescale.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class bubblescale implements DemoModule
{
    //Name of demo program
    public String toString() { return "Bubble XY Scaling"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The XY points for the bubble chart. The bubble chart has independent
        // bubble size on the X and Y direction.
        double[] dataX0 = {1000, 1500, 1700};
        double[] dataY0 = {25, 20, 65};
        double[] dataZX0 = {500, 200, 600};
        double[] dataZY0 = {15, 30, 20};

        double[] dataX1 = {500, 1000, 1300};
        double[] dataY1 = {35, 50, 75};
        double[] dataZX1 = {800, 300, 500};
        double[] dataZY1 = {8, 27, 25};

        double[] dataX2 = {150, 300};
        double[] dataY2 = {20, 60};
        double[] dataZX2 = {160, 400};
        double[] dataZY2 = {30, 20};

        // Create a XYChart object of size 450 x 420 pixels
        XYChart c = new 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(
            Chart.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", Chart.CircleSymbol, 9,
            0xff3333, 0xff3333);
        c.addScatterLayer(dataX0, dataY0, "", Chart.CircleSymbol, 9, 0x80ff3333,
            0x80ff3333).setSymbolScale(dataZX0, Chart.XAxisScale, dataZY0,
            Chart.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", Chart.SquareSymbol, 7,
            0x3333ff, 0x3333ff);
        c.addScatterLayer(dataX1, dataY1, "", Chart.SquareSymbol, 9, 0x803333ff,
            0x803333ff).setSymbolScale(dataZX1, Chart.XAxisScale, dataZY1,
            Chart.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", Chart.DiamondSymbol, 9,
            0x00ff00, 0x00ff00);
        c.addScatterLayer(dataX2, dataY2, "", Chart.DiamondSymbol, 9, 0x8033ff33,
            0x8033ff33).setSymbolScale(dataZX2, Chart.XAxisScale, dataZY2,
            Chart.YAxisScale);

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='Voltage = {x} +/- {={zx}/2} V, Current = {value} +/- " +
            "{={zy}/2} A'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new bubblescale();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/vector.jsp
<%@page import="ChartDirector.*" %>
<%
// The (x, y) coordinates of the starting point of the vectors
double[] dataX = {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};
double[] dataY = {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
double[] dataR = {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};
double[] dataA = {-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
XYChart c = new 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, Chart.YAxisScale, 0x0000cc
    ).setArrowHead(11);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='Vector at ({x}, {value}): Length = {len}, Angle = {dir} deg'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Vector Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/vector.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class vector implements DemoModule
{
    //Name of demo program
    public String toString() { return "Vector Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The (x, y) coordinates of the starting point of the vectors
        double[] dataX = {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};
        double[] dataY = {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
        double[] dataR = {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};
        double[] dataA = {-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
        XYChart c = new 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, Chart.YAxisScale, 0x0000cc
            ).setArrowHead(11);

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='Vector at ({x}, {value}): Length = {len}, Angle = {dir} deg'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new vector();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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 (JSP version) or BaseChart.makeImage (Java version).

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

Source Code Listing

[JSP Version] jspdemo/simplearea.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the area chart
double[] data = {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
String[] labels = {"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
XYChart c = new 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
String chart1URL = c.makeSession(request, "chart1");

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='Hour {xLabel}: Traffic {value} GBytes'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Simple Area Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/simplearea.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class simplearea implements DemoModule
{
    //Name of demo program
    public String toString() { return "Simple Area Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the area chart
        double[] data = {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
        String[] labels = {"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
        XYChart c = new 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
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='Hour {xLabel}: Traffic {value} GBytes'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new simplearea();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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.

  • The brushed silver background is achieved by using Chart.brushedSilverColor to create the brushed silver color, then use it in XYChart.XYChart as the chart background color.

  • The rounded frame is configured using BaseChart.setRoundedFrame.

  • The soft drop shadow is configured using BaseChart.setDropShadow.

  • Add a title to the chart using BaseChart.addTitle. The title text is represented using CDML to include star icons in the text.

  • Add a transparent box using BaseChart.addText and Box.setSize, with a depressed 3D border configured with Box.setBackground and rounded corners configured with Box.setRoundedCorners. The box is for decorative purpose and acts as the border for the chart contents excluding the title.

  • Set the background, border and grid colors of the plot area using XYChart.setPlotArea.

  • 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

[JSP Version] jspdemo/enhancedarea.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the area chart
double[] data = {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
String[] labels = {"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 360 pixels, with a brushed silver
// background, 1 pixel 3D border effect, rounded corners and soft drop shadow.
XYChart c = new XYChart(600, 360, Chart.brushedSilverColor(), Chart.Transparent, 1);
c.setRoundedFrame();
c.setDropShadow();

//Set search path to current JSP directory for loading icon images
c.setSearchPath(getServletConfig().getServletContext(), request);

// Add a title box to the chart using 18 pts Times Bold Italic font.
TextBox title = c.addTitle(
    "<*block,valign=absmiddle*><*img=star.png*><*img=star.png*> Performance " +
    "Enhancer <*img=star.png*><*img=star.png*><*/*>", "Times New Roman Bold Italic",
    18);

//
// Use a text box with a depressed 3D border to create the inner depressed region
//

// The width of the frame border
int frameWidth = 5;

// Set the depressed region position
TextBox contentBox = c.addText(frameWidth, title.getHeight(), "");
contentBox.setSize(c.getDrawArea().getWidth() - 1 - frameWidth * 2, c.getDrawArea(
    ).getHeight() - title.getHeight() - frameWidth - 1);

// Use -1 as the rasied effect to create a depressed region
contentBox.setBackground(Chart.Transparent, Chart.Transparent, -1);

// Set rounded corners, and put the text box at the back of the chart
contentBox.setRoundedCorners(10);
contentBox.setZOrder(Chart.ChartBackZ);

// Tentatively set the plotarea to 50 pixels from the left depressed edge, and 25
// pixels under the top depressed edge. Set the width to 75 pixels less than the
// depressed region width, and the height to 75 pixels less than the depressed region
// height. Use white (ffffff) background, transparent border, and grey (cccccc)
// horizontal and vertical grid lines.
PlotArea plotArea = c.setPlotArea(50 + contentBox.getLeftX(), contentBox.getTopY() +
    25, contentBox.getWidth() - 75, contentBox.getHeight() - 75, 0xffffff, -1, -1,
    0xcccccc, -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 using a gradient color that changes vertically from
// semi-transparent red (60ff0000) to semi-transparent white (60ffffff)
c.addAreaLayer(data, c.linearGradientColor(0, contentBox.getTopY() + 20, 0,
    contentBox.getTopY() + contentBox.getHeight() - 50, 0x60ff0000, 0x60ffffff));

// Adjust the plot area size, such that the bounding box (inclusive of axes) is 15
// pixels from the left depressed edge, 25 pixels below the top depressed edge, 25
// pixels from the right depressed edge, and 15 pixels above the bottom depressed
// edge.
c.packPlotArea(contentBox.getLeftX() + 15, contentBox.getTopY() + 25,
    contentBox.getLeftX() + contentBox.getWidth() - 25, contentBox.getTopY() +
    contentBox.getHeight() - 15);

// Add a custom CDML text with the bottom right corner is anchored to the bootom
// right corner of the plot area, with 5 pixels margin.
c.addText(plotArea.getLeftX() + plotArea.getWidth() - 5, plotArea.getTopY() +
    plotArea.getHeight() - 5,
    "<*block,valign=absmiddle*><*img=small_molecule.png*> <*block*><*font=Times " +
    "New Roman Bold Italic,size=10,color=804040*>Molecular\nEngineering<*/*>"
    ).setAlignment(Chart.BottomRight);

// Output the chart
String chart1URL = c.makeSession(request, "chart1", Chart.JPG);

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='Hour {xLabel}: {value} KJ/liter'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Enhanced Area Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/enhancedarea.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class enhancedarea implements DemoModule
{
    //Name of demo program
    public String toString() { return "Enhanced Area Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the area chart
        double[] data = {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
        String[] labels = {"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 360 pixels, with a brushed silver
        // background, 1 pixel 3D border effect, rounded corners and soft drop
        // shadow.
        XYChart c = new XYChart(600, 360, Chart.brushedSilverColor(),
            Chart.Transparent, 1);
        c.setRoundedFrame();
        c.setDropShadow();

        // Add a title box to the chart using 18 pts Times Bold Italic font.
        TextBox title = c.addTitle(
            "<*block,valign=absmiddle*><*img=star.png*><*img=star.png*> " +
            "Performance Enhancer <*img=star.png*><*img=star.png*><*/*>",
            "Times New Roman Bold Italic", 18);

        //
        // Use a text box with a depressed 3D border to create the inner depressed
        // region
        //

        // The width of the frame border
        int frameWidth = 5;

        // Set the depressed region position
        TextBox contentBox = c.addText(frameWidth, title.getHeight(), "");
        contentBox.setSize(c.getDrawArea().getWidth() - 1 - frameWidth * 2,
            c.getDrawArea().getHeight() - title.getHeight() - frameWidth - 1);

        // Use -1 as the rasied effect to create a depressed region
        contentBox.setBackground(Chart.Transparent, Chart.Transparent, -1);

        // Set rounded corners, and put the text box at the back of the chart
        contentBox.setRoundedCorners(10);
        contentBox.setZOrder(Chart.ChartBackZ);

        // Tentatively set the plotarea to 50 pixels from the left depressed edge,
        // and 25 pixels under the top depressed edge. Set the width to 75 pixels
        // less than the depressed region width, and the height to 75 pixels less
        // than the depressed region height. Use white (ffffff) background,
        // transparent border, and grey (cccccc) horizontal and vertical grid lines.
        PlotArea plotArea = c.setPlotArea(50 + contentBox.getLeftX(),
            contentBox.getTopY() + 25, contentBox.getWidth() - 75,
            contentBox.getHeight() - 75, 0xffffff, -1, -1, 0xcccccc, -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 using a gradient color that changes
        // vertically from semi-transparent red (60ff0000) to semi-transparent white
        // (60ffffff)
        c.addAreaLayer(data, c.linearGradientColor(0, contentBox.getTopY() + 20, 0,
            contentBox.getTopY() + contentBox.getHeight() - 50, 0x60ff0000,
            0x60ffffff));

        // Adjust the plot area size, such that the bounding box (inclusive of axes)
        // is 15 pixels from the left depressed edge, 25 pixels below the top
        // depressed edge, 25 pixels from the right depressed edge, and 15 pixels
        // above the bottom depressed edge.
        c.packPlotArea(contentBox.getLeftX() + 15, contentBox.getTopY() + 25,
            contentBox.getLeftX() + contentBox.getWidth() - 25, contentBox.getTopY()
             + contentBox.getHeight() - 15);

        // Add a custom CDML text with the bottom right corner is anchored to the
        // bootom right corner of the plot area, with 5 pixels margin.
        c.addText(plotArea.getLeftX() + plotArea.getWidth() - 5, plotArea.getTopY() +
            plotArea.getHeight() - 5,
            "<*block,valign=absmiddle*><*img=small_molecule.png*> <*block*>" +
            "<*font=Times New Roman Bold Italic,size=10,color=804040*>Molecular\n" +
            "Engineering<*/*>").setAlignment(Chart.BottomRight);

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='Hour {xLabel}: {value} KJ/liter'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new enhancedarea();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


3D Area Chart

3D Area Chart

This example demonstrates a 3D area chart configured using Layer.set3D.

Source Code Listing

[JSP Version] jspdemo/threedarea.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the area chart
double[] data = {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
String[] labels = {"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
XYChart c = new 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
String chart1URL = c.makeSession(request, "chart1");

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='Hour {xLabel}: Traffic {value} MBytes'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    3D Area Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/threedarea.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class threedarea implements DemoModule
{
    //Name of demo program
    public String toString() { return "3D Area Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the area chart
        double[] data = {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
        String[] labels = {"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
        XYChart c = new 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
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='Hour {xLabel}: Traffic {value} MBytes'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new threedarea();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/patternarea.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the area chart
double[] data = {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
String[] labels = {"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)
XYChart c = new XYChart(300, 180, 0xffffa0, 0x000000);

//Set search path to current JSP directory for loading icon images
c.setSearchPath(getServletConfig().getServletContext(), request);

// 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(new int[]{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
AreaLayer layer = c.addAreaLayer();

// Load a snow pattern from an external file "snow.png".
int 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
String chart1URL = c.makeSession(request, "chart1");

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "", "title='{xLabel}:00 - {value} mm/hour'")
    ;
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Pattern Area Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/patternarea.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class patternarea implements DemoModule
{
    //Name of demo program
    public String toString() { return "Pattern Area Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the area chart
        double[] data = {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
        String[] labels = {"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)
        XYChart c = new XYChart(300, 180, 0xffffa0, 0x000000);

        // 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(new int[]{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
        AreaLayer layer = c.addAreaLayer();

        // Load a snow pattern from an external file "snow.png".
        int 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
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='{xLabel}:00 - {value} mm/hour'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new patternarea();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/stackedarea.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the area chart
double[] data0 = {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};
double[] data1 = {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};
double[] data2 = {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};
String[] labels = {"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)
XYChart c = new 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(Chart.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
AreaLayer layer = c.addAreaLayer2(Chart.Stack);
layer.addDataSet(data0, 0x4040ff, "Store #1");
layer.addDataSet(data1, 0xff4040, "Store #2");
layer.addDataSet(data2, 0x40ff40, "Store #3");

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName} sales at hour {xLabel}: US${value}K'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Stacked Area Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/stackedarea.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class stackedarea implements DemoModule
{
    //Name of demo program
    public String toString() { return "Stacked Area Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the area chart
        double[] data0 = {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};
        double[] data1 = {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};
        double[] data2 = {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};
        String[] labels = {"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)
        XYChart c = new 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(Chart.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
        AreaLayer layer = c.addAreaLayer2(Chart.Stack);
        layer.addDataSet(data0, 0x4040ff, "Store #1");
        layer.addDataSet(data1, 0xff4040, "Store #2");
        layer.addDataSet(data2, 0x40ff40, "Store #3");

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='{dataSetName} sales at hour {xLabel}: US${value}K'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new stackedarea();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/threedstackarea.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the area chart
double[] data0 = {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};
double[] data1 = {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};
double[] data2 = {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};
String[] labels = {"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
XYChart c = new 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\nQueries\n(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
AreaLayer 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
String chart1URL = c.makeSession(request, "chart1");

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName} load at hour {xLabel}: {value} queries/sec'");
%>
<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 color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/threedstackarea.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class threedstackarea implements DemoModule
{
    //Name of demo program
    public String toString() { return "3D Stacked Area Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the area chart
        double[] data0 = {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};
        double[] data1 = {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};
        double[] data2 = {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};
        String[] labels = {"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
        XYChart c = new 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\nQueries\n(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
        AreaLayer 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
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='{dataSetName} load at hour {xLabel}: {value} queries/sec'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new threedstackarea();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/percentarea.jsp
<%@page import="ChartDirector.*" %>
<%@page import="java.util.*" %>
<%
// The data for the area chart
double[] data0 = {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};
double[] data1 = {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};
double[] data2 = {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
Date[] labels = {new GregorianCalendar(1996, 0, 1).getTime(), new GregorianCalendar(
    1996, 3, 1).getTime(), new GregorianCalendar(1996, 6, 1).getTime(),
    new GregorianCalendar(1996, 9, 1).getTime(), new GregorianCalendar(1997, 0, 1
    ).getTime(), new GregorianCalendar(1997, 3, 1).getTime(), new GregorianCalendar(
    1997, 6, 1).getTime(), new GregorianCalendar(1997, 9, 1).getTime(),
    new GregorianCalendar(1998, 0, 1).getTime(), new GregorianCalendar(1998, 3, 1
    ).getTime(), new GregorianCalendar(1998, 6, 1).getTime(), new GregorianCalendar(
    1998, 9, 1).getTime(), new GregorianCalendar(1999, 0, 1).getTime(),
    new GregorianCalendar(1999, 3, 1).getTime(), new GregorianCalendar(1999, 6, 1
    ).getTime(), new GregorianCalendar(1999, 9, 1).getTime(), new GregorianCalendar(
    2000, 0, 1).getTime(), new GregorianCalendar(2000, 3, 1).getTime(),
    new GregorianCalendar(2000, 6, 1).getTime(), new GregorianCalendar(2000, 9, 1
    ).getTime(), new GregorianCalendar(2001, 0, 1).getTime(), new GregorianCalendar(
    2001, 3, 1).getTime(), new GregorianCalendar(2001, 6, 1).getTime(),
    new GregorianCalendar(2001, 9, 1).getTime(), new GregorianCalendar(2002, 0, 1
    ).getTime()};

// 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
XYChart c = new XYChart(500, 280, 0xffffcc, 0, 1);

//Set search path to current JSP directory for loading icon images
c.setSearchPath(getServletConfig().getServletContext(), request);

// 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 legendBox = c.addLegend(370, 45, true, "Arial Bold", 8);

// Set the legend box background and border to transparent
legendBox.setBackground(Chart.Transparent, Chart.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(Chart.StartOfYearFilter(), "{value|yyyy}",
    Chart.AllPassFilter(), "-");

// Add a percentage area layer to the chart
AreaLayer layer = c.addAreaLayer2(Chart.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(Chart.ReverseLegend);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName} sales at {xLabel|yyyy} Q{=({xLabel|m}+2)/3|0}: " +
    "US${value}K ({percent}%)'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Percentage Area Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/percentarea.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import ChartDirector.*;

public class percentarea implements DemoModule
{
    //Name of demo program
    public String toString() { return "Percentage Area Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the area chart
        double[] data0 = {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};
        double[] data1 = {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};
        double[] data2 = {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
        Date[] labels = {new GregorianCalendar(1996, 0, 1).getTime(),
            new GregorianCalendar(1996, 3, 1).getTime(), new GregorianCalendar(1996,
            6, 1).getTime(), new GregorianCalendar(1996, 9, 1).getTime(),
            new GregorianCalendar(1997, 0, 1).getTime(), new GregorianCalendar(1997,
            3, 1).getTime(), new GregorianCalendar(1997, 6, 1).getTime(),
            new GregorianCalendar(1997, 9, 1).getTime(), new GregorianCalendar(1998,
            0, 1).getTime(), new GregorianCalendar(1998, 3, 1).getTime(),
            new GregorianCalendar(1998, 6, 1).getTime(), new GregorianCalendar(1998,
            9, 1).getTime(), new GregorianCalendar(1999, 0, 1).getTime(),
            new GregorianCalendar(1999, 3, 1).getTime(), new GregorianCalendar(1999,
            6, 1).getTime(), new GregorianCalendar(1999, 9, 1).getTime(),
            new GregorianCalendar(2000, 0, 1).getTime(), new GregorianCalendar(2000,
            3, 1).getTime(), new GregorianCalendar(2000, 6, 1).getTime(),
            new GregorianCalendar(2000, 9, 1).getTime(), new GregorianCalendar(2001,
            0, 1).getTime(), new GregorianCalendar(2001, 3, 1).getTime(),
            new GregorianCalendar(2001, 6, 1).getTime(), new GregorianCalendar(2001,
            9, 1).getTime(), new GregorianCalendar(2002, 0, 1).getTime()};

        // 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
        XYChart c = new XYChart(500, 280, 0xffffcc, 0, 1);

        // 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 legendBox = c.addLegend(370, 45, true, "Arial Bold", 8);

        // Set the legend box background and border to transparent
        legendBox.setBackground(Chart.Transparent, Chart.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(Chart.StartOfYearFilter(), "{value|yyyy}",
            Chart.AllPassFilter(), "-");

        // Add a percentage area layer to the chart
        AreaLayer layer = c.addAreaLayer2(Chart.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(Chart.ReverseLegend);

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='{dataSetName} sales at {xLabel|yyyy} Q{=({xLabel|m}+2)/3|0}: " +
            "US${value}K ({percent}%)'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new percentarea();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/deptharea.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the area chart
double[] data0 = {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};
double[] data1 = {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};
double[] data2 = {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};
String[] labels = {"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
XYChart c = new 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(Chart.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
String chart1URL = c.makeSession(request, "chart1");

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName} load at hour {xLabel}: {value} MBytes'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Depth Area Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/deptharea.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class deptharea implements DemoModule
{
    //Name of demo program
    public String toString() { return "Depth Area Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the area chart
        double[] data0 = {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};
        double[] data1 = {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};
        double[] data2 = {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};
        String[] labels = {"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
        XYChart c = new 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(Chart.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
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='{dataSetName} load at hour {xLabel}: {value} MBytes'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new deptharea();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/rotatedarea.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the area chart
double[] data = {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
double[] labels = {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
XYChart c = new 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
String chart1URL = c.makeSession(request, "chart1");

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='Carbon dioxide concentration at {xLabel}: {value} ppm'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Rotated Area Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/rotatedarea.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class rotatedarea implements DemoModule
{
    //Name of demo program
    public String toString() { return "Rotated Area Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the area chart
        double[] data = {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
        double[] labels = {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
        XYChart c = new 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
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='Carbon dioxide concentration at {xLabel}: {value} ppm'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new rotatedarea();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/boxwhisker.jsp
<%@page import="ChartDirector.*" %>
<%
// Sample data for the Box-Whisker chart. Represents the minimum, 1st quartile,
// medium, 3rd quartile and maximum values of some quantities
double[] Q0Data = {40, 45, 40, 30, 20, 50, 25, 44};
double[] Q1Data = {55, 60, 50, 40, 38, 60, 51, 60};
double[] Q2Data = {62, 70, 60, 50, 48, 70, 62, 70};
double[] Q3Data = {70, 80, 65, 60, 53, 78, 69, 76};
double[] Q4Data = {80, 90, 75, 70, 60, 85, 80, 84};

// The labels for the chart
String[] labels = {"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
XYChart c = new 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
String chart1URL = c.makeSession(request, "chart1");

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{xLabel}: min/med/max = {min}/{med}/{max}\nInter-quartile range: " +
    "{bottom} to {top}'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Box-Whisker Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/boxwhisker.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class boxwhisker implements DemoModule
{
    //Name of demo program
    public String toString() { return "Box-Whisker Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // Sample data for the Box-Whisker chart. Represents the minimum, 1st
        // quartile, medium, 3rd quartile and maximum values of some quantities
        double[] Q0Data = {40, 45, 40, 30, 20, 50, 25, 44};
        double[] Q1Data = {55, 60, 50, 40, 38, 60, 51, 60};
        double[] Q2Data = {62, 70, 60, 50, 48, 70, 62, 70};
        double[] Q3Data = {70, 80, 65, 60, 53, 78, 69, 76};
        double[] Q4Data = {80, 90, 75, 70, 60, 85, 80, 84};

        // The labels for the chart
        String[] labels = {"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
        XYChart c = new 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
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='{xLabel}: min/med/max = {min}/{med}/{max} Inter-quartile " +
            "range: {bottom} to {top}'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new boxwhisker();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/boxwhisker2.jsp
<%@page import="ChartDirector.*" %>
<%
// Sample data for the Box-Whisker chart. Represents the minimum, 1st quartile,
// medium, 3rd quartile and maximum values of some quantities
double[] Q0Data = {40, 45, 35};
double[] Q1Data = {55, 60, 50};
double[] Q2Data = {62, 70, 60};
double[] Q3Data = {70, 80, 65};
double[] Q4Data = {80, 90, 75};

// The labels for the chart
String[] labels = {"<*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
XYChart c = new XYChart(540, 320);

// swap the x and y axes to create a horizontal box-whisker chart
c.swapXY();

//Set search path to current JSP directory for loading icon images
c.setSearchPath(getServletConfig().getServletContext(), request);

// 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
String chart1URL = c.makeSession(request, "chart1");

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{xLabel}: min/med/max = {min}/{med}/{max}\n Inter-quartile range: " +
    "{bottom} to {top}'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Horizontal Box-Whisker Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/boxwhisker2.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class boxwhisker2 implements DemoModule
{
    //Name of demo program
    public String toString() { return "Horizontal Box-Whisker Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // Sample data for the Box-Whisker chart. Represents the minimum, 1st
        // quartile, medium, 3rd quartile and maximum values of some quantities
        double[] Q0Data = {40, 45, 35};
        double[] Q1Data = {55, 60, 50};
        double[] Q2Data = {62, 70, 60};
        double[] Q3Data = {70, 80, 65};
        double[] Q4Data = {80, 90, 75};

        // The labels for the chart
        String[] labels = {"<*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
        XYChart c = new XYChart(540, 320);

        // swap the x and y axes to create a horizontal box-whisker chart
        c.swapXY();

        // 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
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='{xLabel}: min/med/max = {min}/{med}/{max}  Inter-quartile " +
            "range: {bottom} to {top}'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new boxwhisker2();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/floatingbox.jsp
<%@page import="ChartDirector.*" %>
<%
// Sample data for the Box-Whisker chart. Represents the minimum, 1st quartile,
// medium, 3rd quartile and maximum values of some quantities
double[] Q0Data = {40, 45, 40, 30, 20, 50, 25, 44};
double[] Q1Data = {55, 60, 50, 40, 38, 60, 51, 60};
double[] Q2Data = {62, 70, 60, 50, 48, 70, 62, 70};
double[] Q3Data = {70, 80, 65, 60, 53, 78, 69, 76};
double[] Q4Data = {80, 90, 75, 70, 60, 85, 80, 84};

// The labels for the chart
String[] labels = {"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
XYChart c = new 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
LegendBox b = c.addLegend(50 + 225, 22, false, "Arial Bold", 10);
b.setAlignment(Chart.TopCenter);
b.setBackground(Chart.Transparent);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{xLabel} ({dataSetName}): {bottom} to {top} points'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Floating Box Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/floatingbox.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class floatingbox implements DemoModule
{
    //Name of demo program
    public String toString() { return "Floating Box Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // Sample data for the Box-Whisker chart. Represents the minimum, 1st
        // quartile, medium, 3rd quartile and maximum values of some quantities
        double[] Q0Data = {40, 45, 40, 30, 20, 50, 25, 44};
        double[] Q1Data = {55, 60, 50, 40, 38, 60, 51, 60};
        double[] Q2Data = {62, 70, 60, 50, 48, 70, 62, 70};
        double[] Q3Data = {70, 80, 65, 60, 53, 78, 69, 76};
        double[] Q4Data = {80, 90, 75, 70, 60, 85, 80, 84};

        // The labels for the chart
        String[] labels = {"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
        XYChart c = new 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
        LegendBox b = c.addLegend(50 + 225, 22, false, "Arial Bold", 10);
        b.setAlignment(Chart.TopCenter);
        b.setBackground(Chart.Transparent);

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='{xLabel} ({dataSetName}): {bottom} to {top} points'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new floatingbox();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/waterfall.jsp
<%@page import="ChartDirector.*" %>
<%
// 4 data points to represent the cash flow for the Q1 - Q4
double[] data = {230, 140, 220, 330, 150};

// We want to plot a waterfall chart showing the 4 quarters as well as the total
String[] labels = {"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).
double[] boxTop = new 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.
double[] boxBottom = new ArrayMath(boxTop).shift(1, 0).result();

// The last point (total) is different. Its bottom side is always 0.
boxBottom[boxBottom.length - 1] = 0;

// Create a XYChart object of size 500 x 280 pixels. Set background color to light
// blue (ccccff), with 1 pixel 3D border effect.
XYChart c = new 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
BoxWhiskerLayer 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(Chart.Center);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{xLabel}: {={top}-{bottom}} millions'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Waterfall Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/waterfall.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class waterfall implements DemoModule
{
    //Name of demo program
    public String toString() { return "Waterfall Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // 4 data points to represent the cash flow for the Q1 - Q4
        double[] data = {230, 140, 220, 330, 150};

        // We want to plot a waterfall chart showing the 4 quarters as well as the
        // total
        String[] labels = {"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).
        double[] boxTop = new 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.
        double[] boxBottom = new ArrayMath(boxTop).shift(1, 0).result();

        // The last point (total) is different. Its bottom side is always 0.
        boxBottom[boxBottom.length - 1] = 0;

        // Create a XYChart object of size 500 x 280 pixels. Set background color to
        // light blue (ccccff), with 1 pixel 3D border effect.
        XYChart c = new 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
        BoxWhiskerLayer 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(Chart.Center);

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='{xLabel}: {={top}-{bottom}} millions'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new waterfall();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/posnegwaterfall.jsp
<%@page import="ChartDirector.*" %>
<%
// 4 data points to represent the cash flow for the Q1 - Q4
double[] data = {230, -140, 220, 330};

// We want to plot a waterfall chart showing the 4 quarters as well as the total
String[] labels = {"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).
double[] boxTop = new ArrayMath(data).insert2(0, 1, data.length).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.
double[] boxBottom = new ArrayMath(boxTop).shift(1, 0).result();

// The last point (total) is different. Its bottom side is always 0.
boxBottom[boxBottom.length - 1] = 0;

// In this example, we want to use different colors depending on the data is positive
// or negative.
int posColor = 0x00ff00;
int 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.
XYChart c = new 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.
LegendBox b = c.addLegend(55, 25, false, "Arial Bold", 8);
b.setBackground(Chart.Transparent, Chart.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
BoxWhiskerLayer layer = c.addBoxWhiskerLayer(boxTop, boxBottom);

// Color the bars depending on whether it is positive or negative
for (int i = 0; i < boxTop.length; ++i) {
    if (boxTop[i] >= boxBottom[i]) {
        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(Chart.Center);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{xLabel}: {={top}-{bottom}} millions'");
%>
<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 color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/posnegwaterfall.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class posnegwaterfall implements DemoModule
{
    //Name of demo program
    public String toString() { return "Pos/Neg Waterfall Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // 4 data points to represent the cash flow for the Q1 - Q4
        double[] data = {230, -140, 220, 330};

        // We want to plot a waterfall chart showing the 4 quarters as well as the
        // total
        String[] labels = {"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).
        double[] boxTop = new ArrayMath(data).insert2(0, 1, data.length).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.
        double[] boxBottom = new ArrayMath(boxTop).shift(1, 0).result();

        // The last point (total) is different. Its bottom side is always 0.
        boxBottom[boxBottom.length - 1] = 0;

        // In this example, we want to use different colors depending on the data is
        // positive or negative.
        int posColor = 0x00ff00;
        int 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.
        XYChart c = new 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.
        LegendBox b = c.addLegend(55, 25, false, "Arial Bold", 8);
        b.setBackground(Chart.Transparent, Chart.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
        BoxWhiskerLayer layer = c.addBoxWhiskerLayer(boxTop, boxBottom);

        // Color the bars depending on whether it is positive or negative
        for (int i = 0; i < boxTop.length; ++i) {
            if (boxTop[i] >= boxBottom[i]) {
                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(Chart.Center);

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='{xLabel}: {={top}-{bottom}} millions'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new posnegwaterfall();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/gantt.jsp
<%@page import="ChartDirector.*" %>
<%@page import="java.util.*" %>
<%
// data for the gantt chart, representing the start date, end date and names for
// various activities
Date[] startDate = {new GregorianCalendar(2004, 7, 16).getTime(),
    new GregorianCalendar(2004, 7, 30).getTime(), new GregorianCalendar(2004, 8, 13
    ).getTime(), new GregorianCalendar(2004, 8, 20).getTime(), new GregorianCalendar(
    2004, 8, 27).getTime(), new GregorianCalendar(2004, 9, 4).getTime(),
    new GregorianCalendar(2004, 9, 25).getTime(), new GregorianCalendar(2004, 10, 1
    ).getTime(), new GregorianCalendar(2004, 10, 8).getTime()};
Date[] endDate = {new GregorianCalendar(2004, 7, 30).getTime(),
    new GregorianCalendar(2004, 8, 13).getTime(), new GregorianCalendar(2004, 8, 27
    ).getTime(), new GregorianCalendar(2004, 9, 4).getTime(), new GregorianCalendar(
    2004, 9, 11).getTime(), new GregorianCalendar(2004, 10, 8).getTime(),
    new GregorianCalendar(2004, 10, 8).getTime(), new GregorianCalendar(2004, 10, 22
    ).getTime(), new GregorianCalendar(2004, 10, 22).getTime()};
String[] labels = {"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.
XYChart c = new 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, Chart.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(new GregorianCalendar(2004, 7, 16).getTime(),
    new GregorianCalendar(2004, 10, 22).getTime(), 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(Chart.StartOfMonthFilter(),
    "<*font=Arial Bold*>{value|mmm d}", Chart.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(Chart.CTime(startDate), Chart.CTime(endDate), null, null, null,
    0x00cc00, Chart.SameAsMainColor, Chart.SameAsMainColor);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{xLabel}: {top|mmm dd, yyyy} to {bottom|mmm dd, yyyy}'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Simple Gantt Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/gantt.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import ChartDirector.*;

public class gantt implements DemoModule
{
    //Name of demo program
    public String toString() { return "Simple Gantt Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // data for the gantt chart, representing the start date, end date and names
        // for various activities
        Date[] startDate = {new GregorianCalendar(2004, 7, 16).getTime(),
            new GregorianCalendar(2004, 7, 30).getTime(), new GregorianCalendar(2004,
            8, 13).getTime(), new GregorianCalendar(2004, 8, 20).getTime(),
            new GregorianCalendar(2004, 8, 27).getTime(), new GregorianCalendar(2004,
            9, 4).getTime(), new GregorianCalendar(2004, 9, 25).getTime(),
            new GregorianCalendar(2004, 10, 1).getTime(), new GregorianCalendar(2004,
            10, 8).getTime()};
        Date[] endDate = {new GregorianCalendar(2004, 7, 30).getTime(),
            new GregorianCalendar(2004, 8, 13).getTime(), new GregorianCalendar(2004,
            8, 27).getTime(), new GregorianCalendar(2004, 9, 4).getTime(),
            new GregorianCalendar(2004, 9, 11).getTime(), new GregorianCalendar(2004,
            10, 8).getTime(), new GregorianCalendar(2004, 10, 8).getTime(),
            new GregorianCalendar(2004, 10, 22).getTime(), new GregorianCalendar(
            2004, 10, 22).getTime()};
        String[] labels = {"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.
        XYChart c = new 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, Chart.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(new GregorianCalendar(2004, 7, 16).getTime(),
            new GregorianCalendar(2004, 10, 22).getTime(), 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(Chart.StartOfMonthFilter(),
            "<*font=Arial Bold*>{value|mmm d}", Chart.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(Chart.CTime(startDate), Chart.CTime(endDate), null,
            null, null, 0x00cc00, Chart.SameAsMainColor, Chart.SameAsMainColor);

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='{xLabel}: {top|mmm dd, yyyy} to {bottom|mmm dd, yyyy}'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new gantt();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/colorgantt.jsp
<%@page import="ChartDirector.*" %>
<%@page import="java.util.*" %>
<%
// The tasks for the gantt chart
String[] labels = {"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
double[] taskNo = {0, 0, 1, 2, 3, 4, 5, 6, 6, 7, 8, 8};
Date[] startDate = {new GregorianCalendar(2004, 7, 16).getTime(),
    new GregorianCalendar(2004, 9, 4).getTime(), new GregorianCalendar(2004, 7, 30
    ).getTime(), new GregorianCalendar(2004, 8, 13).getTime(), new GregorianCalendar(
    2004, 8, 20).getTime(), new GregorianCalendar(2004, 8, 27).getTime(),
    new GregorianCalendar(2004, 9, 4).getTime(), new GregorianCalendar(2004, 9, 4
    ).getTime(), new GregorianCalendar(2004, 9, 25).getTime(), new GregorianCalendar(
    2004, 10, 1).getTime(), new GregorianCalendar(2004, 9, 18).getTime(),
    new GregorianCalendar(2004, 10, 8).getTime()};
Date[] endDate = {new GregorianCalendar(2004, 7, 30).getTime(),
    new GregorianCalendar(2004, 9, 18).getTime(), new GregorianCalendar(2004, 8, 13
    ).getTime(), new GregorianCalendar(2004, 8, 27).getTime(), new GregorianCalendar(
    2004, 9, 4).getTime(), new GregorianCalendar(2004, 9, 11).getTime(),
    new GregorianCalendar(2004, 10, 8).getTime(), new GregorianCalendar(2004, 9, 18
    ).getTime(), new GregorianCalendar(2004, 10, 8).getTime(), new GregorianCalendar(
    2004, 10, 22).getTime(), new GregorianCalendar(2004, 10, 1).getTime(),
    new GregorianCalendar(2004, 10, 22).getTime()};
int[] colors = {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.
XYChart c = new 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, Chart.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(new GregorianCalendar(2004, 7, 16).getTime(),
    new GregorianCalendar(2004, 10, 22).getTime(), 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(Chart.StartOfMonthFilter(),
    "<*font=Arial Bold*>{value|mmm d}", Chart.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(new double[]{1}, Chart.CTime(new Date[]{new GregorianCalendar(2004,
    8, 13).getTime()}), "Milestone 1", Chart.Cross2Shape(), 13, 0xffff00
    ).setHTMLImageMap("{disable}");
c.addScatterLayer(new double[]{3}, Chart.CTime(new Date[]{new GregorianCalendar(2004,
    9, 4).getTime()}), "Milestone 2", Chart.StarShape(5), 15, 0xff00ff
    ).setHTMLImageMap("{disable}");
c.addScatterLayer(new double[]{5}, Chart.CTime(new Date[]{new GregorianCalendar(2004,
    10, 8).getTime()}), "Milestone 3", Chart.TriangleSymbol, 13, 0xff9933
    ).setHTMLImageMap("{disable}");

// Add a multi-color box-whisker layer to represent the gantt bars
BoxWhiskerLayer layer = c.addBoxWhiskerLayer2(Chart.CTime(startDate),
    Chart.CTime(endDate), null, null, null, colors);
layer.setXData(taskNo);
layer.setBorderColor(Chart.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 / (labels.length)));

// 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 legendBox = c.addLegend2(140, 265, Chart.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
String chart1URL = c.makeSession(request, "chart1");

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{xLabel}: {top|mmm dd, yyyy} to {bottom|mmm dd, yyyy}'");
%>
<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 color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/colorgantt.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import ChartDirector.*;

public class colorgantt implements DemoModule
{
    //Name of demo program
    public String toString() { return "Multi-Color Gantt Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The tasks for the gantt chart
        String[] labels = {"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
        double[] taskNo = {0, 0, 1, 2, 3, 4, 5, 6, 6, 7, 8, 8};
        Date[] startDate = {new GregorianCalendar(2004, 7, 16).getTime(),
            new GregorianCalendar(2004, 9, 4).getTime(), new GregorianCalendar(2004,
            7, 30).getTime(), new GregorianCalendar(2004, 8, 13).getTime(),
            new GregorianCalendar(2004, 8, 20).getTime(), new GregorianCalendar(2004,
            8, 27).getTime(), new GregorianCalendar(2004, 9, 4).getTime(),
            new GregorianCalendar(2004, 9, 4).getTime(), new GregorianCalendar(2004,
            9, 25).getTime(), new GregorianCalendar(2004, 10, 1).getTime(),
            new GregorianCalendar(2004, 9, 18).getTime(), new GregorianCalendar(2004,
            10, 8).getTime()};
        Date[] endDate = {new GregorianCalendar(2004, 7, 30).getTime(),
            new GregorianCalendar(2004, 9, 18).getTime(), new GregorianCalendar(2004,
            8, 13).getTime(), new GregorianCalendar(2004, 8, 27).getTime(),
            new GregorianCalendar(2004, 9, 4).getTime(), new GregorianCalendar(2004,
            9, 11).getTime(), new GregorianCalendar(2004, 10, 8).getTime(),
            new GregorianCalendar(2004, 9, 18).getTime(), new GregorianCalendar(2004,
            10, 8).getTime(), new GregorianCalendar(2004, 10, 22).getTime(),
            new GregorianCalendar(2004, 10, 1).getTime(), new GregorianCalendar(2004,
            10, 22).getTime()};
        int[] colors = {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.
        XYChart c = new 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, Chart.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(new GregorianCalendar(2004, 7, 16).getTime(),
            new GregorianCalendar(2004, 10, 22).getTime(), 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(Chart.StartOfMonthFilter(),
            "<*font=Arial Bold*>{value|mmm d}", Chart.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(new double[]{1}, Chart.CTime(new Date[]{
            new GregorianCalendar(2004, 8, 13).getTime()}), "Milestone 1",
            Chart.Cross2Shape(), 13, 0xffff00).setHTMLImageMap("{disable}");
        c.addScatterLayer(new double[]{3}, Chart.CTime(new Date[]{
            new GregorianCalendar(2004, 9, 4).getTime()}), "Milestone 2",
            Chart.StarShape(5), 15, 0xff00ff).setHTMLImageMap("{disable}");
        c.addScatterLayer(new double[]{5}, Chart.CTime(new Date[]{
            new GregorianCalendar(2004, 10, 8).getTime()}), "Milestone 3",
            Chart.TriangleSymbol, 13, 0xff9933).setHTMLImageMap("{disable}");

        // Add a multi-color box-whisker layer to represent the gantt bars
        BoxWhiskerLayer layer = c.addBoxWhiskerLayer2(Chart.CTime(startDate),
            Chart.CTime(endDate), null, null, null, colors);
        layer.setXData(taskNo);
        layer.setBorderColor(Chart.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 / (labels.length)));

        // 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 legendBox = c.addLegend2(140, 265, Chart.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
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='{xLabel}: {top|mmm dd, yyyy} to {bottom|mmm dd, yyyy}'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new colorgantt();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/layergantt.jsp
<%@page import="ChartDirector.*" %>
<%@page import="java.util.*" %>
<%
// the names of the tasks
String[] labels = {"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
Date[] startDate = {new GregorianCalendar(2004, 7, 16).getTime(),
    new GregorianCalendar(2004, 7, 30).getTime(), new GregorianCalendar(2004, 8, 13
    ).getTime(), new GregorianCalendar(2004, 8, 20).getTime(), new GregorianCalendar(
    2004, 8, 27).getTime(), new GregorianCalendar(2004, 9, 4).getTime(),
    new GregorianCalendar(2004, 9, 25).getTime(), new GregorianCalendar(2004, 10, 1
    ).getTime(), new GregorianCalendar(2004, 10, 8).getTime()};
Date[] endDate = {new GregorianCalendar(2004, 7, 30).getTime(),
    new GregorianCalendar(2004, 8, 13).getTime(), new GregorianCalendar(2004, 8, 27
    ).getTime(), new GregorianCalendar(2004, 9, 4).getTime(), new GregorianCalendar(
    2004, 9, 11).getTime(), new GregorianCalendar(2004, 10, 8).getTime(),
    new GregorianCalendar(2004, 10, 8).getTime(), new GregorianCalendar(2004, 10, 22
    ).getTime(), new GregorianCalendar(2004, 10, 22).getTime()};

// the actual start dates and end dates for the tasks up to now
Date[] actualStartDate = {new GregorianCalendar(2004, 7, 16).getTime(),
    new GregorianCalendar(2004, 7, 27).getTime(), new GregorianCalendar(2004, 8, 9
    ).getTime(), new GregorianCalendar(2004, 8, 18).getTime(), new GregorianCalendar(
    2004, 8, 22).getTime()};
Date[] actualEndDate = {new GregorianCalendar(2004, 7, 27).getTime(),
    new GregorianCalendar(2004, 8, 9).getTime(), new GregorianCalendar(2004, 8, 27
    ).getTime(), new GregorianCalendar(2004, 9, 2).getTime(), new GregorianCalendar(
    2004, 9, 8).getTime()};

// Create a XYChart object of size 620 x 280 pixels. Set background color to light
// green (ccffcc) with 1 pixel 3D border effect.
XYChart c = new 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("Multi-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, Chart.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(new GregorianCalendar(2004, 7, 16).getTime(),
    new GregorianCalendar(2004, 10, 22).getTime(), 86400 * 7);

// Add a red (ff0000) dash line to represent the current day
c.yAxis().addMark(Chart.CTime(new GregorianCalendar(2004, 9, 8).getTime()),
    c.dashLineColor(0xff0000, Chart.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(Chart.StartOfMonthFilter(),
    "<*font=Arial Bold*>{value|mmm d}", Chart.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
int 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.
int actualColor = c.patternColor(new int[]{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.
BoxWhiskerLayer actualLayer = c.addBoxLayer(Chart.CTime(actualStartDate),
    Chart.CTime(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(Chart.CTime(startDate), Chart.CTime(endDate), plannedColor, "Planned"
    ).setBorderColor(Chart.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.
LegendBox b = c.addLegend(595, 60, false, "Arial Bold", 8);
b.setAlignment(Chart.TopRight);
b.setBackground(0x80808080, -1, 2);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{xLabel} ({dataSetName}): {top|mmm dd, yyyy} to {bottom|mmm dd, yyyy}'");
%>
<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 color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/layergantt.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import ChartDirector.*;

public class layergantt implements DemoModule
{
    //Name of demo program
    public String toString() { return "Multi-Layer Gantt Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // the names of the tasks
        String[] labels = {"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
        Date[] startDate = {new GregorianCalendar(2004, 7, 16).getTime(),
            new GregorianCalendar(2004, 7, 30).getTime(), new GregorianCalendar(2004,
            8, 13).getTime(), new GregorianCalendar(2004, 8, 20).getTime(),
            new GregorianCalendar(2004, 8, 27).getTime(), new GregorianCalendar(2004,
            9, 4).getTime(), new GregorianCalendar(2004, 9, 25).getTime(),
            new GregorianCalendar(2004, 10, 1).getTime(), new GregorianCalendar(2004,
            10, 8).getTime()};
        Date[] endDate = {new GregorianCalendar(2004, 7, 30).getTime(),
            new GregorianCalendar(2004, 8, 13).getTime(), new GregorianCalendar(2004,
            8, 27).getTime(), new GregorianCalendar(2004, 9, 4).getTime(),
            new GregorianCalendar(2004, 9, 11).getTime(), new GregorianCalendar(2004,
            10, 8).getTime(), new GregorianCalendar(2004, 10, 8).getTime(),
            new GregorianCalendar(2004, 10, 22).getTime(), new GregorianCalendar(
            2004, 10, 22).getTime()};

        // the actual start dates and end dates for the tasks up to now
        Date[] actualStartDate = {new GregorianCalendar(2004, 7, 16).getTime(),
            new GregorianCalendar(2004, 7, 27).getTime(), new GregorianCalendar(2004,
            8, 9).getTime(), new GregorianCalendar(2004, 8, 18).getTime(),
            new GregorianCalendar(2004, 8, 22).getTime()};
        Date[] actualEndDate = {new GregorianCalendar(2004, 7, 27).getTime(),
            new GregorianCalendar(2004, 8, 9).getTime(), new GregorianCalendar(2004,
            8, 27).getTime(), new GregorianCalendar(2004, 9, 2).getTime(),
            new GregorianCalendar(2004, 9, 8).getTime()};

        // Create a XYChart object of size 620 x 280 pixels. Set background color to
        // light green (ccffcc) with 1 pixel 3D border effect.
        XYChart c = new 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("Multi-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, Chart.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(new GregorianCalendar(2004, 7, 16).getTime(),
            new GregorianCalendar(2004, 10, 22).getTime(), 86400 * 7);

        // Add a red (ff0000) dash line to represent the current day
        c.yAxis().addMark(Chart.CTime(new GregorianCalendar(2004, 9, 8).getTime()),
            c.dashLineColor(0xff0000, Chart.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(Chart.StartOfMonthFilter(),
            "<*font=Arial Bold*>{value|mmm d}", Chart.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
        int 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.
        int actualColor = c.patternColor(new int[]{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.
        BoxWhiskerLayer actualLayer = c.addBoxLayer(Chart.CTime(actualStartDate),
            Chart.CTime(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(Chart.CTime(startDate), Chart.CTime(endDate), plannedColor,
            "Planned").setBorderColor(Chart.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.
        LegendBox b = c.addLegend(595, 60, false, "Arial Bold", 8);
        b.setAlignment(Chart.TopRight);
        b.setBackground(0x80808080, -1, 2);

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='{xLabel} ({dataSetName}): {top|mmm dd, yyyy} to {bottom|mmm " +
            "dd, yyyy}'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new layergantt();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


Contour Charts/Heat Maps

Contour Charts/Heat Maps

Title | Description
Contour Chart | Demonstrates creating a contour chart.
Continuous Contour Coloring | Demonstrates continuous coloring of the contour layer.
Scattered Data Contour Chart | Demonstrates using scattered data for the contour layer.
Contour Interpolation | Demonstrates spline and linear surface interpolation, and discrete and continuous coloring.


Contour Chart

Contour Chart

This example demonstrates creating a contour chart.

  • The contour chart is created by adding a contour layer to the chart using XYChart.addContourLayer.

  • By default, grid lines are drawn at the background of the plot area and so are behind all chart layers. In this example, PlotArea.moveGridBefore is used to move the grid lines in front of the contour layer.

  • The color axis (visually represented as the color legend) is positioned vertically to the right of the plot area using ContourLayer.setColorAxis.

Source Code Listing

[JSP Version] jspdemo/contour.jsp
<%@page import="ChartDirector.*" %>
<%
// The x and y coordinates of the grid
double[] dataX = {-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8,
    9, 10};
double[] dataY = {-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8,
    9, 10};

// The values at the grid points. In this example, we will compute the values using
// the formula z = x * sin(y) + y * sin(x).
double[] dataZ = new double[(dataX.length) * (dataY.length)];
for (int yIndex = 0; yIndex < dataY.length; ++yIndex) {
    double y = dataY[yIndex];
    for (int xIndex = 0; xIndex < dataX.length; ++xIndex) {
        double x = dataX[xIndex];
        dataZ[yIndex * (dataX.length) + xIndex] = x * Math.sin(y) + y * Math.sin(x);
    }
}

// Create a XYChart object of size 600 x 500 pixels
XYChart c = new XYChart(600, 500);

// Add a title to the chart using 15 points Arial Bold Italic font
c.addTitle("z = x * sin(y) + y * sin(x)      ", "Arial Bold Italic", 15);

// Set the plotarea at (75, 40) and of size 400 x 400 pixels. Use semi-transparent
// black (80000000) dotted lines for both horizontal and vertical grid lines
c.setPlotArea(75, 40, 400, 400, -1, -1, -1, c.dashLineColor(0x80000000, Chart.DotLine
    ), -1);

// Set x-axis and y-axis title using 12 points Arial Bold Italic font
c.xAxis().setTitle("X-Axis Title Place Holder", "Arial Bold Italic", 12);
c.yAxis().setTitle("Y-Axis Title Place Holder", "Arial Bold Italic", 12);

// Set x-axis and y-axis labels to use Arial Bold font
c.xAxis().setLabelStyle("Arial Bold");
c.yAxis().setLabelStyle("Arial Bold");

// When auto-scaling, use tick spacing of 40 pixels as a guideline
c.yAxis().setTickDensity(40);
c.xAxis().setTickDensity(40);

// Add a contour layer using the given data
ContourLayer layer = c.addContourLayer(dataX, dataY, dataZ);

// Move the grid lines in front of the contour layer
c.getPlotArea().moveGridBefore(layer);

// Add a color axis (the legend) in which the top left corner is anchored at (505,
// 40). Set the length to 400 pixels and the labels on the right side.
ColorAxis cAxis = layer.setColorAxis(505, 40, Chart.TopLeft, 400, Chart.Right);

// Add a title to the color axis using 12 points Arial Bold Italic font
cAxis.setTitle("Color Legend Title Place Holder", "Arial Bold Italic", 12);

// Set color axis labels to use Arial Bold font
cAxis.setLabelStyle("Arial Bold");

// Output the chart
String chart1URL = c.makeSession(request, "chart1");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Contour Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'>
</body>
</html>

[Java Version] javademo/contour.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class contour implements DemoModule
{
    //Name of demo program
    public String toString() { return "Contour Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The x and y coordinates of the grid
        double[] dataX = {-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5,
            6, 7, 8, 9, 10};
        double[] dataY = {-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5,
            6, 7, 8, 9, 10};

        // The values at the grid points. In this example, we will compute the values
        // using the formula z = x * sin(y) + y * sin(x).
        double[] dataZ = new double[(dataX.length) * (dataY.length)];
        for (int yIndex = 0; yIndex < dataY.length; ++yIndex) {
            double y = dataY[yIndex];
            for (int xIndex = 0; xIndex < dataX.length; ++xIndex) {
                double x = dataX[xIndex];
                dataZ[yIndex * (dataX.length) + xIndex] = x * Math.sin(y) + y *
                    Math.sin(x);
            }
        }

        // Create a XYChart object of size 600 x 500 pixels
        XYChart c = new XYChart(600, 500);

        // Add a title to the chart using 15 points Arial Bold Italic font
        c.addTitle("z = x * sin(y) + y * sin(x)      ", "Arial Bold Italic", 15);

        // Set the plotarea at (75, 40) and of size 400 x 400 pixels. Use
        // semi-transparent black (80000000) dotted lines for both horizontal and
        // vertical grid lines
        c.setPlotArea(75, 40, 400, 400, -1, -1, -1, c.dashLineColor(0x80000000,
            Chart.DotLine), -1);

        // Set x-axis and y-axis title using 12 points Arial Bold Italic font
        c.xAxis().setTitle("X-Axis Title Place Holder", "Arial Bold Italic", 12);
        c.yAxis().setTitle("Y-Axis Title Place Holder", "Arial Bold Italic", 12);

        // Set x-axis and y-axis labels to use Arial Bold font
        c.xAxis().setLabelStyle("Arial Bold");
        c.yAxis().setLabelStyle("Arial Bold");

        // When auto-scaling, use tick spacing of 40 pixels as a guideline
        c.yAxis().setTickDensity(40);
        c.xAxis().setTickDensity(40);

        // Add a contour layer using the given data
        ContourLayer layer = c.addContourLayer(dataX, dataY, dataZ);

        // Move the grid lines in front of the contour layer
        c.getPlotArea().moveGridBefore(layer);

        // Add a color axis (the legend) in which the top left corner is anchored at
        // (505, 40). Set the length to 400 pixels and the labels on the right side.
        ColorAxis cAxis = layer.setColorAxis(505, 40, Chart.TopLeft, 400, Chart.Right
            );

        // Add a title to the color axis using 12 points Arial Bold Italic font
        cAxis.setTitle("Color Legend Title Place Holder", "Arial Bold Italic", 12);

        // Set color axis labels to use Arial Bold font
        cAxis.setLabelStyle("Arial Bold");

        // Output the chart
        viewer.setChart(c);
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new contour();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


Continuous Contour Coloring

Continuous Contour Coloring

This example demonstrates continuous coloring of the contour layer.

By default, a contour layer will be discretely colored, which means the color will change in discrete steps according to the z level. In continuous coloring, the color will change continuously according to the z level. Continuous coloring can be enabled using ColorAxis.setColorGradient.

Source Code Listing

[JSP Version] jspdemo/smoothcontour.jsp
<%@page import="ChartDirector.*" %>
<%
// The x and y coordinates of the grid
double[] dataX = {-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8,
    9, 10};
double[] dataY = {-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8,
    9, 10};

// The values at the grid points. In this example, we will compute the values using
// the formula z = Sin(x / 2) * Sin(y / 2).
double[] dataZ = new double[(dataX.length) * (dataY.length)];
for (int yIndex = 0; yIndex < dataY.length; ++yIndex) {
    double y = dataY[yIndex];
    for (int xIndex = 0; xIndex < dataX.length; ++xIndex) {
        double x = dataX[xIndex];
        dataZ[yIndex * (dataX.length) + xIndex] = Math.sin(x / 2.0) * Math.sin(y /
            2.0);
    }
}

// Create a XYChart object of size 600 x 500 pixels
XYChart c = new XYChart(600, 500);

// Add a title to the chart using 18 points Times New Roman Bold Italic font
c.addTitle("Nano Lattice Twister Field Intensity        ",
    "Times New Roman Bold Italic", 18);

// Set the plotarea at (75, 40) and of size 400 x 400 pixels. Use semi-transparent
// black (80000000) dotted lines for both horizontal and vertical grid lines
c.setPlotArea(75, 40, 400, 400, -1, -1, -1, c.dashLineColor(0x80000000, Chart.DotLine
    ), -1);

// Set x-axis and y-axis title using 12 points Arial Bold Italic font
c.xAxis().setTitle("Lattice X Direction (nm)", "Arial Bold Italic", 12);
c.yAxis().setTitle("Lattice Y Direction (nm)", "Arial Bold Italic", 12);

// Set x-axis and y-axis labels to use Arial Bold font
c.xAxis().setLabelStyle("Arial Bold");
c.yAxis().setLabelStyle("Arial Bold");

// When auto-scaling, use tick spacing of 40 pixels as a guideline
c.yAxis().setTickDensity(40);
c.xAxis().setTickDensity(40);

// Add a contour layer using the given data
ContourLayer layer = c.addContourLayer(dataX, dataY, dataZ);

// Set the contour color to transparent
layer.setContourColor(Chart.Transparent);

// Move the grid lines in front of the contour layer
c.getPlotArea().moveGridBefore(layer);

// Add a color axis (the legend) in which the left center point is anchored at (495,
// 240). Set the length to 370 pixels and the labels on the right side.
ColorAxis cAxis = layer.setColorAxis(495, 240, Chart.Left, 370, Chart.Right);

// Add a bounding box to the color axis using light grey (eeeeee) as the background
// and dark grey (444444) as the border.
cAxis.setBoundingBox(0xeeeeee, 0x444444);

// Add a title to the color axis using 12 points Arial Bold Italic font
cAxis.setTitle("Twist Pressure (Twist-Volt)", "Arial Bold Italic", 12);

// Set color axis labels to use Arial Bold font
cAxis.setLabelStyle("Arial Bold");

// Use smooth gradient coloring
cAxis.setColorGradient(true);

// Output the chart
String chart1URL = c.makeSession(request, "chart1", Chart.JPG);
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Continuous Contour Coloring
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'>
</body>
</html>

[Java Version] javademo/smoothcontour.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class smoothcontour implements DemoModule
{
    //Name of demo program
    public String toString() { return "Continuous Contour Coloring"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The x and y coordinates of the grid
        double[] dataX = {-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5,
            6, 7, 8, 9, 10};
        double[] dataY = {-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5,
            6, 7, 8, 9, 10};

        // The values at the grid points. In this example, we will compute the values
        // using the formula z = Sin(x / 2) * Sin(y / 2).
        double[] dataZ = new double[(dataX.length) * (dataY.length)];
        for (int yIndex = 0; yIndex < dataY.length; ++yIndex) {
            double y = dataY[yIndex];
            for (int xIndex = 0; xIndex < dataX.length; ++xIndex) {
                double x = dataX[xIndex];
                dataZ[yIndex * (dataX.length) + xIndex] = Math.sin(x / 2.0) *
                    Math.sin(y / 2.0);
            }
        }

        // Create a XYChart object of size 600 x 500 pixels
        XYChart c = new XYChart(600, 500);

        // Add a title to the chart using 18 points Times New Roman Bold Italic font
        c.addTitle("Nano Lattice Twister Field Intensity        ",
            "Times New Roman Bold Italic", 18);

        // Set the plotarea at (75, 40) and of size 400 x 400 pixels. Use
        // semi-transparent black (80000000) dotted lines for both horizontal and
        // vertical grid lines
        c.setPlotArea(75, 40, 400, 400, -1, -1, -1, c.dashLineColor(0x80000000,
            Chart.DotLine), -1);

        // Set x-axis and y-axis title using 12 points Arial Bold Italic font
        c.xAxis().setTitle("Lattice X Direction (nm)", "Arial Bold Italic", 12);
        c.yAxis().setTitle("Lattice Y Direction (nm)", "Arial Bold Italic", 12);

        // Set x-axis and y-axis labels to use Arial Bold font
        c.xAxis().setLabelStyle("Arial Bold");
        c.yAxis().setLabelStyle("Arial Bold");

        // When auto-scaling, use tick spacing of 40 pixels as a guideline
        c.yAxis().setTickDensity(40);
        c.xAxis().setTickDensity(40);

        // Add a contour layer using the given data
        ContourLayer layer = c.addContourLayer(dataX, dataY, dataZ);

        // Set the contour color to transparent
        layer.setContourColor(Chart.Transparent);

        // Move the grid lines in front of the contour layer
        c.getPlotArea().moveGridBefore(layer);

        // Add a color axis (the legend) in which the left center point is anchored
        // at (495, 240). Set the length to 370 pixels and the labels on the right
        // side.
        ColorAxis cAxis = layer.setColorAxis(495, 240, Chart.Left, 370, Chart.Right);

        // Add a bounding box to the color axis using light grey (eeeeee) as the
        // background and dark grey (444444) as the border.
        cAxis.setBoundingBox(0xeeeeee, 0x444444);

        // Add a title to the color axis using 12 points Arial Bold Italic font
        cAxis.setTitle("Twist Pressure (Twist-Volt)", "Arial Bold Italic", 12);

        // Set color axis labels to use Arial Bold font
        cAxis.setLabelStyle("Arial Bold");

        // Use smooth gradient coloring
        cAxis.setColorGradient(true);

        // Output the chart
        viewer.setChart(c);
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new smoothcontour();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


Scattered Data Contour Chart

Scattered Data Contour Chart

This example demonstrates using scattered data for the contour layer.

In previous contour chart examples, the data are gridded, which means the data points lie on a rectangular grid.

ChartDirector also supports scattered data points, which means the data points can be at arbitrary positions. In this example, in additional to a contour layer added using XYChart.addContourLayer, there is also a scatter layer added using XYChart.addScatterLayer to show the positions of the data points.

Source Code Listing

[JSP Version] jspdemo/scattercontour.jsp
<%@page import="ChartDirector.*" %>
<%
// The (x, y, z) coordinates of the scattered data
double[] dataX = {0.5, 1.9, 4.9, 1.0, 8.9, 9.8, 5.9, 2.9, 6.8, 9.0, 0.0, 8.9, 1.9,
    4.8, 2.4, 3.4, 7.9, 7.5, 4.8, 7.5, 9.5, 0.4, 8.9, 0.9, 5.4, 9.4, 2.9, 8.9, 0.9,
    8.9, 10.0, 1.0, 6.8, 3.8, 9.0, 5.3, 6.4, 4.9, 4.5, 2.0, 5.4, 0.0, 10.0, 3.9, 5.4,
    5.9, 5.8, 0.3, 4.4, 8.3};
double[] dataY = {3.3, 3.0, 0.7, 1.0, 9.3, 4.5, 8.4, 0.1, 0.8, 0.1, 9.3, 1.8, 4.3,
    1.3, 2.3, 5.4, 6.9, 9.0, 9.8, 7.5, 1.8, 1.4, 4.5, 7.8, 3.8, 4.0, 2.9, 2.4, 3.9,
    2.9, 2.3, 9.3, 2.0, 3.4, 4.8, 2.3, 3.4, 2.3, 1.5, 7.8, 4.5, 0.9, 6.3, 2.4, 6.9,
    2.8, 1.3, 2.9, 6.4, 6.3};
double[] dataZ = {6.6, 12.5, 7.4, 6.2, 9.6, 13.6, 19.9, 2.2, 6.9, 3.4, 8.7, 8.4, 7.8,
    8.0, 9.4, 11.9, 9.6, 15.7, 12.0, 13.3, 9.6, 6.4, 9.0, 6.9, 4.6, 9.7, 10.6, 9.2,
    7.0, 6.9, 9.7, 8.6, 8.0, 13.6, 13.2, 5.9, 9.0, 3.2, 8.3, 9.7, 8.2, 6.1, 8.7, 5.6,
    14.9, 9.8, 9.3, 5.1, 10.8, 9.8};

// Create a XYChart object of size 450 x 540 pixels
XYChart c = new XYChart(450, 540);

// Add a title to the chart using 15 points Arial Italic font
c.addTitle("      Contour Chart with Scattered Data", "Arial Italic", 15);

// Set the plotarea at (65, 40) and of size 360 x 360 pixels. Use semi-transparent
// black (c0000000) for both horizontal and vertical grid lines
c.setPlotArea(65, 40, 360, 360, -1, -1, -1, 0xc0000000, -1);

// Set x-axis and y-axis title using 12 points Arial Bold Italic font
c.xAxis().setTitle("X-Axis Title Place Holder", "Arial Bold Italic", 10);
c.yAxis().setTitle("Y-Axis Title Place Holder", "Arial Bold Italic", 10);

// Set x-axis and y-axis labels to use Arial Bold font
c.xAxis().setLabelStyle("Arial Bold");
c.yAxis().setLabelStyle("Arial Bold");

// When x-axis and y-axis color to transparent
c.xAxis().setColors(Chart.Transparent);
c.yAxis().setColors(Chart.Transparent);

// Add a scatter layer to the chart to show the position of the data points
c.addScatterLayer(dataX, dataY, "", Chart.Cross2Shape(0.2), 7, 0x000000);

// Add a contour layer using the given data
ContourLayer layer = c.addContourLayer(dataX, dataY, dataZ);

// Move the grid lines in front of the contour layer
c.getPlotArea().moveGridBefore(layer);

// Add a color axis (the legend) in which the top center is anchored at (245, 455).
// Set the length to 330 pixels and the labels on the top side.
ColorAxis cAxis = layer.setColorAxis(245, 455, Chart.TopCenter, 330, Chart.Top);

// Add a bounding box to the color axis using the default line color as border.
cAxis.setBoundingBox(Chart.Transparent, Chart.LineColor);

// Add a title to the color axis using 12 points Arial Bold Italic font
cAxis.setTitle("Color Legend Title Place Holder", "Arial Bold Italic", 10);

// Set color axis labels to use Arial Bold font
cAxis.setLabelStyle("Arial Bold");

// Set the color axis range as 0 to 20, with a step every 2 units
cAxis.setLinearScale(0, 20, 2);

// Output the chart
String chart1URL = c.makeSession(request, "chart1");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Scattered Data Contour Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'>
</body>
</html>

[Java Version] javademo/scattercontour.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class scattercontour implements DemoModule
{
    //Name of demo program
    public String toString() { return "Scattered Data Contour Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The (x, y, z) coordinates of the scattered data
        double[] dataX = {0.5, 1.9, 4.9, 1.0, 8.9, 9.8, 5.9, 2.9, 6.8, 9.0, 0.0, 8.9,
            1.9, 4.8, 2.4, 3.4, 7.9, 7.5, 4.8, 7.5, 9.5, 0.4, 8.9, 0.9, 5.4, 9.4,
            2.9, 8.9, 0.9, 8.9, 10.0, 1.0, 6.8, 3.8, 9.0, 5.3, 6.4, 4.9, 4.5, 2.0,
            5.4, 0.0, 10.0, 3.9, 5.4, 5.9, 5.8, 0.3, 4.4, 8.3};
        double[] dataY = {3.3, 3.0, 0.7, 1.0, 9.3, 4.5, 8.4, 0.1, 0.8, 0.1, 9.3, 1.8,
            4.3, 1.3, 2.3, 5.4, 6.9, 9.0, 9.8, 7.5, 1.8, 1.4, 4.5, 7.8, 3.8, 4.0,
            2.9, 2.4, 3.9, 2.9, 2.3, 9.3, 2.0, 3.4, 4.8, 2.3, 3.4, 2.3, 1.5, 7.8,
            4.5, 0.9, 6.3, 2.4, 6.9, 2.8, 1.3, 2.9, 6.4, 6.3};
        double[] dataZ = {6.6, 12.5, 7.4, 6.2, 9.6, 13.6, 19.9, 2.2, 6.9, 3.4, 8.7,
            8.4, 7.8, 8.0, 9.4, 11.9, 9.6, 15.7, 12.0, 13.3, 9.6, 6.4, 9.0, 6.9, 4.6,
            9.7, 10.6, 9.2, 7.0, 6.9, 9.7, 8.6, 8.0, 13.6, 13.2, 5.9, 9.0, 3.2, 8.3,
            9.7, 8.2, 6.1, 8.7, 5.6, 14.9, 9.8, 9.3, 5.1, 10.8, 9.8};

        // Create a XYChart object of size 450 x 540 pixels
        XYChart c = new XYChart(450, 540);

        // Add a title to the chart using 15 points Arial Italic font
        c.addTitle("      Contour Chart with Scattered Data", "Arial Italic", 15);

        // Set the plotarea at (65, 40) and of size 360 x 360 pixels. Use
        // semi-transparent black (c0000000) for both horizontal and vertical grid
        // lines
        c.setPlotArea(65, 40, 360, 360, -1, -1, -1, 0xc0000000, -1);

        // Set x-axis and y-axis title using 12 points Arial Bold Italic font
        c.xAxis().setTitle("X-Axis Title Place Holder", "Arial Bold Italic", 10);
        c.yAxis().setTitle("Y-Axis Title Place Holder", "Arial Bold Italic", 10);

        // Set x-axis and y-axis labels to use Arial Bold font
        c.xAxis().setLabelStyle("Arial Bold");
        c.yAxis().setLabelStyle("Arial Bold");

        // When x-axis and y-axis color to transparent
        c.xAxis().setColors(Chart.Transparent);
        c.yAxis().setColors(Chart.Transparent);

        // Add a scatter layer to the chart to show the position of the data points
        c.addScatterLayer(dataX, dataY, "", Chart.Cross2Shape(0.2), 7, 0x000000);

        // Add a contour layer using the given data
        ContourLayer layer = c.addContourLayer(dataX, dataY, dataZ);

        // Move the grid lines in front of the contour layer
        c.getPlotArea().moveGridBefore(layer);

        // Add a color axis (the legend) in which the top center is anchored at (245,
        // 455). Set the length to 330 pixels and the labels on the top side.
        ColorAxis cAxis = layer.setColorAxis(245, 455, Chart.TopCenter, 330,
            Chart.Top);

        // Add a bounding box to the color axis using the default line color as
        // border.
        cAxis.setBoundingBox(Chart.Transparent, Chart.LineColor);

        // Add a title to the color axis using 12 points Arial Bold Italic font
        cAxis.setTitle("Color Legend Title Place Holder", "Arial Bold Italic", 10);

        // Set color axis labels to use Arial Bold font
        cAxis.setLabelStyle("Arial Bold");

        // Set the color axis range as 0 to 20, with a step every 2 units
        cAxis.setLinearScale(0, 20, 2);

        // Output the chart
        viewer.setChart(c);
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new scattercontour();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


Contour Interpolation

Contour Interpolation

This example demonstrates spline and linear surface interpolation, and discrete and continuous coloring.

The data points for the contour layer are the z values at certain (x, y) points. However, to draw the contour and to color the layer, it is necessarily to know the z values at all pixels in the xy plane. ChartDirector uses surface interpolation to compute the z values at all pixels from the given data points. Two types of interpolation - spline and linear - are supported. They can be configured using ContourLayer.setSmoothInterpolation.

The coloring of the contour layer can be discrete or continuous, configurable using ColorAxis.setColorGradient.

Source Code Listing

[JSP Version] jspdemo/contourinterpolate.jsp
<%@page import="ChartDirector.*" %>
<%@page import="javax.servlet.http.*" %>
<%!
// A simple structure to represent a chart image with an image map
private static class ImageWithHotSpot
{
    String imageURL;
    String imageMap;
}

// Function to create the demo charts
ImageWithHotSpot createChart(HttpServletRequest request, int index)
{
    // The x and y coordinates of the grid
    double[] dataX = {-4, -3, -2, -1, 0, 1, 2, 3, 4};
    double[] dataY = {-4, -3, -2, -1, 0, 1, 2, 3, 4};

    // The values at the grid points. In this example, we will compute the values
    // using the formula z = Sin(x * pi / 3) * Sin(y * pi / 3).
    double[] dataZ = new double[(dataX.length) * (dataY.length)];
    for (int yIndex = 0; yIndex < dataY.length; ++yIndex) {
        double y = dataY[yIndex];
        for (int xIndex = 0; xIndex < dataX.length; ++xIndex) {
            double x = dataX[xIndex];
            dataZ[yIndex * (dataX.length) + xIndex] = Math.sin(x * 3.1416 / 3) *
                Math.sin(y * 3.1416 / 3);
        }
    }

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

    // Set the plotarea at (30, 25) and of size 300 x 300 pixels. Use
    // semi-transparent black (c0000000) for both horizontal and vertical grid lines
    c.setPlotArea(30, 25, 300, 300, -1, -1, -1, 0xc0000000, -1);

    // Add a contour layer using the given data
    ContourLayer layer = c.addContourLayer(dataX, dataY, dataZ);

    // Set the x-axis and y-axis scale
    c.xAxis().setLinearScale(-4, 4, 1);
    c.yAxis().setLinearScale(-4, 4, 1);

    if (index == 0) {
        // Discrete coloring, spline surface interpolation
        c.addTitle("Spline Surface - Discrete Coloring", "Arial Bold Italic", 12);
    } else if (index == 1) {
        // Discrete coloring, linear surface interpolation
        c.addTitle("Linear Surface - Discrete Coloring", "Arial Bold Italic", 12);
        layer.setSmoothInterpolation(false);
    } else if (index == 2) {
        // Smooth coloring, spline surface interpolation
        c.addTitle("Spline Surface - Continuous Coloring", "Arial Bold Italic", 12);
        layer.setContourColor(Chart.Transparent);
        layer.colorAxis().setColorGradient(true);
    } else {
        // Discrete coloring, linear surface interpolation
        c.addTitle("Linear Surface - Continuous Coloring", "Arial Bold Italic", 12);
        layer.setSmoothInterpolation(false);
        layer.setContourColor(Chart.Transparent);
        layer.colorAxis().setColorGradient(true);
    }

    // Output the chart
    ImageWithHotSpot ret = new ImageWithHotSpot();
    ret.imageURL = c.makeSession(request, "chart" + index, Chart.JPG);
    return ret;
}
%>
<%
ImageWithHotSpot chart0 = createChart(request, 0);
ImageWithHotSpot chart1 = createChart(request, 1);
ImageWithHotSpot chart2 = createChart(request, 2);
ImageWithHotSpot chart3 = createChart(request, 3);
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Contour Interpolation
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart0.imageURL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1.imageURL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart2.imageURL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart3.imageURL)%>'>
</body>
</html>

[Java Version] javademo/contourinterpolate.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class contourinterpolate implements DemoModule
{
    //Name of demo program
    public String toString() { return "Contour Interpolation"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 4; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The x and y coordinates of the grid
        double[] dataX = {-4, -3, -2, -1, 0, 1, 2, 3, 4};
        double[] dataY = {-4, -3, -2, -1, 0, 1, 2, 3, 4};

        // The values at the grid points. In this example, we will compute the values
        // using the formula z = Sin(x * pi / 3) * Sin(y * pi / 3).
        double[] dataZ = new double[(dataX.length) * (dataY.length)];
        for (int yIndex = 0; yIndex < dataY.length; ++yIndex) {
            double y = dataY[yIndex];
            for (int xIndex = 0; xIndex < dataX.length; ++xIndex) {
                double x = dataX[xIndex];
                dataZ[yIndex * (dataX.length) + xIndex] = Math.sin(x * 3.1416 / 3) *
                    Math.sin(y * 3.1416 / 3);
            }
        }

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

        // Set the plotarea at (30, 25) and of size 300 x 300 pixels. Use
        // semi-transparent black (c0000000) for both horizontal and vertical grid
        // lines
        c.setPlotArea(30, 25, 300, 300, -1, -1, -1, 0xc0000000, -1);

        // Add a contour layer using the given data
        ContourLayer layer = c.addContourLayer(dataX, dataY, dataZ);

        // Set the x-axis and y-axis scale
        c.xAxis().setLinearScale(-4, 4, 1);
        c.yAxis().setLinearScale(-4, 4, 1);

        if (index == 0) {
            // Discrete coloring, spline surface interpolation
            c.addTitle("Spline Surface - Discrete Coloring", "Arial Bold Italic", 12)
                ;
        } else if (index == 1) {
            // Discrete coloring, linear surface interpolation
            c.addTitle("Linear Surface - Discrete Coloring", "Arial Bold Italic", 12)
                ;
            layer.setSmoothInterpolation(false);
        } else if (index == 2) {
            // Smooth coloring, spline surface interpolation
            c.addTitle("Spline Surface - Continuous Coloring", "Arial Bold Italic",
                12);
            layer.setContourColor(Chart.Transparent);
            layer.colorAxis().setColorGradient(true);
        } else {
            // Discrete coloring, linear surface interpolation
            c.addTitle("Linear Surface - Continuous Coloring", "Arial Bold Italic",
                12);
            layer.setSmoothInterpolation(false);
            layer.setContourColor(Chart.Transparent);
            layer.colorAxis().setColorGradient(true);
        }

        // Output the chart
        viewer.setChart(c);
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new contourinterpolate();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);
        frame.getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
        frame.setSize(800, 450);

        // Create the charts and put them in the content pane
        for (int i = 0; i < demo.getNoOfCharts(); ++i)
        {
            ChartViewer viewer = new ChartViewer();
            demo.createChart(viewer, i);
            frame.getContentPane().add(viewer);
        }

        // Display the window
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/hloc.jsp
<%@page import="ChartDirector.*" %>
<%
//
// Sample data for the HLOC chart.
//
double[] highData = {2043, 2039, 2076, 2064, 2048, 2058, 2070, 2033, 2027, 2029,
    2071, 2085, 2034, 2031, 2056, 2128, 2180, 2183, 2192, 2213, 2230, 2281, 2272};

double[] lowData = {1931, 1921, 1985, 2028, 1986, 1994, 1999, 1958, 1943, 1944, 1962,
    2011, 1975, 1962, 1928, 2059, 2112, 2103, 2151, 2127, 2123, 2152, 2212};

double[] openData = {2000, 1957, 1993, 2037, 2018, 2021, 2045, 2009, 1959, 1985,
    2008, 2048, 2006, 2010, 1971, 2080, 2116, 2137, 2170, 2172, 2171, 2191, 2240};

double[] closeData = {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
String[] labels = {"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
XYChart c = new 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
HLOCLayer layer = c.addHLOCLayer3(highData, lowData, openData, closeData, 0x008000,
    0xff0000);

// Set the line width to 2 pixels
layer.setLineWidth(2);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{xLabel} Jan 2001\nHigh:{high}\nOpen:{open}\nClose:{close}\nLow:{low}'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Simple HLOC Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/hloc.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class hloc implements DemoModule
{
    //Name of demo program
    public String toString() { return "Simple HLOC Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        //
        // Sample data for the HLOC chart.
        //
        double[] highData = {2043, 2039, 2076, 2064, 2048, 2058, 2070, 2033, 2027,
            2029, 2071, 2085, 2034, 2031, 2056, 2128, 2180, 2183, 2192, 2213, 2230,
            2281, 2272};

        double[] lowData = {1931, 1921, 1985, 2028, 1986, 1994, 1999, 1958, 1943,
            1944, 1962, 2011, 1975, 1962, 1928, 2059, 2112, 2103, 2151, 2127, 2123,
            2152, 2212};

        double[] openData = {2000, 1957, 1993, 2037, 2018, 2021, 2045, 2009, 1959,
            1985, 2008, 2048, 2006, 2010, 1971, 2080, 2116, 2137, 2170, 2172, 2171,
            2191, 2240};

        double[] closeData = {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
        String[] labels = {"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
        XYChart c = new 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
        HLOCLayer layer = c.addHLOCLayer3(highData, lowData, openData, closeData,
            0x008000, 0xff0000);

        // Set the line width to 2 pixels
        layer.setLineWidth(2);

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='{xLabel} Jan 2001 High:{high} Open:{open} Close:{close} " +
            "Low:{low}'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new hloc();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/candlestick.jsp
<%@page import="ChartDirector.*" %>
<%
//
// Sample data for the CandleStick chart.
//
double[] highData = {2043, 2039, 2076, 2064, 2048, 2058, 2070, 2033, 2027, 2029,
    2071, 2085, 2034, 2031, 2056, 2128, 2180, 2183, 2192, 2213, 2230, 2281, 2272};

double[] lowData = {1931, 1921, 1985, 2028, 1986, 1994, 1999, 1958, 1943, 1944, 1962,
    2011, 1975, 1962, 1928, 2059, 2112, 2103, 2151, 2127, 2123, 2152, 2212};

double[] openData = {2000, 1957, 1993, 2037, 2018, 2021, 2045, 2009, 1959, 1985,
    2008, 2048, 2006, 2010, 1971, 2080, 2116, 2137, 2170, 2172, 2171, 2191, 2240};

double[] closeData = {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
String[] labels = {"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
XYChart c = new 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 CandleStick layer to the chart using green (00ff00) for up candles and red
// (ff0000) for down candles
CandleStickLayer layer = c.addCandleStickLayer(highData, lowData, openData,
    closeData, 0x00ff00, 0xff0000);

// Set the line width to 2 pixels
layer.setLineWidth(2);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{xLabel} Jan 2001\nHigh:{high}\nOpen:{open}\nClose:{close}\nLow:{low}'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Simple Candlestick Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/candlestick.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class candlestick implements DemoModule
{
    //Name of demo program
    public String toString() { return "Simple Candlestick Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        //
        // Sample data for the CandleStick chart.
        //
        double[] highData = {2043, 2039, 2076, 2064, 2048, 2058, 2070, 2033, 2027,
            2029, 2071, 2085, 2034, 2031, 2056, 2128, 2180, 2183, 2192, 2213, 2230,
            2281, 2272};

        double[] lowData = {1931, 1921, 1985, 2028, 1986, 1994, 1999, 1958, 1943,
            1944, 1962, 2011, 1975, 1962, 1928, 2059, 2112, 2103, 2151, 2127, 2123,
            2152, 2212};

        double[] openData = {2000, 1957, 1993, 2037, 2018, 2021, 2045, 2009, 1959,
            1985, 2008, 2048, 2006, 2010, 1971, 2080, 2116, 2137, 2170, 2172, 2171,
            2191, 2240};

        double[] closeData = {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
        String[] labels = {"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
        XYChart c = new 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 CandleStick layer to the chart using green (00ff00) for up candles
        // and red (ff0000) for down candles
        CandleStickLayer layer = c.addCandleStickLayer(highData, lowData, openData,
            closeData, 0x00ff00, 0xff0000);

        // Set the line width to 2 pixels
        layer.setLineWidth(2);

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='{xLabel} Jan 2001 High:{high} Open:{open} Close:{close} " +
            "Low:{low}'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new candlestick();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/finance.jsp
<%@page import="ChartDirector.*" %>
<%@page import="java.util.*" %>
<%
// Create a finance chart demo containing 100 days of data
int noOfDays = 100;

// To compute moving averages starting from the first day, we need to get extra data
// points before the first day
int 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 rantable = new 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, new GregorianCalendar(2002, 8, 4).getTime(), 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
double[] timeStamps = rantable.getCol(0);
double[] highData = rantable.getCol(1);
double[] lowData = rantable.getCol(2);
double[] openData = rantable.getCol(3);
double[] closeData = rantable.getCol(4);
double[] volData = rantable.getCol(5);

// Create a FinanceChart object of width 640 pixels
FinanceChart c = new FinanceChart(640);

// 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 240 pixels in height
c.addMainChart(240);

// 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 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 75 pixels volume bars sub-chart to the bottom of the main chart, using
// green/red/grey for up/down/flat days
c.addVolBars(75, 0x99ff99, 0xff9999, 0x808080);

// Append a 14-days RSI indicator chart (75 pixels high) 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(75, 14, 0x800080, 20, 0xff0000, 0x0000ff);

// Append a 12-days momentum indicator chart (75 pixels high) using blue (0000ff)
// color.
c.addMomentum(75, 12, 0x0000ff);

// Output the chart
String chart1URL = c.makeSession(request, "chart1");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Finance Chart (1)
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'>
</body>
</html>

[Java Version] javademo/finance.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import ChartDirector.*;

public class finance implements DemoModule
{
    //Name of demo program
    public String toString() { return "Finance Chart (1)"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // Create a finance chart demo containing 100 days of data
        int noOfDays = 100;

        // To compute moving averages starting from the first day, we need to get
        // extra data points before the first day
        int 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 rantable = new 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, new GregorianCalendar(2002, 8, 4).getTime(), 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
        double[] timeStamps = rantable.getCol(0);
        double[] highData = rantable.getCol(1);
        double[] lowData = rantable.getCol(2);
        double[] openData = rantable.getCol(3);
        double[] closeData = rantable.getCol(4);
        double[] volData = rantable.getCol(5);

        // Create a FinanceChart object of width 640 pixels
        FinanceChart c = new FinanceChart(640);

        // 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 240 pixels in height
        c.addMainChart(240);

        // 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 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 75 pixels volume bars sub-chart to the bottom of the main chart,
        // using green/red/grey for up/down/flat days
        c.addVolBars(75, 0x99ff99, 0xff9999, 0x808080);

        // Append a 14-days RSI indicator chart (75 pixels high) 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(75, 14, 0x800080, 20, 0xff0000, 0x0000ff);

        // Append a 12-days momentum indicator chart (75 pixels high) using blue
        // (0000ff) color.
        c.addMomentum(75, 12, 0x0000ff);

        // Output the chart
        viewer.setChart(c);
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new finance();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/finance2.jsp
<%@page import="ChartDirector.*" %>
<%@page import="java.util.*" %>
<%
// Create a finance chart demo containing 100 days of data
int noOfDays = 100;

// To compute moving averages starting from the first day, we need to get extra data
// points before the first day
int 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 rantable = new 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, new GregorianCalendar(2002, 8, 4).getTime(), 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
double[] timeStamps = rantable.getCol(0);
double[] highData = rantable.getCol(1);
double[] lowData = rantable.getCol(2);
double[] openData = rantable.getCol(3);
double[] closeData = rantable.getCol(4);
double[] volData = rantable.getCol(5);

// Create a FinanceChart object of width 640 pixels
FinanceChart c = new FinanceChart(640);

// 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 (75 pixels high) with %K = 14 and %D = 3
c.addSlowStochastic(75, 14, 3, 0x006060, 0x606000);

// Add the main chart with 240 pixels in height
c.addMainChart(240);

// 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 candlestick 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 75 pixels volume bars sub-chart to the bottom of the main chart, using
// green/red/grey for up/down/flat days
c.addVolBars(75, 0x99ff99, 0xff9999, 0x808080);

// Append a MACD(26, 12) indicator chart (75 pixels high) after the main chart, using
// 9 days for computing divergence.
c.addMACD(75, 26, 12, 9, 0x0000ff, 0xff00ff, 0x008000);

// Output the chart
String chart1URL = c.makeSession(request, "chart1");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Finance Chart (2)
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'>
</body>
</html>

[Java Version] javademo/finance2.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import ChartDirector.*;

public class finance2 implements DemoModule
{
    //Name of demo program
    public String toString() { return "Finance Chart (2)"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // Create a finance chart demo containing 100 days of data
        int noOfDays = 100;

        // To compute moving averages starting from the first day, we need to get
        // extra data points before the first day
        int 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 rantable = new 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, new GregorianCalendar(2002, 8, 4).getTime(), 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
        double[] timeStamps = rantable.getCol(0);
        double[] highData = rantable.getCol(1);
        double[] lowData = rantable.getCol(2);
        double[] openData = rantable.getCol(3);
        double[] closeData = rantable.getCol(4);
        double[] volData = rantable.getCol(5);

        // Create a FinanceChart object of width 640 pixels
        FinanceChart c = new FinanceChart(640);

        // 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 (75 pixels high) with %K = 14 and %D = 3
        c.addSlowStochastic(75, 14, 3, 0x006060, 0x606000);

        // Add the main chart with 240 pixels in height
        c.addMainChart(240);

        // 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 candlestick 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 75 pixels volume bars sub-chart to the bottom of the main chart,
        // using green/red/grey for up/down/flat days
        c.addVolBars(75, 0x99ff99, 0xff9999, 0x808080);

        // Append a MACD(26, 12) indicator chart (75 pixels high) after the main
        // chart, using 9 days for computing divergence.
        c.addMACD(75, 26, 12, 9, 0x0000ff, 0xff00ff, 0x008000);

        // Output the chart
        viewer.setChart(c);
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new finance2();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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.

This sample program is available as a JSP application, and also as a standalone Java application.

Interactive Financial Chart in JSP

The Interactive Financial Chart is implemented in two parts - "financedemo.jsp" for the containing web page, and "financedemochart.jsp" for the charting page.

The containing web page "financedemo.jsp" 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.jsp" and uses it to update the <IMG> tag.

The "financedemochart.jsp" draws the finance chart according to the query parameters, which reflects user selections, and outputs the chart to the <IMG> tag.

The "financedemochart.jsp" 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.

[JSP Version] jspdemo/financedemo.jsp
<html>
<head>
<title>ChartDirector Financial Chart Demonstration</title>
<style>
.inputtitle {font-size:11px; margin:10px 5px; font-family:verdana}
.input {font-size:11px; font-family:verdana}
</style>
<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.jsp?";
    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 class="inputtitle">
                <b>Ticker Symbol</b><br />
                <input id="TickerSymbol" name="TickerSymbol" class="input" style="width:140px;" value="ASE.SYMBOL">
            </div>
            <div class="inputtitle">
                <b>Compare With</b><br />
                <input id="CompareWith" name="CompareWith" class="input" style="width:140px;" value="">
            </div>
            <div class="inputtitle">
                <b>Time Period</b><br />
                <select id="TimeRange" name="TimeRange" class="input" style="width:140px;">
                    <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 class="inputtitle">
                <b>Chart Size</b><br />
                <select id="ChartSize" name="ChartSize" class="input" style="width:140px;">
                    <option value="S">Small</option>
                    <option value="M">Medium</option>
                    <option value="L" selected>Large</option>
                    <option value="H">Huge</option>
                </select><br />
            </div>
            <div class="inputtitle">
                <input type="checkbox" id="Volume" name="Volume" checked><label for="Volume">Show Volume Bars</label><br />
                <input type="checkbox" id="ParabolicSAR" name="ParabolicSAR"><label for="ParabolicSAR">Parabolic SAR</label><br />
                <input type="checkbox" id="LogScale" name="LogScale"><label for="LogScale">Log Scale</label><br />
                <input type="checkbox" id="PercentageScale" name="PercentageScale"><label for="PercentageScale">Percentage Scale</label><br />
            </div>
            <div class="inputtitle">
                <b>Chart Type</b><br />
                <select id="ChartType" name="ChartType" class="input" style="width:140px;">
                    <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 class="inputtitle">
                <b>Price Band</b><br />
                <select id="Band" name="Band" class="input" style="width:140px;">
                    <option value="None">None</option>
                    <option value="BB" selected>Bollinger Band</option>
                    <option value="DC">Donchian Channel</option>
                    <option value="Envelop">Envelop (SMA 20 +/- 10%)</option>
                </select>
            </div>
            <div class="inputtitle">
                <b>Moving Averages</b><br />
                <nobr><select id="avgType1" name="avgType1" class="input" style="width:105px;">
                    <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" class="input" style="width:30px;" value="10"></nobr><br />
                <nobr><select id="avgType2" name="avgType2" class="input" style="width:105px;">
                    <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" class="input" style="width:30px;" value="25"></nobr><br />
            </div>
            <div class="inputtitle">
                <b>Technical Indicators</b><br />
                <select id="Indicator1" name="Indicator1" class="input" style="width:140px;">
                    <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" class="input" style="width:140px;">
                    <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" class="input" style="width:140px;">
                    <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" class="input" style="width:140px;">
                    <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 class="inputtitle" style="text-align:center">
                <input id="Button1" name="Button1" type="submit" class="input" 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>
</html>

[JSP Version] jspdemo/financedemochart.jsp
<%@page import="ChartDirector.*, java.util.*"%>
<%!
//
// 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
private Date[] timeStamps = null;
double[] volData = null;
double[] highData = null;
double[] lowData = null;
double[] openData = null;
double[] closeData = null;

// An extra data series to compare with the close data
double[] compareData = null;

// The resolution of the data in seconds. 1 day = 86400 seconds.
int resolution = 86400;

/// <summary>
/// Get the 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>
/// <param name="durationInDays">The number of trading days to get.</param>
/// <param name="extraPoints">The extra leading data points needed in order to
/// compute moving averages.</param>
/// <returns>True if successfully obtain the data, otherwise false.</returns>
protected boolean getData(String ticker, GregorianCalendar startDate,
    GregorianCalendar endDate, int durationInDays, int extraPoints)
{
    // This method should return false if the ticker symbol is invalid. In this
    // sample code, as we are using a random number generator for the data, all
    // ticker symbol is allowed, but we still assumed an empty symbol is invalid.
    if ("".equals(ticker)) {
        return false;
    }

    // In this demo, we can get 15 min, daily, weekly or monthly data depending on
    // the time range.
    resolution = 86400;
    if (durationInDays <= 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.
        double dataPointsPerDay = 6.5 * 3600 / resolution;
        GregorianCalendar adjustedStartDate = new GregorianCalendar(startDate.get(Calendar.YEAR),
            startDate.get(Calendar.MONTH), startDate.get(Calendar.DAY_OF_MONTH));
        adjustedStartDate.add(Calendar.DAY_OF_MONTH,
            -(int)Math.ceil(extraPoints / dataPointsPerDay * 7 / 5) - 2);

        // Get the required 15 min data
        get15MinData(ticker, adjustedStartDate.getTime(), endDate.getTime());

    } else if (durationInDays >= 4.5 * 360) {
        // 4 years or more - use monthly data points.
        resolution = 30 * 86400;

        // Adjust startDate backwards to cater for extraPoints
        GregorianCalendar adjustedStartDate = (GregorianCalendar)startDate.clone();
        adjustedStartDate.add(Calendar.MONTH, -extraPoints);

        // Get the required monthly data
        getMonthlyData(ticker, adjustedStartDate.getTime(), endDate.getTime());

    } else if (durationInDays >= 1.5 * 360) {
        // 1 year or more - use weekly points.
        resolution = 7 * 86400;

        // Adjust startDate backwards to cater for extraPoints
        GregorianCalendar adjustedStartDate = (GregorianCalendar)startDate.clone();
        adjustedStartDate.add(Calendar.DAY_OF_MONTH, -extraPoints * 7 - 6);

        // Get the required weekly data
        getWeeklyData(ticker, adjustedStartDate.getTime(), endDate.getTime());

    } 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.
        GregorianCalendar adjustedStartDate = new GregorianCalendar(startDate.get(Calendar.YEAR),
            startDate.get(Calendar.MONTH), startDate.get(Calendar.DAY_OF_MONTH));
        adjustedStartDate.add(Calendar.DAY_OF_MONTH, - (extraPoints * 7 + 4) / 5 - 2);

        // Get the required daily data
        getDailyData(ticker, adjustedStartDate.getTime(), endDate.getTime());
    }

    return true;
}

/// <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>
protected void get15MinData(String ticker, Date startDate, Date 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>
protected void getDailyData(String ticker, Date startDate, Date 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>
protected void getWeeklyData(String ticker, Date startDate, Date 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>
protected void getMonthlyData(String ticker, Date startDate, Date 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>
protected void generateRandomData(String ticker, Date startDate, Date endDate,
    int resolution)
{
    FinanceSimulator db = new FinanceSimulator(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>
protected void convertDailyToWeeklyData()
{
    aggregateData(new ArrayMath(timeStamps).selectStartOfWeek());
}

/// <summary>
/// A utility to convert daily to monthly data.
/// </summary>
protected void convertDailyToMonthlyData()
{
    aggregateData(new ArrayMath(timeStamps).selectStartOfMonth());
}

/// <summary>
/// An internal method used to aggregate daily data.
/// </summary>
protected void aggregateData(ArrayMath aggregator)
{
    timeStamps = Chart.NTime(aggregator.aggregate(Chart.CTime(timeStamps),
        Chart.AggregateFirst));
    highData = aggregator.aggregate(highData, Chart.AggregateMax);
    lowData = aggregator.aggregate(lowData, Chart.AggregateMin);
    openData = aggregator.aggregate(openData, Chart.AggregateFirst);
    closeData = aggregator.aggregate(closeData, Chart.AggregateLast);
    volData = aggregator.aggregate(volData, Chart.AggregateSum);
}

/// <summary>
/// Create a financial chart according to user selections. The user selections are
/// encoded in the query parameters.
/// </summary>
public BaseChart drawChart(HttpServletRequest request)
{
    // In this demo, we just assume we plot up to the latest time. So end date is
    // now.
    GregorianCalendar endDate = new GregorianCalendar();

    // 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 ((endDate.get(Calendar.HOUR_OF_DAY) * 60 + endDate.get(Calendar.MINUTE) <
        9 * 60 + 30) || (endDate.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) ||
        (endDate.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY))
    {
        endDate.add(Calendar.DAY_OF_MONTH, -1);
        endDate.set(Calendar.HOUR_OF_DAY, 16);
        endDate.set(Calendar.MINUTE, 0);
        endDate.set(Calendar.SECOND, 0);
    }

    // The duration selected by the user
    int durationInDays = Integer.parseInt(request.getParameter("TimeRange"));

    // Compute the start date by subtracting the duration from the end date.
    GregorianCalendar startDate;
    if (durationInDays >= 30) {
        // More or equal to 30 days - so we use months as the unit
        startDate = new GregorianCalendar(endDate.get(Calendar.YEAR),
            endDate.get(Calendar.MONTH), 1);
        startDate.add(Calendar.MONTH, -durationInDays / 30);
    } 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 = new GregorianCalendar(endDate.get(Calendar.YEAR),
            endDate.get(Calendar.MONTH), endDate.get(Calendar.DAY_OF_MONTH), 9, 30, 0);
        for (int i = 1; i < durationInDays; ++i)
        {
            startDate.add(Calendar.DAY_OF_MONTH,
                (startDate.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY) ? -3 : -1);
        }
    }

    // The moving average periods selected by the user.
    int avgPeriod1 = 0;
    try { avgPeriod1 = Integer.parseInt(request.getParameter("movAvg1")); }
    catch (Exception e) { avgPeriod1 = 0; }
    int avgPeriod2 = 0;
    try { avgPeriod2 = Integer.parseInt(request.getParameter("movAvg2")); }
    catch (Exception e) { avgPeriod2 = 0; }

    if (avgPeriod1 < 0) {
        avgPeriod1 = 0;
    } else if (avgPeriod1 > 300) {
        avgPeriod1 = 300;
    }

    if (avgPeriod2 < 0) {
        avgPeriod2 = 0;
    } else if (avgPeriod2 > 300) {
        avgPeriod2 = 300;
    }

    // We need extra leading data points in order to compute moving averages.
    int extraPoints = 20;
    if (avgPeriod1 > extraPoints) {
        extraPoints = avgPeriod1;
    }
    if (avgPeriod2 > extraPoints) {
        extraPoints = avgPeriod2;
    }

    // Get the data series to compare with, if any.
    String compareKey = request.getParameter("CompareWith").trim();
    compareData = null;
    if (getData(compareKey, startDate, endDate, durationInDays, extraPoints)) {
          compareData = closeData;
    }

    // The data series we want to get.
    String tickerKey = request.getParameter("TickerSymbol").trim();
    if (!getData(tickerKey, startDate, endDate, durationInDays, extraPoints)) {
        return errMsg("Please enter a valid ticker symbol");
    }

    // 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 = timeStamps.length;
    Date cutOff = startDate.getTime();
    for (int i = 0; i < timeStamps.length; ++i)
    {
        if (!timeStamps[i].before(cutOff))
        {
            extraPoints = i;
            break;
        }
    }

    // Check if there is any valid data
    if (extraPoints >= timeStamps.length) {
        // No data - just display the no data message.
        return errMsg("No data available for the specified time period");
    }

    // 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 < 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).
        GregorianCalendar lastTime = new GregorianCalendar();
        lastTime.setTime(timeStamps[timeStamps.length - 1]);
        int extraTrailingPoints = (int)((16 * 3600 - lastTime.get(Calendar.HOUR_OF_DAY) * 3600
            - lastTime.get(Calendar.MINUTE) * 60 - lastTime.get(Calendar.SECOND)) / resolution);
        if (extraTrailingPoints > 0)
        {
            Date[] extendedTimeStamps = new Date[timeStamps.length + extraTrailingPoints];
            System.arraycopy(timeStamps, 0, extendedTimeStamps, 0, timeStamps.length);
            for (int i = 0; i < extraTrailingPoints; ++i)
            {
                lastTime.add(Calendar.SECOND, resolution);
                extendedTimeStamps[i + timeStamps.length] = (Date)lastTime.getTime().clone();
            }
            timeStamps = extendedTimeStamps;
        }
    }

    //
    // 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.
    //
    int width = 780;
    int mainHeight = 255;
    int indicatorHeight = 80;

    String size = request.getParameter("ChartSize");
    if ("S".equals(size)) {
        // Small chart size
        width = 450;
        mainHeight = 160;
        indicatorHeight = 60;
    } else if ("M".equals(size)) {
        // Medium chart size
        width = 620;
        mainHeight = 215;
        indicatorHeight = 70;
    } else if ("H".equals(size)) {
        // Huge chart size
        width = 1000;
        mainHeight = 320;
        indicatorHeight = 90;
    }

    // Create the chart object using the selected size
    FinanceChart m = new 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(Chart.TopLeft, tickerKey);

    // We displays the current date as well as the data resolution on the next line.
    String resolutionText = "";
    if (resolution == 30 * 86400) {
        resolutionText = "Monthly";
    } else if (resolution == 7 * 86400) {
        resolutionText = "Weekly";
    } else if (resolution == 86400) {
        resolutionText = "Daily";
    } else if (resolution == 900) {
        resolutionText = "15-min";
    }

    m.addPlotAreaTitle(Chart.BottomLeft, "<*font=Arial,size=8*>" + m.formatValue(
        new Date(), "mmm dd, yyyy") + " - " + resolutionText + " chart");

    // A copyright message at the bottom left corner the title area
    m.addPlotAreaTitle(Chart.BottomRight,
        "<*font=Arial,size=8*>(c) Advanced Software Engineering");

    //
    // Add the first techical indicator according. In this demo, we draw the first
    // indicator on top of the main chart.
    //
    addIndicator(m, request.getParameter("Indicator1"), indicatorHeight);

    //
    // Add the main chart
    //
    m.addMainChart(mainHeight);

    //
    // Set log or linear scale according to user preference
    //
    if ("1".equals(request.getParameter("LogScale"))) {
        m.setLogScale(true);
    }

    //
    // Set axis labels to show data values or percentage change to user preference
    //
    if ("1".equals(request.getParameter("PercentageScale"))) {
        m.setPercentageAxis();
    }

    //
    // Draw any price line the user has selected
    //
    String mainType = request.getParameter("ChartType");
    if ("Close".equals(mainType)) {
        m.addCloseLine(0x000040);
    } else if ("TP".equals(mainType)) {
        m.addTypicalPrice(0x000040);
    } else if ("WC".equals(mainType)) {
        m.addWeightedClose(0x000040);
    } else if ("Median".equals(mainType)) {
        m.addMedianPrice(0x000040);
    }

    //
    // Add comparison line if there is data for comparison
    //
    if (compareData != null) {
        if (compareData.length > extraPoints) {
            m.addComparison(compareData, 0x0000ff, compareKey);
        }
    }

    //
    // Add moving average lines.
    //
    addMovingAvg(m, request.getParameter("avgType1"), avgPeriod1, 0x663300);
    addMovingAvg(m, request.getParameter("avgType2"), avgPeriod2, 0x9900ff);

    //
    // Draw candlesticks or OHLC symbols if the user has selected them.
    //
    if ("CandleStick".equals(mainType)) {
        m.addCandleStick(0x33ff33, 0xff3333);
    } else if ("OHLC".equals(mainType)) {
        m.addHLOC(0x008800, 0xcc0000);
    }

    //
    // Add parabolic SAR if necessary
    //
    if ("1".equals(request.getParameter("ParabolicSAR"))) {
        m.addParabolicSAR(0.02, 0.02, 0.2, Chart.DiamondShape, 5, 0x008800, 0x000000)
            ;
    }

    //
    // Add price band/channel/envelop to the chart according to user selection
    //
    String bandType = request.getParameter("Band");
    if ("BB".equals(bandType)) {
        m.addBollingerBand(20, 2, 0x9999ff, 0xc06666ff);
    } else if ("DC".equals(bandType)) {
        m.addDonchianChannel(20, 0x9999ff, 0xc06666ff);
    } else if ("Envelop".equals(bandType)) {
        m.addEnvelop(20, 0.1, 0x9999ff, 0xc06666ff);
    }

    //
    // Add volume bars to the main chart if necessary
    //
    if ("1".equals(request.getParameter("Volume"))) {
        m.addVolBars(indicatorHeight, 0x99ff99, 0xff9999, 0xc0c0c0);
    }

    //
    // Add additional indicators as according to user selection.
    //
    addIndicator(m, request.getParameter("Indicator2"), indicatorHeight);
    addIndicator(m, request.getParameter("Indicator3"), indicatorHeight);
    addIndicator(m, request.getParameter("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>
/// <returns>The LineLayer object representing line layer created.</returns>
protected LineLayer addMovingAvg(FinanceChart m, String avgType, int avgPeriod,
    int color)
{
    if (avgPeriod > 1) {
        if ("SMA".equals(avgType)) {
            return m.addSimpleMovingAvg(avgPeriod, color);
        } else if ("EMA".equals(avgType)) {
            return m.addExpMovingAvg(avgPeriod, color);
        } else if ("TMA".equals(avgType)) {
            return m.addTriMovingAvg(avgPeriod, color);
        } else if ("WMA".equals(avgType)) {
            return m.addWeightedMovingAvg(avgPeriod, color);
        }
    }
    return null;
}

/// <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>
/// <returns>The XYChart object representing indicator chart.</returns>
protected XYChart addIndicator(FinanceChart m, String indicator, int height)
{
    if ("RSI".equals(indicator)) {
        return m.addRSI(height, 14, 0x800080, 20, 0xff6666, 0x6666ff);
    } else if ("StochRSI".equals(indicator)) {
        return m.addStochRSI(height, 14, 0x800080, 30, 0xff6666, 0x6666ff);
    } else if ("MACD".equals(indicator)) {
        return m.addMACD(height, 26, 12, 9, 0x0000ff, 0xff00ff, 0x008000);
    } else if ("FStoch".equals(indicator)) {
        return m.addFastStochastic(height, 14, 3, 0x006060, 0x606000);
    } else if ("SStoch".equals(indicator)) {
        return m.addSlowStochastic(height, 14, 3, 0x006060, 0x606000);
    } else if ("ATR".equals(indicator)) {
        return m.addATR(height, 14, 0x808080, 0x0000ff);
    } else if ("ADX".equals(indicator)) {
        return m.addADX(height, 14, 0x008000, 0x800000, 0x000080);
    } else if ("DCW".equals(indicator)) {
        return m.addDonchianWidth(height, 20, 0x0000ff);
    } else if ("BBW".equals(indicator)) {
        return m.addBollingerWidth(height, 20, 2, 0x0000ff);
    } else if ("DPO".equals(indicator)) {
        return m.addDPO(height, 20, 0x0000ff);
    } else if ("PVT".equals(indicator)) {
        return m.addPVT(height, 0x0000ff);
    } else if ("Momentum".equals(indicator)) {
        return m.addMomentum(height, 12, 0x0000ff);
    } else if ("Performance".equals(indicator)) {
        return m.addPerformance(height, 0x0000ff);
    } else if ("ROC".equals(indicator)) {
        return m.addROC(height, 12, 0x0000ff);
    } else if ("OBV".equals(indicator)) {
        return m.addOBV(height, 0x0000ff);
    } else if ("AccDist".equals(indicator)) {
        return m.addAccDist(height, 0x0000ff);
    } else if ("CLV".equals(indicator)) {
        return m.addCLV(height, 0x0000ff);
    } else if ("WilliamR".equals(indicator)) {
        return m.addWilliamR(height, 14, 0x800080, 30, 0xff6666, 0x6666ff);
    } else if ("Aroon".equals(indicator)) {
        return m.addAroon(height, 14, 0x339933, 0x333399);
    } else if ("AroonOsc".equals(indicator)) {
        return m.addAroonOsc(height, 14, 0x0000ff);
    } else if ("CCI".equals(indicator)) {
        return m.addCCI(height, 20, 0x800080, 100, 0xff6666, 0x6666ff);
    } else if ("EMV".equals(indicator)) {
        return m.addEaseOfMovement(height, 9, 0x006060, 0x606000);
    } else if ("MDX".equals(indicator)) {
        return m.addMassIndex(height, 0x800080, 0xff6666, 0x6666ff);
    } else if ("CVolatility".equals(indicator)) {
        return m.addChaikinVolatility(height, 10, 10, 0x0000ff);
    } else if ("COscillator".equals(indicator)) {
        return m.addChaikinOscillator(height, 0x0000ff);
    } else if ("CMF".equals(indicator)) {
        return m.addChaikinMoneyFlow(height, 21, 0x008000);
    } else if ("NVI".equals(indicator)) {
        return m.addNVI(height, 255, 0x0000ff, 0x883333);
    } else if ("PVI".equals(indicator)) {
        return m.addPVI(height, 255, 0x0000ff, 0x883333);
    } else if ("MFI".equals(indicator)) {
        return m.addMFI(height, 14, 0x800080, 30, 0xff6666, 0x6666ff);
    } else if ("PVO".equals(indicator)) {
        return m.addPVO(height, 26, 12, 9, 0x0000ff, 0xff00ff, 0x008000);
    } else if ("PPO".equals(indicator)) {
        return m.addPPO(height, 26, 12, 9, 0x0000ff, 0xff00ff, 0x008000);
    } else if ("UO".equals(indicator)) {
        return m.addUltimateOscillator(height, 7, 14, 28, 0x800080, 20, 0xff6666,
            0x6666ff);
    } else if ("Vol".equals(indicator)) {
        return m.addVolIndicator(height, 0x99ff99, 0xff9999, 0xc0c0c0);
    } else if ("TRIX".equals(indicator)) {
        return m.addTRIX(height, 12, 0x0000ff);
    }
    return null;
}

/// <summary>
/// Creates a dummy chart to show an error message.
/// </summary>
/// <param name="msg">The error message.
/// <returns>The BaseChart object containing the error message.</returns>
protected BaseChart errMsg(String msg)
{
    MultiChart m = new MultiChart(400, 200);
    m.addTitle2(Chart.Center, msg, "Arial", 10).setMaxWidth(m.getWidth());
    return m;
}
%>
<%

// create the finance chart
BaseChart c = drawChart(request);

try
{
    // stream the chart to the browser and terminate immediately
    out.clear();
    if (WebChartViewer.streamChart(response, c.makeChart2(Chart.PNG)))
        return;
}
catch (IllegalStateException e)
{
    // Some very old servers may not support streaming. So we are forced to redirect
    // to the browser to use the traditional method.
    response.sendRedirect(response.encodeRedirectURL("getchart.jsp?" +
        c.makeSession(request, "chart1")));
    return;
}

%>

Interactive Financial Chart as Standalone Application

The standalone Interactive Financial Chart is based on SWING user interface. The code can be roughly divided into 3 main parts.

  • The first part of the code is to initialize the user interface.

  • The second part of the code is the get15MinData, getDailyData, getWeeklyData and getMonthlyData functions, which 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 third part of the code is the drawChart function. This is the real charting code, which creates a FinanceChart object, set data to it, and configures it according to the states of the user controls.

[Java Version] javademo/FinanceDemo.java
import ChartDirector.*;
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class FinanceDemo extends JFrame implements DemoModule
{
    // The ticker symbol, timeStamps, volume, high, low, open and close data
    String tickerKey = "";
    private Date[] timeStamps;
    private double[] volData;       //The volume values.
    private double[] highData;      //The high values.
    private double[] lowData;       //The low values.
    private double[] openData;      //The open values.
    private double[] closeData;     //The close values.

    // An extra data series to compare with the close data
    String compareKey = "";
    double[] compareData = null;

    // The resolution of the data in seconds. 1 day = 86400 seconds.
    int resolution = 86400;

    // The moving average periods
    private int avgPeriod1;
    private int avgPeriod2;

    // Will set to true at the end of initialization
    private boolean hasFinishedInitialization;

    //
    // Controls in the JFrame
    //
    private JTextField tickerSymbol;
    private JTextField compareWith;
    private JComboBox timeRange;
    private JComboBox chartSize;
    private JCheckBox volumeBars;
    private JCheckBox parabolicSAR;
    private JCheckBox logScale;
    private JCheckBox percentageScale;
    private JComboBox chartType;
    private JComboBox priceBand;
    private JComboBox avgType1;
    private JTextField movAvg1;
    private JComboBox avgType2;
    private JTextField movAvg2;
    private JComboBox indicator1;
    private JComboBox indicator2;
    private JComboBox indicator3;
    private JComboBox indicator4;
     private ChartViewer chartViewer1;

    /// <summary>
    /// A utility class for adding items to ComboBox
    /// </summary>
    private static class ListItem
    {
        private String m_key;
        private String m_value;

        private ListItem(String key, String val)
        {
            m_key = key;
            m_value = val;
        }

        private String getKey()
        {
            return m_key;
        }

        public String toString()
        {
            return m_value;
        }
    }

    /// <summary>
    /// The main method to allow this demo to run as a standalone program.
    /// </summary>
    public static void main(String args[])
    {
        FinanceDemo demo = new FinanceDemo();
        demo.setDefaultCloseOperation(EXIT_ON_CLOSE);
        demo.setupFrame();
        demo.setVisible(true);
    }

    /// <summary>
    /// Set up the JFrame
    /// </summary>
    private void setupFrame()
    {
        // Do nothing if already initialized
        if (hasFinishedInitialization)
            return;

        setTitle("ChartDirector Financial Chart Demonstration");

        // Top label bar
        JLabel topLabel = new JLabel("Advanced Software Engineering");
        topLabel.setForeground(new java.awt.Color(255, 255, 51));
        topLabel.setBackground(new java.awt.Color(0, 0, 128));
        topLabel.setBorder(new javax.swing.border.EmptyBorder(2, 0, 2, 5));
        topLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        topLabel.setOpaque(true);
        getContentPane().add(topLabel, java.awt.BorderLayout.NORTH);

        // Left panel
        JPanel leftPanel = new JPanel(null);

        // Ticker Symbol
        leftPanel.add(new JLabel("Ticker Symbol")).setBounds(8, 4, 140, 18);
        tickerSymbol = new JTextField("ASE.SYMBOL");
        leftPanel.add(tickerSymbol).setBounds(8, 22, 140, 20);

        // Compare With
        leftPanel.add(new JLabel("Compare With")).setBounds(8, 46, 140, 18);
        compareWith = new JTextField();
        leftPanel.add(compareWith).setBounds(8, 64, 140, 20);

        // Time Period
        leftPanel.add(new JLabel("Time Period")).setBounds(8, 88, 140, 18);
        timeRange = new JComboBox();
        leftPanel.add(timeRange).setBounds(8, 106, 140, 20);

        // Chart Size
        leftPanel.add(new JLabel("Chart Size")).setBounds(8, 130, 140, 18);
        chartSize = new JComboBox();
        leftPanel.add(chartSize).setBounds(8, 148, 140, 20);

        // Value bars/Log Scale/Grid Lines
        volumeBars = new JCheckBox("Show Volume Bars", true);
        parabolicSAR = new JCheckBox("Parabolic SAR", false);
        logScale = new JCheckBox("Log Scale", false);
        percentageScale = new JCheckBox("Percentage Grid", false);
        leftPanel.add(volumeBars).setBounds(8, 172, 140, 20);
        leftPanel.add(parabolicSAR).setBounds(8, 192, 140, 20);
        leftPanel.add(logScale).setBounds(8, 212, 140, 20);
        leftPanel.add(percentageScale).setBounds(8, 232, 140, 20);

        // Chart Type
        leftPanel.add(new JLabel("Chart Type")).setBounds(8, 256, 140, 18);
        chartType = new JComboBox();
        leftPanel.add(chartType).setBounds(8, 274, 140, 20);

        // Price Bands
        leftPanel.add(new JLabel("Price Bands")).setBounds(8, 298, 140, 18);
        priceBand = new JComboBox();
        leftPanel.add(priceBand).setBounds(8, 316, 140, 20);

        // Moving Averages
        leftPanel.add(new JLabel("Moving Averages")).setBounds(8, 340, 140, 18);
        avgType1 = new JComboBox();
        avgType2 = new JComboBox();
        movAvg1 = new JTextField("10");
        movAvg2 = new JTextField("25");
        leftPanel.add(avgType1).setBounds(8, 358, 105, 20);
        leftPanel.add(avgType2).setBounds(8, 378, 105, 20);
        leftPanel.add(movAvg1).setBounds(113, 358, 35, 20);
        leftPanel.add(movAvg2).setBounds(113, 378, 35, 20);

        // Technical Indicators
        leftPanel.add(new JLabel("Technical Indicators")).setBounds(8, 402, 140, 18);
        indicator1 = new JComboBox();
        indicator2 = new JComboBox();
        indicator3 = new JComboBox();
        indicator4 = new JComboBox();
        leftPanel.add(indicator1).setBounds(8, 420, 140, 20);
        leftPanel.add(indicator2).setBounds(8, 440, 140, 20);
        leftPanel.add(indicator3).setBounds(8, 460, 140, 20);
        leftPanel.add(indicator4).setBounds(8, 480, 140, 20);

        // Put Left Panel in a scroll pane
        leftPanel.setPreferredSize(new Dimension(150, 510));
        JScrollPane leftScrollPane = new JScrollPane(leftPanel,
            JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        leftScrollPane.setPreferredSize(new Dimension(170, 515));

        // Chart Viewer
        chartViewer1 = new ChartViewer();
        chartViewer1.setBackground(new java.awt.Color(255, 255, 255));
        chartViewer1.setHorizontalAlignment(SwingConstants.CENTER);
        chartViewer1.setOpaque(true);

        // Put Chart Viewer in a scroll pane
        JScrollPane rightScrollPane = new JScrollPane(chartViewer1);
        rightScrollPane.setPreferredSize(new Dimension(800, 490));

        // Put the LeftPanel and RightScrollPane on the JFrame
        getContentPane().add(leftScrollPane, java.awt.BorderLayout.WEST);
        getContentPane().add(rightScrollPane, java.awt.BorderLayout.CENTER);

        // Font to use for user interface elements
        Font controlFont = new Font("Dialog", Font.PLAIN, 11);
        Font labelFont = new Font("Dialog", Font.BOLD, 11);

        // Use the same action hanlder for all controls
        ActionListener actionHandler = new ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                handleSelection(evt); }};

        // Text field connects to the textChangeHandler for validating the text
        FocusAdapter textChangeHandler = new FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                textChanged(evt); }};

        for (int i = 0; i < leftPanel.getComponentCount(); ++i)
        {
            // Set all UI fonts (except labels) to uiFont
            Component c = leftPanel.getComponent(i);
            if (!(c instanceof JLabel))
                c.setFont(controlFont);
            else
                c.setFont(labelFont);

            // Connect controls to event handlers
            if (c instanceof JComboBox)
                ((JComboBox)c).addActionListener(actionHandler);
            if (c instanceof JCheckBox)
                ((JCheckBox)c).addActionListener(actionHandler);
            if (c instanceof JTextField)
            {
                ((JTextField)c).addActionListener(actionHandler);
                ((JTextField)c).addFocusListener(textChangeHandler);
            }
        }

        //
        // Fill the contents of the combo boxes
        //

        timeRange.setModel(new DefaultComboBoxModel(new ListItem[]
        {
             new ListItem("1", "1 day"),
             new ListItem("2", "2 days"),
             new ListItem("5", "5 days"),
             new ListItem("10", "10 days"),
             new ListItem("30", "1 month"),
             new ListItem("60", "2 months"),
             new ListItem("90", "3 months"),
             new ListItem("180", "6 months"),
             new ListItem("360", "1 year"),
             new ListItem("720", "2 years"),
             new ListItem("1080", "3 years"),
             new ListItem("1440", "4 years"),
             new ListItem("1800", "5 years"),
             new ListItem("3600", "10 years")
        }));
        timeRange.setSelectedIndex(7);

        chartSize.setModel(new DefaultComboBoxModel(new ListItem[]
        {
             new ListItem("S", "Small"),
             new ListItem("M", "Medium"),
             new ListItem("L", "Large"),
             new ListItem("H", "Huge")
        }));
        chartSize.setSelectedIndex(2);

        chartType.setModel(new DefaultComboBoxModel(new ListItem[]
        {
             new ListItem("None", "None"),
             new ListItem("CandleStick", "CandleStick"),
             new ListItem("Close", "Closing Price"),
             new ListItem("Median", "Median Price"),
             new ListItem("OHLC", "OHLC"),
             new ListItem("TP", "Typical Price"),
             new ListItem("WC", "Weighted Close")
        }));
        chartType.setSelectedIndex(1);

        priceBand.setModel(new DefaultComboBoxModel(new ListItem[]
         {
             new ListItem("None", "None"),
             new ListItem("BB", "Bollinger Band"),
             new ListItem("DC", "Donchain Channel"),
             new ListItem("Envelop", "Envelop (SMA 20 +/- 10%)")
         }));
        priceBand.setSelectedIndex(1);

        avgType1.setModel(new DefaultComboBoxModel(new ListItem[]
        {
            new ListItem("None", "None"),
            new ListItem("SMA", "Simple"),
            new ListItem("EMA", "Exponential"),
            new ListItem("TMA", "Triangular"),
            new ListItem("WMA", "Weighted")
        }));
        avgType1.setSelectedIndex(1);

        avgType2.setModel(new DefaultComboBoxModel(new ListItem[]
        {
            new ListItem("None", "None"),
            new ListItem("SMA", "Simple"),
            new ListItem("EMA", "Exponential"),
            new ListItem("TMA", "Triangular"),
            new ListItem("WMA", "Weighted")
        }));
        avgType2.setSelectedIndex(1);

        ListItem[] indicators =
        {
            new ListItem("None", "None"),
            new ListItem("AccDist", "Accumulation/Distribution"),
            new ListItem("AroonOsc", "Aroon Oscillator"),
            new ListItem("Aroon", "Aroon Up/Down"),
            new ListItem("ADX", "Avg Directional Index"),
            new ListItem("ATR", "Avg True Range"),
            new ListItem("BBW", "Bollinger Band Width"),
            new ListItem("CMF", "Chaikin Money Flow"),
            new ListItem("COscillator", "Chaikin Oscillator"),
            new ListItem("CVolatility", "Chaikin Volatility"),
            new ListItem("CLV", "Close Location Value"),
            new ListItem("CCI", "Commodity Channel Index"),
            new ListItem("DPO", "Detrended Price Osc"),
            new ListItem("DCW", "Donchian Channel Width"),
            new ListItem("EMV", "Ease of Movement"),
            new ListItem("FStoch", "Fast Stochastic"),
            new ListItem("MACD", "MACD"),
            new ListItem("MDX", "Mass Index"),
            new ListItem("Momentum", "Momentum"),
            new ListItem("MFI", "Money Flow Index"),
            new ListItem("NVI", "Neg Volume Index"),
            new ListItem("OBV", "On Balance Volume"),
            new ListItem("Performance", "Performance"),
            new ListItem("PPO", "% Price Oscillator"),
            new ListItem("PVO", "% Volume Oscillator"),
            new ListItem("PVI", "Pos Volume Index"),
            new ListItem("PVT", "Price Volume Trend"),
            new ListItem("ROC", "Rate of Change"),
            new ListItem("RSI", "RSI"),
            new ListItem("SStoch", "Slow Stochastic"),
            new ListItem("StochRSI", "StochRSI"),
            new ListItem("TRIX", "TRIX"),
            new ListItem("UO", "Ultimate Oscillator"),
            new ListItem("Vol", "Volume"),
            new ListItem("WilliamR", "William's %R")
        };

        indicator1.setModel(new DefaultComboBoxModel(indicators));
        indicator2.setModel(new DefaultComboBoxModel(indicators));
        indicator3.setModel(new DefaultComboBoxModel(indicators));
        indicator4.setModel(new DefaultComboBoxModel(indicators));

        for (int i = 0; i < indicators.length; ++i)
        {
            if (indicators[i].getKey() == "RSI")
                indicator1.setSelectedIndex(i);
            else if (indicators[i].getKey() == "MACD")
                indicator2.setSelectedIndex(i);
        }
        indicator3.setSelectedIndex(0);
        indicator4.setSelectedIndex(0);

        // Layout and display the JFrame
        pack();
        hasFinishedInitialization = true;

        // Update the chart
        drawChart(chartViewer1);
    }

    /// <summary>
    /// Get the 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>
    /// <param name="durationInDays">The number of trading days to get.</param>
    /// <param name="extraPoints">The extra leading data points needed in order to
    /// compute moving averages.</param>
    /// <returns>True if successfully obtain the data, otherwise false.</returns>
    protected boolean getData(String ticker, GregorianCalendar startDate,
        GregorianCalendar endDate, int durationInDays, int extraPoints)
    {
        // This method should return false if the ticker symbol is invalid. In this
        // sample code, as we are using a random number generator for the data, all
        // ticker symbol is allowed, but we still assumed an empty symbol is invalid.
        if (ticker.equals("")) {
            return false;
        }

        // In this demo, we can get 15 min, daily, weekly or monthly data depending on
        // the time range.
        resolution = 86400;
        if (durationInDays <= 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.
            double dataPointsPerDay = 6.5 * 3600 / resolution;
            GregorianCalendar adjustedStartDate = new GregorianCalendar(startDate.get(Calendar.YEAR),
                startDate.get(Calendar.MONTH), startDate.get(Calendar.DAY_OF_MONTH));
            adjustedStartDate.add(Calendar.DAY_OF_MONTH,
                -(int)Math.ceil(extraPoints / dataPointsPerDay * 7 / 5) - 2);

            // Get the required 15 min data
            get15MinData(ticker, adjustedStartDate.getTime(), endDate.getTime());

        } else if (durationInDays >= 4.5 * 360) {
            // 4 years or more - use monthly data points.
            resolution = 30 * 86400;

            // Adjust startDate backwards to cater for extraPoints
            GregorianCalendar adjustedStartDate = (GregorianCalendar)startDate.clone();
            adjustedStartDate.add(Calendar.MONTH, -extraPoints);

            // Get the required monthly data
            getMonthlyData(ticker, adjustedStartDate.getTime(), endDate.getTime());

        } else if (durationInDays >= 1.5 * 360) {
            // 1 year or more - use weekly points.
            resolution = 7 * 86400;

            // Adjust startDate backwards to cater for extraPoints
            GregorianCalendar adjustedStartDate = (GregorianCalendar)startDate.clone();
                adjustedStartDate.add(Calendar.DAY_OF_MONTH, -extraPoints * 7 - 6);

            // Get the required weekly data
            getWeeklyData(ticker, adjustedStartDate.getTime(), endDate.getTime());

        } 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.
            GregorianCalendar adjustedStartDate = new GregorianCalendar(startDate.get(Calendar.YEAR),
                startDate.get(Calendar.MONTH), startDate.get(Calendar.DAY_OF_MONTH));
            adjustedStartDate.add(Calendar.DAY_OF_MONTH, - (extraPoints * 7 + 4) / 5 - 2);

            // Get the required daily data
            getDailyData(ticker, adjustedStartDate.getTime(), endDate.getTime());
        }

        return true;
    }

    /// <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>
    private void get15MinData(String ticker, Date startDate, Date 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>
    private void getDailyData(String ticker, Date startDate, Date 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. A typical database code
        // example is like below. (This only shows a general idea. The exact details may differ
        // depending on your database brand and schema.)
        //
        //   //Connect to database using a suitable JDBC driver and the connect string
        //   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        //   java.sql.Connection dbConn = java.sql.DriverManager.getConnection
        //        ("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=example.mdb");
        //
        //   //SQL statement to get the data. We use prepared statements in the example as it
        //   //offers a portable way to handle date/time formats.
        //   String sql = "Select recordDate, highData, lowData, openData, closeDate, volData " +
        //       "From dailyFinanceTable Where ticker = '" + ticker + "' And recordDate >= ? " +
        //       " And recordDate <= ? Order By recordDate";
        //   java.sql.PreparedStatement stmt = dbConn.prepareStatement(sql);
        //   stmt.setDate(1, new java.sql.Date(startDate.getTime()));
        //   stmt.setDate(2, new java.sql.Date(endDate.getTime()));
        //
        //   //The most convenient way to read the SQL result into arrays is to use the
        //   //ChartDirector DBTable utility.
        //   DBTable table = new DBTable(stmt.executeQuery());
        //   stmt.close();
        //   dbConn.close();
        //
        //   //Now get the data into arrays
        //   timeStamps = table.getColAsDateTime(0);
        //   highData = table.getCol(1);
        //   lowData = table.getCol(2);
        //   openData = table.getCol(3);
        //   closeData = table.getCol(4);
        //   volData = table.getCol(5);
        //

        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>
    private void getWeeklyData(String ticker, Date startDate, Date 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 weekly
        // data, you may call "getDailyData" to get daily data first, and then call
        // "convertDailyToWeeklyData" to convert it to weekly data, like:
        //
        //      getDailyData(startDate, endDate);
        //      convertDailyToWeeklyData();
        //
        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>
    private void getMonthlyData(String ticker, Date startDate, Date 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 monthly
        // data, you may call "getDailyData" to get daily data first, and then call
        // "convertDailyToMonthlyData" to convert it to monthly data, like:
        //
        //      getDailyData(startDate, endDate);
        //      convertDailyToMonthlyData();
        //
        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>
    private void generateRandomData(String ticker, Date startDate, Date endDate, int resolution)
    {
        FinanceSimulator db = new FinanceSimulator(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>
    private void convertDailyToWeeklyData()
    {
        aggregateData(new ArrayMath(timeStamps).selectStartOfWeek());
    }

    /// <summary>
    /// A utility to convert daily to monthly data.
    /// </summary>
    private void convertDailyToMonthlyData()
    {
        aggregateData(new ArrayMath(timeStamps).selectStartOfMonth());
    }

    /// <summary>
    /// An internal method used to aggregate daily data.
    /// </summary>
    private void aggregateData(ArrayMath aggregator)
    {
        timeStamps = Chart.NTime(aggregator.aggregate(Chart.CTime(timeStamps), Chart.AggregateFirst));
        highData = aggregator.aggregate(highData, Chart.AggregateMax);
        lowData = aggregator.aggregate(lowData, Chart.AggregateMin);
        openData = aggregator.aggregate(openData, Chart.AggregateFirst);
        closeData = aggregator.aggregate(closeData, Chart.AggregateLast);
        volData = aggregator.aggregate(volData, Chart.AggregateSum);
    }

    /// <summary>
    /// Handler for modifications to the text boxes
    /// </summary>
   private void textChanged(java.awt.event.FocusEvent evt)
    {
        //
        // Redraw chart if the text box is changed
        //

           JTextField src = (JTextField)evt.getSource();

        int period;
        try { period = Integer.parseInt(src.getText()); }
        catch (NumberFormatException e) { period = 0; }

        if (((src == tickerSymbol) && !tickerSymbol.getText().trim().equals(tickerKey)) ||
            ((src == compareWith) && !compareWith.getText().trim().equals(compareKey)) ||
            ((src == movAvg1) && (period != avgPeriod1)) ||
            ((src == movAvg2) && (period != avgPeriod2)))
            drawChart(chartViewer1);
    }

    /// <summary>
    /// Handler for the actionPerformed event for the controls
    /// </summary>
    private void handleSelection(java.awt.event.ActionEvent evt)
    {
        if (hasFinishedInitialization)
            drawChart(chartViewer1);
    }

    /// <summary>
    /// Draw the chart according to user selection and display it in the WebChartViewer.
    /// </summary>
    /// <param name="viewer">The ChartViewer object to display the chart.</param>
    private void drawChart(ChartViewer viewer)
    {
        // In this demo, we just assume we plot up to the latest time. So endDate is now.
        GregorianCalendar endDate = new GregorianCalendar();

        // 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 ((endDate.get(Calendar.HOUR_OF_DAY) * 60 + endDate.get(Calendar.MINUTE) <
            9 * 60 + 30) || (endDate.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) ||
            (endDate.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY))
        {
            endDate.add(Calendar.DAY_OF_MONTH, -1);
            endDate.set(Calendar.HOUR_OF_DAY, 16);
            endDate.set(Calendar.MINUTE, 0);
            endDate.set(Calendar.SECOND, 0);
        }

        // The duration selected by the user
        int durationInDays = Integer.parseInt(((ListItem)timeRange.getSelectedItem()).getKey());

        // Compute the start date by subtracting the duration from the end date.
        GregorianCalendar startDate;
        if (durationInDays >= 30)
        {
            // More or equal to 30 days - so we use months as the unit
            startDate = new GregorianCalendar(endDate.get(Calendar.YEAR), endDate.get(Calendar.MONTH), 1);
            startDate.add(Calendar.MONTH, -durationInDays / 30);
        }
        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 = new GregorianCalendar(endDate.get(Calendar.YEAR), endDate.get(Calendar.MONTH),
                endDate.get(Calendar.DAY_OF_MONTH), 9, 30, 0);
            for (int i = 1; i < durationInDays; ++i)
                startDate.add(Calendar.DAY_OF_MONTH, (startDate.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY) ? -3 : -1);
        }

        // The moving average periods selected by the user.
        int avgPeriod1;
        try { avgPeriod1 = Integer.parseInt(movAvg1.getText()); }
        catch (NumberFormatException e) { avgPeriod1 = 0;}
        int avgPeriod2;
        try { avgPeriod2 = Integer.parseInt(movAvg2.getText()); }
        catch (NumberFormatException e) { avgPeriod2 = 0;}

        avgPeriod1 = Math.max(0, Math.min(300, avgPeriod1));
        avgPeriod2 = Math.max(0, Math.min(300, avgPeriod2));

        // We need extra leading data points in order to compute moving averages.
        int extraPoints = Math.max(20, Math.max(avgPeriod1, avgPeriod2));

        // Get the data series to compare with, if any.
        compareKey = compareWith.getText().trim();
        compareData = null;
        if (getData(compareKey, startDate, endDate, durationInDays, extraPoints))
            compareData = closeData;

        // The data series we want to get.
        tickerKey = tickerSymbol.getText().trim();
        if (!getData(tickerKey, startDate, endDate, durationInDays, extraPoints))
        {
            errMsg(viewer, "Please enter a valid ticker symbol");
            return;
        }

        // 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 = timeStamps.length;
        Date cutOff = startDate.getTime();
        for (int i = 0; i < timeStamps.length; ++i)
        {
            if (!timeStamps[i].before(cutOff))
            {
                extraPoints = i;
                break;
            }
        }

        // Check if there is any valid data
        if (extraPoints >= timeStamps.length)
        {
            // No data - just display the no data message.
            errMsg(viewer, "No data available for the specified time period");
            return;
        }

        // 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 <= 86400)
        {
            // Add extra points to the axis until it reaches the end of the day. The end
            // of day is assumed to be 4:00pm (it depends on the stock exchange).
            GregorianCalendar lastTime = new GregorianCalendar();
            lastTime.setTime(timeStamps[timeStamps.length - 1]);
            int extraTrailingPoints = (int)((16 * 3600 - lastTime.get(Calendar.HOUR_OF_DAY) * 3600
                - lastTime.get(Calendar.MINUTE) * 60 - lastTime.get(Calendar.SECOND)) / resolution);
            if (extraTrailingPoints > 0)
            {
                Date[] extendedTimeStamps = new Date[timeStamps.length + extraTrailingPoints];
                System.arraycopy(timeStamps, 0, extendedTimeStamps, 0, timeStamps.length);
                for (int i = 0; i < extraTrailingPoints; ++i)
                {
                    lastTime.add(Calendar.SECOND, resolution);
                    extendedTimeStamps[i + timeStamps.length] = (Date)lastTime.getTime().clone();
                }
                timeStamps = extendedTimeStamps;
            }
        }

        //
        // At this stage, all data is 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.
        //
        int width = 780;
        int mainHeight = 255;
        int indicatorHeight = 80;

        String selectedSize = ((ListItem)chartSize.getSelectedItem()).getKey();
        if (selectedSize == "S")
        {
            // Small chart size
            width = 450;
            mainHeight = 160;
            indicatorHeight = 60;
        }
        else if (selectedSize == "M")
        {
            // Medium chart size
            width = 620;
            mainHeight = 215;
            indicatorHeight = 70;
        }
        else if (selectedSize == "H")
        {
            // Huge chart size
            width = 1000;
            mainHeight = 320;
            indicatorHeight = 90;
        }

        // Create the chart object using the selected size
        FinanceChart m = new 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(Chart.TopLeft, tickerKey);

        // We displays the current date as well as the data resolution on the next line.
        String resolutionText = "";
        if (resolution == 30 * 86400)
            resolutionText = "Monthly";
        else if (resolution == 7 * 86400)
            resolutionText = "Weekly";
        else if (resolution == 86400)
            resolutionText = "Daily";
        else if (resolution == 900)
            resolutionText = "15-min";

        m.addPlotAreaTitle(Chart.BottomLeft, "<*font=arial.ttf,size=8*>"
            + m.formatValue(new Date(), "mmm dd, yyyy") + " - " + resolutionText + " chart");

        // A copyright message at the bottom left corner the title area
        m.addPlotAreaTitle(Chart.BottomRight, "<*font=arial.ttf,size=8*>(c) Advanced Software Engineering");

        //
        // Add the first techical indicator according. In this demo, we draw the first
        // indicator on top of the main chart.
        //
        addIndicator(m, ((ListItem)indicator1.getSelectedItem()).getKey(), indicatorHeight);

        //
        // Add the main chart
        //
        m.addMainChart(mainHeight);

        //
        // Set log or linear scale according to user preference
        //
        m.setLogScale(logScale.isSelected());

        //
        // Set axis labels to show data values or percentage change to user preference
        //
        if (percentageScale.isSelected())
            m.setPercentageAxis();

        //
        // Draw the main chart depending on the chart type the user has selected
        //
        String selectedType = ((ListItem)chartType.getSelectedItem()).getKey();
        if (selectedType == "Close")
            m.addCloseLine(0x000040);
        else if (selectedType == "TP")
            m.addTypicalPrice(0x000040);
        else if (selectedType == "WC")
            m.addWeightedClose(0x000040);
        else if (selectedType == "Median")
            m.addMedianPrice(0x000040);

        //
        // Add comparison line if there is data for comparison
        //
        if (compareData != null) {
            if (compareData.length > extraPoints) {
                m.addComparison(compareData, 0x0000ff, compareKey);
            }
        }

        //
        // Add moving average lines.
        //
        addMovingAvg(m, ((ListItem)avgType1.getSelectedItem()).getKey(), avgPeriod1, 0x663300);
        addMovingAvg(m, ((ListItem)avgType2.getSelectedItem()).getKey(), avgPeriod2, 0x9900ff);

        //
        // Draw the main chart if the user has selected CandleStick or OHLC. We draw it
        // here to make sure it is drawn behind the moving average lines (that is, the
        // moving average lines stay on top.)
        //
        if (selectedType == "CandleStick")
            m.addCandleStick(0x33ff33, 0xff3333);
        else if (selectedType == "OHLC")
            m.addHLOC(0x8000, 0x800000);

        //
        // Add parabolic SAR if necessary
        //
        if (parabolicSAR.isSelected())
            m.addParabolicSAR(0.02, 0.02, 0.2, Chart.DiamondShape, 5, 0x008800, 0x000000);

        //
        // Add price band/channel/envelop to the chart according to user selection
        //
        String selectedBand = ((ListItem)priceBand.getSelectedItem()).getKey();
        if (selectedBand == "BB")
            m.addBollingerBand(20, 2, 0x9999ff, 0xc06666ff);
        else if (selectedBand == "DC")
            m.addDonchianChannel(20, 0x9999ff, 0xc06666ff);
        else if (selectedBand == "Envelop")
            m.addEnvelop(20, 0.1, 0x9999ff, 0xc06666ff);

        //
        // Add volume bars to the main chart if necessary
        //
        if (volumeBars.isSelected())
            m.addVolBars(indicatorHeight, 0x99ff99, 0xff9999, 0xc0c0c0);

        //
        // Add additional indicators as according to user selection.
        //
        addIndicator(m, ((ListItem)indicator2.getSelectedItem()).getKey(), indicatorHeight);
        addIndicator(m, ((ListItem)indicator3.getSelectedItem()).getKey(), indicatorHeight);
        addIndicator(m, ((ListItem)indicator4.getSelectedItem()).getKey(), indicatorHeight);

        // Output chart to ChartViewer
        viewer.setImage(m.makeImage());
        viewer.setImageMap(m.getHTMLImageMap("", "", "title='" + m.getToolTipDateFormat() +
            " {value|P}'"));
    }

    /// <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>
    protected LineLayer addMovingAvg(FinanceChart m, String avgType, int avgPeriod, int color)
    {
        if (avgPeriod > 1)
        {
            if (avgType == "SMA")
                return m.addSimpleMovingAvg(avgPeriod, color);
            else if (avgType == "EMA")
                return m.addExpMovingAvg(avgPeriod, color);
            else if (avgType == "TMA")
                return m.addTriMovingAvg(avgPeriod, color);
            else if (avgType == "WMA")
                return m.addWeightedMovingAvg(avgPeriod, color);
        }
        return null;
    }

    /// <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>
    /// <returns>The XYChart object representing indicator chart.</returns>
    protected XYChart addIndicator(FinanceChart m, String indicator, int height)
    {
        if (indicator == "RSI")
            return m.addRSI(height, 14, 0x800080, 20, 0xff6666, 0x6666ff);
        else if (indicator == "StochRSI")
            return m.addStochRSI(height, 14, 0x800080, 30, 0xff6666, 0x6666ff);
        else if (indicator == "MACD")
            return m.addMACD(height, 26, 12, 9, 0xff, 0xff00ff, 0x8000);
        else if (indicator == "FStoch")
            return m.addFastStochastic(height, 14, 3, 0x6060, 0x606000);
        else if (indicator == "SStoch")
            return m.addSlowStochastic(height, 14, 3, 0x6060, 0x606000);
        else if (indicator == "ATR")
            return m.addATR(height, 14, 0x808080, 0xff);
        else if (indicator == "ADX")
            return m.addADX(height, 14, 0x8000, 0x800000, 0x80);
        else if (indicator == "DCW")
            return m.addDonchianWidth(height, 20, 0xff);
        else if (indicator == "BBW")
            return m.addBollingerWidth(height, 20, 2, 0xff);
        else if (indicator == "DPO")
            return m.addDPO(height, 20, 0xff);
        else if (indicator == "PVT")
            return m.addPVT(height, 0xff);
        else if (indicator == "Momentum")
            return m.addMomentum(height, 12, 0xff);
        else if (indicator == "Performance")
            return m.addPerformance(height, 0xff);
        else if (indicator == "ROC")
            return m.addROC(height, 12, 0xff);
        else if (indicator == "OBV")
            return m.addOBV(height, 0xff);
        else if (indicator == "AccDist")
            return m.addAccDist(height, 0xff);
        else if (indicator == "CLV")
            return m.addCLV(height, 0xff);
        else if (indicator == "WilliamR")
            return m.addWilliamR(height, 14, 0x800080, 30, 0xff6666, 0x6666ff);
        else if (indicator == "Aroon")
            return m.addAroon(height, 14, 0x339933, 0x333399);
        else if (indicator == "AroonOsc")
            return m.addAroonOsc(height, 14, 0xff);
        else if (indicator == "CCI")
            return m.addCCI(height, 20, 0x800080, 100, 0xff6666, 0x6666ff);
        else if (indicator == "EMV")
            return m.addEaseOfMovement(height, 9, 0x6060, 0x606000);
        else if (indicator == "MDX")
            return m.addMassIndex(height, 0x800080, 0xff6666, 0x6666ff);
        else if (indicator == "CVolatility")
            return m.addChaikinVolatility(height, 10, 10, 0xff);
        else if (indicator == "COscillator")
            return m.addChaikinOscillator(height, 0xff);
        else if (indicator == "CMF")
            return m.addChaikinMoneyFlow(height, 21, 0x8000);
        else if (indicator == "NVI")
            return m.addNVI(height, 255, 0xff, 0x883333);
        else if (indicator == "PVI")
            return m.addPVI(height, 255, 0xff, 0x883333);
        else if (indicator == "MFI")
            return m.addMFI(height, 14, 0x800080, 30, 0xff6666, 0x6666ff);
        else if (indicator == "PVO")
            return m.addPVO(height, 26, 12, 9, 0xff, 0xff00ff, 0x8000);
        else if (indicator == "PPO")
            return m.addPPO(height, 26, 12, 9, 0xff, 0xff00ff, 0x8000);
        else if (indicator == "UO")
            return m.addUltimateOscillator(height, 7, 14, 28, 0x800080, 20, 0xff6666, 0x6666ff);
        else if (indicator == "Vol")
            return m.addVolIndicator(height, 0x99ff99, 0xff9999, 0xc0c0c0);
        else if (indicator == "TRIX")
            return m.addTRIX(height, 12, 0xff);
        return null;
    }

    /// <summary>
    /// Creates a dummy chart to show an error message.
    /// </summary>
    /// <param name="viewer">The WinChartViewer to display the error message.</param>
    /// <param name="msg">The error message</param>
    protected void errMsg(ChartViewer viewer, String msg)
    {
         MultiChart m = new MultiChart(400, 200);
         m.addTitle2(Chart.Center, msg, "Arial", 10).setMaxWidth(m.getWidth());
         viewer.setImage(m.makeImage());
    }

    //
    // Implementation of the DemoModule interface to allow this demo to run inside the
    // ChartDirectorDemo browser
    //

    // Name of demo program
    public String toString()
    {
        return "Interactive Financial Chart";
    }

    // Number of charts produced in this demo
    public int getNoOfCharts()
    {
        // This demo open its own frame instead of using the right pane of the ChartDirectorDemo
        // browser for display, so we just load the frame, then returns 0.
        setupFrame();
        setVisible(true);
        return 0;
    }

    // Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // Do nothing, as the ChartDirectorDemo browser right pane is not used.
    }
}


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.
Data Table (1) | Demonstrates putting a data table under the x-axis.
Data Table (2) | Demonstrates putting a data table under the x-axis and extend it with additional computed values.
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

[JSP Version] jspdemo/markzone.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the chart
double[] data = {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};
String[] labels = {"0\nJun 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\nJun 5"};

// Create a XYChart object of size 400 x 270 pixels
XYChart c = new 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(Chart.Transparent);

// Add a title to the y axis
ChartDirector.TextBox 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(Chart.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.
LegendBox legend = c.addLegend(165, 0, false, "Arial Bold", 8);

// Disable the legend box boundary by setting the colors to Transparent
legend.setBackground(Chart.Transparent, Chart.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
BarLayer 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(Chart.SameAsMainColor, 1);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='Temperature at {x}:00 = {value} C'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Marks and Zones (1)
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/markzone.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class markzone implements DemoModule
{
    //Name of demo program
    public String toString() { return "Marks and Zones (1)"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the chart
        double[] data = {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};
        String[] labels = {"0\nJun 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\nJun 5"};

        // Create a XYChart object of size 400 x 270 pixels
        XYChart c = new 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(Chart.Transparent);

        // Add a title to the y axis
        ChartDirector.TextBox 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(Chart.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.
        LegendBox legend = c.addLegend(165, 0, false, "Arial Bold", 8);

        // Disable the legend box boundary by setting the colors to Transparent
        legend.setBackground(Chart.Transparent, Chart.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
        BarLayer 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(Chart.SameAsMainColor, 1);

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='Temperature at {x}:00 = {value} C'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new markzone();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/markzone2.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the chart
double[] data = {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.
String[] labels = {"0\nJun 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\nJun 5"};

// Create a XYChart object of size 400 x 270 pixels
XYChart c = new 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
Mark 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(Chart.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
Mark 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(Chart.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
Mark 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(Chart.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
String chart1URL = c.makeSession(request, "chart1");

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='Load at {x}:00 = {value} MBytes'");
%>
<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 color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/markzone2.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class markzone2 implements DemoModule
{
    //Name of demo program
    public String toString() { return "Marks and Zones (2)"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the chart
        double[] data = {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.
        String[] labels = {"0\nJun 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\nJun 5"};

        // Create a XYChart object of size 400 x 270 pixels
        XYChart c = new 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
        Mark 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(Chart.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
        Mark 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(Chart.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
        Mark 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(Chart.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
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='Load at {x}:00 = {value} MBytes'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new markzone2();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/yzonecolor.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the chart
double[] data = {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
String[] labels = {"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
XYChart c = new XYChart(500, 300, 0xffffc0, 0x000000, 1);

//Set search path to current JSP directory for loading icon images
c.setSearchPath(getServletConfig().getServletContext(), request);

// 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 legendBox = c.addLegend(55, 25, false, "", 8);
legendBox.setBackground(Chart.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\nEngineering<*/*>"
    ).setAlignment(Chart.BottomRight);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='Hour {xLabel}: {value} KJ/liter'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Y Zone Coloring
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/yzonecolor.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class yzonecolor implements DemoModule
{
    //Name of demo program
    public String toString() { return "Y Zone Coloring"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the chart
        double[] data = {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
        String[] labels = {"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
        XYChart c = new XYChart(500, 300, 0xffffc0, 0x000000, 1);

        // 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 legendBox = c.addLegend(55, 25, false, "", 8);
        legendBox.setBackground(Chart.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\n" +
            "Engineering<*/*>").setAlignment(Chart.BottomRight);

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='Hour {xLabel}: {value} KJ/liter'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new yzonecolor();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/xzonecolor.jsp
<%@page import="ChartDirector.*" %>
<%@page import="java.util.*" %>
<%
// The data for the chart
double[] data = {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
double[] errData = {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
Date[] labels = {new GregorianCalendar(2001, 0, 1).getTime(), new GregorianCalendar(
    2001, 1, 1).getTime(), new GregorianCalendar(2001, 2, 1).getTime(),
    new GregorianCalendar(2001, 3, 1).getTime(), new GregorianCalendar(2001, 4, 1
    ).getTime(), new GregorianCalendar(2001, 5, 1).getTime(), new GregorianCalendar(
    2001, 6, 1).getTime(), new GregorianCalendar(2001, 7, 1).getTime(),
    new GregorianCalendar(2001, 8, 1).getTime(), new GregorianCalendar(2001, 9, 1
    ).getTime(), new GregorianCalendar(2001, 10, 1).getTime(), new GregorianCalendar(
    2001, 11, 1).getTime(), new GregorianCalendar(2002, 0, 1).getTime(),
    new GregorianCalendar(2002, 1, 1).getTime(), new GregorianCalendar(2002, 2, 1
    ).getTime(), new GregorianCalendar(2002, 3, 1).getTime(), new GregorianCalendar(
    2002, 4, 1).getTime(), new GregorianCalendar(2002, 5, 1).getTime(),
    new GregorianCalendar(2002, 6, 1).getTime(), new GregorianCalendar(2002, 7, 1
    ).getTime(), new GregorianCalendar(2002, 8, 1).getTime(), new GregorianCalendar(
    2002, 9, 1).getTime(), new GregorianCalendar(2002, 10, 1).getTime(),
    new GregorianCalendar(2002, 11, 1).getTime(), new GregorianCalendar(2003, 0, 1
    ).getTime()};

// Create a XYChart object of size 550 x 220 pixels
XYChart c = new 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 legendBox = c.addLegend(50, 10, false, "", 8);
legendBox.setBackground(Chart.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(Chart.StartOfYearFilter(),
    "<*font=Arial Bold*>{value|yyyy}", Chart.StartOfMonthFilter(), "{value|mmm}", 3);

// Add a line layer to the chart
LineLayer 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.
int lineColor = layer.xZoneColor(18, 0x333399, c.dashLineColor(0xd04040,
    Chart.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(Chart.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.
int errColor = layer.xZoneColor(18, 0x809999ff, 0x80ff9966);

// Add the upper border of the err zone
layer.addDataSet(new ArrayMath(data).add(errData).result(), errColor, "Upper bound");

// Add the lower border of the err zone
layer.addDataSet(new 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(Chart.NoLegend);

// Color the region between the err zone lines
c.addInterLineLayer(layer.getLine(1), layer.getLine(2), errColor);

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

// Include tool tip for the chart.
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName} on {xLabel|mmm yyyy}: {value} MJoule'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    X Zone Coloring
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/xzonecolor.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import ChartDirector.*;

public class xzonecolor implements DemoModule
{
    //Name of demo program
    public String toString() { return "X Zone Coloring"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the chart
        double[] data = {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
        double[] errData = {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
        Date[] labels = {new GregorianCalendar(2001, 0, 1).getTime(),
            new GregorianCalendar(2001, 1, 1).getTime(), new GregorianCalendar(2001,
            2, 1).getTime(), new GregorianCalendar(2001, 3, 1).getTime(),
            new GregorianCalendar(2001, 4, 1).getTime(), new GregorianCalendar(2001,
            5, 1).getTime(), new GregorianCalendar(2001, 6, 1).getTime(),
            new GregorianCalendar(2001, 7, 1).getTime(), new GregorianCalendar(2001,
            8, 1).getTime(), new GregorianCalendar(2001, 9, 1).getTime(),
            new GregorianCalendar(2001, 10, 1).getTime(), new GregorianCalendar(2001,
            11, 1).getTime(), new GregorianCalendar(2002, 0, 1).getTime(),
            new GregorianCalendar(2002, 1, 1).getTime(), new GregorianCalendar(2002,
            2, 1).getTime(), new GregorianCalendar(2002, 3, 1).getTime(),
            new GregorianCalendar(2002, 4, 1).getTime(), new GregorianCalendar(2002,
            5, 1).getTime(), new GregorianCalendar(2002, 6, 1).getTime(),
            new GregorianCalendar(2002, 7, 1).getTime(), new GregorianCalendar(2002,
            8, 1).getTime(), new GregorianCalendar(2002, 9, 1).getTime(),
            new GregorianCalendar(2002, 10, 1).getTime(), new GregorianCalendar(2002,
            11, 1).getTime(), new GregorianCalendar(2003, 0, 1).getTime()};

        // Create a XYChart object of size 550 x 220 pixels
        XYChart c = new 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 legendBox = c.addLegend(50, 10, false, "", 8);
        legendBox.setBackground(Chart.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(Chart.StartOfYearFilter(),
            "<*font=Arial Bold*>{value|yyyy}", Chart.StartOfMonthFilter(),
            "{value|mmm}", 3);

        // Add a line layer to the chart
        LineLayer 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.
        int lineColor = layer.xZoneColor(18, 0x333399, c.dashLineColor(0xd04040,
            Chart.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(Chart.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.
        int errColor = layer.xZoneColor(18, 0x809999ff, 0x80ff9966);

        // Add the upper border of the err zone
        layer.addDataSet(new ArrayMath(data).add(errData).result(), errColor,
            "Upper bound");

        // Add the lower border of the err zone
        layer.addDataSet(new 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(Chart.NoLegend);

        // Color the region between the err zone lines
        c.addInterLineLayer(layer.getLine(1), layer.getLine(2), errColor);

        // Output the chart
        viewer.setChart(c);

        // Include tool tip for the chart.
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='{dataSetName} on {xLabel|mmm yyyy}: {value} MJoule'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new xzonecolor();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/dualyaxis.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the chart
double[] data0 = {0.05, 0.06, 0.48, 0.1, 0.01, 0.05};
double[] data1 = {100, 125, 265, 147, 67, 105};
String[] labels = {"Jan", "Feb", "Mar", "Apr", "May", "Jun"};

// Create a XYChart object of size 300 x 180 pixels
XYChart c = new 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 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 barLayer = c.addBarLayer(data1, 0x00c000);
barLayer.setUseYAxis2();

// tool tip for the bar layer
barLayer.setHTMLImageMap("", "", "title='Throughput on {xLabel}: {value} MBytes'");

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

// include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Dual Y-Axis
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/dualyaxis.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class dualyaxis implements DemoModule
{
    //Name of demo program
    public String toString() { return "Dual Y-Axis"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the chart
        double[] data0 = {0.05, 0.06, 0.48, 0.1, 0.01, 0.05};
        double[] data1 = {100, 125, 265, 147, 67, 105};
        String[] labels = {"Jan", "Feb", "Mar", "Apr", "May", "Jun"};

        // Create a XYChart object of size 300 x 180 pixels
        XYChart c = new 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 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 barLayer = c.addBarLayer(data1, 0x00c000);
        barLayer.setUseYAxis2();

        // tool tip for the bar layer
        barLayer.setHTMLImageMap("", "",
            "title='Throughput on {xLabel}: {value} MBytes'");

        // Output the chart
        viewer.setChart(c);

        // include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new dualyaxis();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/dualxaxis.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the chart
double[] data0 = {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};
double[] data1 = {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.
String[] labels0 = {"0\nJun 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\nJun 5"};

// The labels for the top x axis. Note that "-" means a minor tick.
String[] labels1 = {"Jun 3\n12", "13", "14", "15", "16", "17", "18", "19", "20",
    "21", "22", "23", "Jun 4\n0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
    "11", "12"};

// Create a XYChart object of size 310 x 310 pixels
XYChart c = new 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
String chart1URL = c.makeSession(request, "chart1");

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName}\nHKT Jun {=3.5+{x}/24|0} {={x}%24}:00 (NYT Jun " +
    "{=3+{x}/24|0} {=({x}+12)%24}:00)\nHKD {={value}*7.8} (USD {value})'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Dual X-Axis
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/dualxaxis.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class dualxaxis implements DemoModule
{
    //Name of demo program
    public String toString() { return "Dual X-Axis"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the chart
        double[] data0 = {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};
        double[] data1 = {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.
        String[] labels0 = {"0\nJun 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\nJun 5"};

        // The labels for the top x axis. Note that "-" means a minor tick.
        String[] labels1 = {"Jun 3\n12", "13", "14", "15", "16", "17", "18", "19",
            "20", "21", "22", "23", "Jun 4\n0", "1", "2", "3", "4", "5", "6", "7",
            "8", "9", "10", "11", "12"};

        // Create a XYChart object of size 310 x 310 pixels
        XYChart c = new 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
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='{dataSetName} HKT Jun {=3.5+{x}/24|0} {={x}%24}:00 (NYT Jun " +
            "{=3+{x}/24|0} {=({x}+12)%24}:00) HKD {={value}*7.8} (USD {value})'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new dualxaxis();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/multiaxes.jsp
<%@page import="ChartDirector.*" %>
<%
// Data for the chart
double[] data0 = {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};
double[] data1 = {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};
double[] data2 = {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};
double[] data3 = {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
String[] labels = {"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 360 pixels. Use a vertical gradient color
// from sky blue (aaccff) to white (ffffff) as background. Set border to grey
// (888888). Use rounded corners. Enable soft drop shadow.
XYChart c = new XYChart(600, 360);
c.setBackground(c.linearGradientColor(0, 0, 0, c.getHeight(), 0xaaccff, 0xffffff),
    0x888888);
c.setRoundedFrame();
c.setDropShadow();

// Add a title box to the chart using 15 pts Arial Bold Italic font. Set top margin
// to 16 pixels.
TextBox title = c.addTitle("Multiple Axes Demonstration", "Arial Bold Italic", 15);
title.setMargin2(0, 0, 16, 0);

// Set the plotarea at (100, 80) and of size 400 x 230 pixels, with white (ffffff)
// background. Use grey #(aaaaa) dotted lines for both horizontal and vertical grid
// lines.
c.setPlotArea(100, 80, 400, 230, 0xffffff, -1, -1, c.dashLineColor(0xaaaaaa,
    Chart.DotLine), -1);

// Add a legend box with the bottom center anchored at (300, 80) (top center of the
// plot area). Use horizontal layout, and 8 points Arial Bold font. Set background
// and border to transparent.
LegendBox legendBox = c.addLegend(300, 80, false, "Arial Bold", 8);
legendBox.setAlignment(Chart.BottomCenter);
legendBox.setBackground(Chart.Transparent, Chart.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\n(Watt)").setAlignment(Chart.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\n(Mbps)").setAlignment(Chart.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
Axis leftAxis = c.addAxis(Chart.Left, 50);
// Add a title on top of the third y axis.
leftAxis.setTitle("Temp\n(C)").setAlignment(Chart.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
Axis rightAxis = c.addAxis(Chart.Right, 50);
// Add a title on top of the fourth y axis.
rightAxis.setTitle("Error\n(%)").setAlignment(Chart.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
LineLayer 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.
LineLayer 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.
LineLayer 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.
LineLayer layer3 = c.addLineLayer(data3, 0x880088, "Error Rate");
layer3.setLineWidth(2);
layer3.setUseYAxis(rightAxis);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName} at hour {xLabel} = {value}'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Multiple Axes
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/multiaxes.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class multiaxes implements DemoModule
{
    //Name of demo program
    public String toString() { return "Multiple Axes"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // Data for the chart
        double[] data0 = {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};
        double[] data1 = {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};
        double[] data2 = {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};
        double[] data3 = {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
        String[] labels = {"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 360 pixels. Use a vertical gradient
        // color from sky blue (aaccff) to white (ffffff) as background. Set border
        // to grey (888888). Use rounded corners. Enable soft drop shadow.
        XYChart c = new XYChart(600, 360);
        c.setBackground(c.linearGradientColor(0, 0, 0, c.getHeight(), 0xaaccff,
            0xffffff), 0x888888);
        c.setRoundedFrame();
        c.setDropShadow();

        // Add a title box to the chart using 15 pts Arial Bold Italic font. Set top
        // margin to 16 pixels.
        TextBox title = c.addTitle("Multiple Axes Demonstration",
            "Arial Bold Italic", 15);
        title.setMargin2(0, 0, 16, 0);

        // Set the plotarea at (100, 80) and of size 400 x 230 pixels, with white
        // (ffffff) background. Use grey #(aaaaa) dotted lines for both horizontal
        // and vertical grid lines.
        c.setPlotArea(100, 80, 400, 230, 0xffffff, -1, -1, c.dashLineColor(0xaaaaaa,
            Chart.DotLine), -1);

        // Add a legend box with the bottom center anchored at (300, 80) (top center
        // of the plot area). Use horizontal layout, and 8 points Arial Bold font.
        // Set background and border to transparent.
        LegendBox legendBox = c.addLegend(300, 80, false, "Arial Bold", 8);
        legendBox.setAlignment(Chart.BottomCenter);
        legendBox.setBackground(Chart.Transparent, Chart.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\n(Watt)").setAlignment(Chart.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\n(Mbps)").setAlignment(Chart.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
        Axis leftAxis = c.addAxis(Chart.Left, 50);
        // Add a title on top of the third y axis.
        leftAxis.setTitle("Temp\n(C)").setAlignment(Chart.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
        Axis rightAxis = c.addAxis(Chart.Right, 50);
        // Add a title on top of the fourth y axis.
        rightAxis.setTitle("Error\n(%)").setAlignment(Chart.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
        LineLayer 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.
        LineLayer 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.
        LineLayer 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.
        LineLayer layer3 = c.addLineLayer(data3, 0x880088, "Error Rate");
        layer3.setLineWidth(2);
        layer3.setUseYAxis(rightAxis);

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='{dataSetName} at hour {xLabel} = {value}'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new multiaxes();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/fourq.jsp
<%@page import="ChartDirector.*" %>
<%
// XY points for the scatter chart
double[] dataX0 = {10, 15, 6, -12, 14, -8, 13, -13, 16, 12, 10.5};
double[] dataY0 = {130, 150, 80, 110, -110, -105, -130, 115, -170, 125, 125};

double[] dataX1 = {6, 7, -4, 3.5, 7, 8, -9, -10, -12, 11, 8};
double[] dataY1 = {65, -40, -40, 45, -70, -80, 80, 10, -100, 105, 60};

double[] dataX2 = {-10, -12, 11, 8, 6, 12, -4, 3.5, 7, 8, -9};
double[] dataY2 = {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
XYChart c = new 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(Chart.XYAxisAtOrigin, Chart.XAxisSymmetric + Chart.YAxisSymmetric);

// Add a legend box at (300, 460) (bottom center of the chart) with horizontal
// layout. Use 8 pts Arial Bold font.
LegendBox legendBox = c.addLegend(300, 460, false, "Arial Bold", 8);
legendBox.setAlignment(Chart.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", Chart.Cross2Shape(), 15, 0xff3333);

// Add scatter layer, using 15 pixels green (33ff33) 6-sided polygon symbols
c.addScatterLayer(dataX1, dataY1, "Group B", Chart.PolygonShape(6), 15, 0x33ff33);

// Add scatter layer, using 15 pixels blue (3333ff) triangle symbols
c.addScatterLayer(dataX2, dataY2, "Group C", Chart.TriangleSymbol, 15, 0x3333ff);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='[{dataSetName}] Alpha = {x}, Beta = {value}'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    4 Quadrant Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/fourq.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class fourq implements DemoModule
{
    //Name of demo program
    public String toString() { return "4 Quadrant Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // XY points for the scatter chart
        double[] dataX0 = {10, 15, 6, -12, 14, -8, 13, -13, 16, 12, 10.5};
        double[] dataY0 = {130, 150, 80, 110, -110, -105, -130, 115, -170, 125, 125};

        double[] dataX1 = {6, 7, -4, 3.5, 7, 8, -9, -10, -12, 11, 8};
        double[] dataY1 = {65, -40, -40, 45, -70, -80, 80, 10, -100, 105, 60};

        double[] dataX2 = {-10, -12, 11, 8, 6, 12, -4, 3.5, 7, 8, -9};
        double[] dataY2 = {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
        XYChart c = new 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(Chart.XYAxisAtOrigin, Chart.XAxisSymmetric +
            Chart.YAxisSymmetric);

        // Add a legend box at (300, 460) (bottom center of the chart) with
        // horizontal layout. Use 8 pts Arial Bold font.
        LegendBox legendBox = c.addLegend(300, 460, false, "Arial Bold", 8);
        legendBox.setAlignment(Chart.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", Chart.Cross2Shape(), 15,
            0xff3333);

        // Add scatter layer, using 15 pixels green (33ff33) 6-sided polygon symbols
        c.addScatterLayer(dataX1, dataY1, "Group B", Chart.PolygonShape(6), 15,
            0x33ff33);

        // Add scatter layer, using 15 pixels blue (3333ff) triangle symbols
        c.addScatterLayer(dataX2, dataY2, "Group C", Chart.TriangleSymbol, 15,
            0x3333ff);

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='[{dataSetName}] Alpha = {x}, Beta = {value}'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new fourq();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


Data Table (1)

Data Table (1)

This example demonstrates putting a data table under the x-axis.

In ChartDirector, the labels in a label based x-axis (that is, axis configured with Axis.setLabels or Axis.setLabels2) can be converted to a table using Axis.makeLabelTable.

Note: Axis.makeLabelTable is only supported on a label based axis with no label stepping. You should not use this method with other axis configuration.

The Axis.makeLabelTable returns a CDMLTable object representing the table. It can be used to add more content to the table and to configure the appearance of the table.

In this example, 3 rows with alternating background colors are added to the table using CDMLTable.appendRow. The cells in the rows are filled with data values using CDMLTable.setText. A column is added to the left of the table using CDMLTable.insertCol, and filled with the legend icons obtained using Layer.getLegendIcon.

Source Code Listing

[JSP Version] jspdemo/datatable.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the line chart
double[] data0 = {42, 49, 33, 38, 64, 56, 29, 41, 44, 57, 59, 42};
double[] data1 = {65, 75, 47, 34, 42, 49, 73, 62, 90, 69, 66, 78};
double[] data2 = {36, 28, 25, 28, 38, 20, 22, 30, 25, 33, 30, 24};
String[] labels = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
    "Oct", "Nov", "Dec"};

// Create a XYChart object of size 600 x 400 pixels
XYChart c = new XYChart(600, 400);

// Add a title to the chart using 18 pts Times Bold Italic font
TextBox title = c.addTitle("Product Line Global Revenue",
    "Times New Roman Bold Italic", 18);

// Tentatively set the plotarea at (50, 55) and of (chart_width - 100) x
// (chart_height - 120) pixels in size. Use a vertical gradient color from sky blue
// (aaccff) t0 light blue (f9f9ff) as background. Set both horizontal and vertical
// grid lines to dotted semi-transprent black (aa000000).
PlotArea plotArea = c.setPlotArea(50, 55, c.getWidth() - 100, c.getHeight() - 120,
    c.linearGradientColor(0, 55, 0, 55 + c.getHeight() - 120, 0xaaccff, 0xf9fcff),
    -1, -1, c.dashLineColor(0xaa000000, Chart.DotLine), -1);

// Add a legend box and anchored the top center at the horizontal center of the
// chart, just under the title. Use 10pts Arial Bold as font, with transparent
// background and border.
LegendBox legendBox = c.addLegend(c.getWidth() / 2, title.getHeight(), false,
    "Arial Bold", 10);
legendBox.setAlignment(Chart.TopCenter);
legendBox.setBackground(Chart.Transparent, Chart.Transparent);

// Set y-axis title using 10 points Arial Bold Italic font, label style to 8 points
// Arial Bold, and axis color to transparent
c.yAxis().setTitle("Revenue (USD millions)", "Arial Bold Italic", 10);
c.yAxis().setLabelStyle("Arial Bold", 8);
c.yAxis().setColors(Chart.Transparent);

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

// Add a line layer to the chart
LineLayer 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(
    Chart.CircleSymbol, 9);
layer.addDataSet(data1, 0x00ff00, "Atom Synthesizer").setDataSymbol(
    Chart.DiamondSymbol, 11);
layer.addDataSet(data2, 0xff6600, "Proton Cannon").setDataSymbol(Chart.Cross2Shape(),
    11);

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

// Convert the labels on the x-axis to a CDMLTable
CDMLTable table = c.xAxis().makeLabelTable();

// Set the default top/bottom margins of the cells to 3 pixels
table.getStyle().setMargin2(0, 0, 3, 3);

// Use Arial Bold as the font for the first row
table.getRowStyle(0).setFontStyle("Arial Bold");

//
// We can add more information to the table. In this sample code, we add the data
// series and the legend icons to the table.
//

// Add 3 more rows to the table. Set the background of the 1st and 3rd rows to light
// grey (eeeeee).
table.appendRow().setBackground(0xeeeeee, Chart.LineColor);
table.appendRow();
table.appendRow().setBackground(0xeeeeee, Chart.LineColor);

// Put the values of the 3 data series to the cells in the 3 rows
for (int i = 0; i < data0.length; ++i) {
    table.setText(i, 1, String.valueOf(data0[i]));
    table.setText(i, 2, String.valueOf(data1[i]));
    table.setText(i, 3, String.valueOf(data2[i]));
}

// Insert a column on the left for the legend icons. Use 5 pixels left/right margins
// and 3 pixels top/bottom margins for the cells in this column.
table.insertCol(0).setMargin2(5, 5, 3, 3);

// The top cell is set to transparent, so it is invisible
table.getCell(0, 0).setBackground(Chart.Transparent, Chart.Transparent);

// The other 3 cells are set to the legend icons of the 3 data series
table.setText(0, 1, layer.getLegendIcon(0));
table.setText(0, 2, layer.getLegendIcon(1));
table.setText(0, 3, layer.getLegendIcon(2));

// Layout legend box first, so we can get its size
c.layoutLegend();

// Adjust the plot area size, such that the bounding box (inclusive of axes) is 2
// pixels from the left, right and bottom edge, and is just under the legend box.
c.packPlotArea(2, legendBox.getTopY() + legendBox.getHeight(), c.getWidth() - 3,
    c.getHeight() - 3);

// After determining the exact plot area position, we may adjust the legend box and
// the title positions so that they are centered relative to the plot area (instead
// of the chart)
legendBox.setPos(plotArea.getLeftX() + (plotArea.getWidth() - legendBox.getWidth()) /
    2, legendBox.getTopY());
title.setPos(plotArea.getLeftX() + (plotArea.getWidth() - title.getWidth()) / 2,
    title.getTopY());

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='Revenue of {dataSetName} in {xLabel}: US$ {value}M'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Data Table (1)
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/datatable.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class datatable implements DemoModule
{
    //Name of demo program
    public String toString() { return "Data Table (1)"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the line chart
        double[] data0 = {42, 49, 33, 38, 64, 56, 29, 41, 44, 57, 59, 42};
        double[] data1 = {65, 75, 47, 34, 42, 49, 73, 62, 90, 69, 66, 78};
        double[] data2 = {36, 28, 25, 28, 38, 20, 22, 30, 25, 33, 30, 24};
        String[] labels = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
            "Sep", "Oct", "Nov", "Dec"};

        // Create a XYChart object of size 600 x 400 pixels
        XYChart c = new XYChart(600, 400);

        // Add a title to the chart using 18 pts Times Bold Italic font
        TextBox title = c.addTitle("Product Line Global Revenue",
            "Times New Roman Bold Italic", 18);

        // Tentatively set the plotarea at (50, 55) and of (chart_width - 100) x
        // (chart_height - 120) pixels in size. Use a vertical gradient color from
        // sky blue (aaccff) t0 light blue (f9f9ff) as background. Set both
        // horizontal and vertical grid lines to dotted semi-transprent black
        // (aa000000).
        PlotArea plotArea = c.setPlotArea(50, 55, c.getWidth() - 100, c.getHeight() -
            120, c.linearGradientColor(0, 55, 0, 55 + c.getHeight() - 120, 0xaaccff,
            0xf9fcff), -1, -1, c.dashLineColor(0xaa000000, Chart.DotLine), -1);

        // Add a legend box and anchored the top center at the horizontal center of
        // the chart, just under the title. Use 10pts Arial Bold as font, with
        // transparent background and border.
        LegendBox legendBox = c.addLegend(c.getWidth() / 2, title.getHeight(), false,
            "Arial Bold", 10);
        legendBox.setAlignment(Chart.TopCenter);
        legendBox.setBackground(Chart.Transparent, Chart.Transparent);

        // Set y-axis title using 10 points Arial Bold Italic font, label style to 8
        // points Arial Bold, and axis color to transparent
        c.yAxis().setTitle("Revenue (USD millions)", "Arial Bold Italic", 10);
        c.yAxis().setLabelStyle("Arial Bold", 8);
        c.yAxis().setColors(Chart.Transparent);

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

        // Add a line layer to the chart
        LineLayer 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(
            Chart.CircleSymbol, 9);
        layer.addDataSet(data1, 0x00ff00, "Atom Synthesizer").setDataSymbol(
            Chart.DiamondSymbol, 11);
        layer.addDataSet(data2, 0xff6600, "Proton Cannon").setDataSymbol(
            Chart.Cross2Shape(), 11);

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

        // Convert the labels on the x-axis to a CDMLTable
        CDMLTable table = c.xAxis().makeLabelTable();

        // Set the default top/bottom margins of the cells to 3 pixels
        table.getStyle().setMargin2(0, 0, 3, 3);

        // Use Arial Bold as the font for the first row
        table.getRowStyle(0).setFontStyle("Arial Bold");

        //
        // We can add more information to the table. In this sample code, we add the
        // data series and the legend icons to the table.
        //

        // Add 3 more rows to the table. Set the background of the 1st and 3rd rows
        // to light grey (eeeeee).
        table.appendRow().setBackground(0xeeeeee, Chart.LineColor);
        table.appendRow();
        table.appendRow().setBackground(0xeeeeee, Chart.LineColor);

        // Put the values of the 3 data series to the cells in the 3 rows
        for (int i = 0; i < data0.length; ++i) {
            table.setText(i, 1, String.valueOf(data0[i]));
            table.setText(i, 2, String.valueOf(data1[i]));
            table.setText(i, 3, String.valueOf(data2[i]));
        }

        // Insert a column on the left for the legend icons. Use 5 pixels left/right
        // margins and 3 pixels top/bottom margins for the cells in this column.
        table.insertCol(0).setMargin2(5, 5, 3, 3);

        // The top cell is set to transparent, so it is invisible
        table.getCell(0, 0).setBackground(Chart.Transparent, Chart.Transparent);

        // The other 3 cells are set to the legend icons of the 3 data series
        table.setText(0, 1, layer.getLegendIcon(0));
        table.setText(0, 2, layer.getLegendIcon(1));
        table.setText(0, 3, layer.getLegendIcon(2));

        // Layout legend box first, so we can get its size
        c.layoutLegend();

        // Adjust the plot area size, such that the bounding box (inclusive of axes)
        // is 2 pixels from the left, right and bottom edge, and is just under the
        // legend box.
        c.packPlotArea(2, legendBox.getTopY() + legendBox.getHeight(), c.getWidth() -
            3, c.getHeight() - 3);

        // After determining the exact plot area position, we may adjust the legend
        // box and the title positions so that they are centered relative to the plot
        // area (instead of the chart)
        legendBox.setPos(plotArea.getLeftX() + (plotArea.getWidth() -
            legendBox.getWidth()) / 2, legendBox.getTopY());
        title.setPos(plotArea.getLeftX() + (plotArea.getWidth() - title.getWidth()) /
            2, title.getTopY());

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='Revenue of {dataSetName} in {xLabel}: US$ {value}M'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new datatable();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


Data Table (2)

Data Table (2)

This example demonstrates putting a data table under the x-axis and extend it with additional computed values.

Similar to the previous example Data Table (1), in this example, Axis.makeLabelTable is used to convert the axis labels to a table. The returned CDMLTable object is used to add more content to the table and to configure the appearance of the table.

  • 3 rows are added to the table using CDMLTable.appendRow. The first 2 rows are used to display the data values of the two data series. The last row is used to display the percentage differences between the data values. CDML is used in the last row to format the texts, so that they are green for positive values, and red for negative values.

  • A column is added to the left of the table using CDMLTable.insertCol, showing the title for the rows.

  • The icons for the data sets are obtained using Layer.getLegendIcon. Note that the icons are represented as CDML, so they can be mixed with other text. In this example, the icons are appended with the names of the data sets.

  • A column is added to the right of the table using CDMLTable.appendCol to show the total values and their percentage difference.

Source Code Listing

[JSP Version] jspdemo/datatable2.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the line chart
double[] data0 = {410, 420, 500, 590};
double[] data1 = {500, 370, 680, 850};
String[] labels = {"Q1", "Q2", "Q3", "Q4"};

// Create a XYChart object of size 600 x 400 pixels
XYChart c = new XYChart(600, 400);

// Add a title to the chart using 18 pts Times Bold Italic font
TextBox title = c.addTitle("Product Line Global Revenue",
    "Times New Roman Bold Italic", 18);

// Tentatively set the plotarea at (50, 55) and of (chart_width - 100) x
// (chart_height - 150) pixels in size. Use a vertical gradient color from sky blue
// (aaccff) t0 light blue (f9f9ff) as background. Set both horizontal and vertical
// grid lines to dotted semi-transprent black (aa000000).
PlotArea plotArea = c.setPlotArea(50, 55, c.getWidth() - 100, c.getHeight() - 150,
    c.linearGradientColor(0, 55, 0, 55 + c.getHeight() - 150, 0xaaccff, 0xf9fcff),
    -1, -1, c.dashLineColor(0xaa000000, Chart.DotLine), -1);

// Set y-axis title using 12 points Arial Bold Italic font, and set its position 10
// pixels from the axis.
c.yAxis().setTitle("Revenue (USD millions)", "Arial Bold Italic", 12);
c.yAxis().setTitlePos(Chart.Left, 10);

// Set y-axis label style to 10 points Arial Bold and axis color to transparent
c.yAxis().setLabelStyle("Arial Bold", 10);
c.yAxis().setColors(Chart.Transparent);

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

// Add a bar layer to the chart with side layout
BarLayer layer = c.addBarLayer2(Chart.Side);

// Add two data sets to the bar layer
layer.addDataSet(data0, 0xff6600, "FY 2007");
layer.addDataSet(data1, 0x0088ff, "FY 2008");

// Use soft lighting effect with light direction from the left
layer.setBorderColor(Chart.Transparent, Chart.softLighting(Chart.Left));

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

// Convert the labels on the x-axis to a CDMLTable
CDMLTable table = c.xAxis().makeLabelTable();

// Set the default left/right margins to 5 pixels and top/bottom margins to 3 pixels.
// Set the default font size to 10 points
TextBox cellStyle = table.getStyle();
cellStyle.setMargin2(5, 5, 4, 3);
cellStyle.setFontSize(10);

// Set the first row to use Arial Bold font, with a light grey (eeeeee) background.
TextBox firstRowStyle = table.getRowStyle(0);
firstRowStyle.setFontStyle("Arial Bold");
firstRowStyle.setBackground(0xeeeeee, Chart.LineColor);

//
// We can add more information to the table. In this sample code, we add the data
// series and the legend icons to the table.
//

// Add 3 more rows to the table. Set the background of the 2nd row to light grey
// (eeeeee).
table.appendRow();
table.appendRow().setBackground(0xeeeeee, Chart.LineColor);
table.appendRow();

// Put the values of the 2 data series in the first 2 rows. Put the percentage
// differences in the 3rd row.
for (int i = 0; i < data0.length; ++i) {
    table.setText(i, 1, String.valueOf(data0[i]));
    table.setText(i, 2, String.valueOf(data1[i]));

    double percentageDiff = 100.0 * (data1[i] - data0[i]) / data0[i];

    // Use red or green color depending on whether the difference is positive or
    // negative
    String formatString = "<*color=008800*>+{value|1}%";
    if (percentageDiff < 0) {
        formatString = "<*color=cc0000*>{value|1}%";
    }
    table.setText(i, 3, c.formatValue(percentageDiff, formatString));
}

// Insert a column on the left for the legend icons using Arial Bold font.
table.insertCol(0).setFontStyle("Arial Bold");

// The top cell is set to transparent, so it is invisible
table.getCell(0, 0).setBackground(Chart.Transparent, Chart.Transparent);

// The next 2 cells are set to the legend icons and names of the 2 data series
table.setText(0, 1, layer.getLegendIcon(0) + "  FY 2007");
table.setText(0, 2, layer.getLegendIcon(1) + "  FY 2008");

// The last cell is set to "Change"
table.setText(0, 3, "Change");

// Append a column on the right for the total values.
table.appendCol();

// Put "Total" in the top cell as the heading of this column
table.setText(table.getColCount() - 1, 0, "Total");

// The next two cells are the total of the data series
double total0 = new ArrayMath(data0).sum();
double total1 = new ArrayMath(data1).sum();
table.setText(table.getColCount() - 1, 1, String.valueOf(total0));
table.setText(table.getColCount() - 1, 2, String.valueOf(total1));

// The last cell is the percentage differences of the total
double totalPercentageDiff = (total1 - total0) / total0 * 100;

// Use red or green color depending on whether the difference is positive or negative
String totalFormatString = "<*color=008800*>+{value|1}%";
if (totalPercentageDiff < 0) {
    totalFormatString = "<*color=cc0000*>{value|1}%";
}
table.setText(table.getColCount() - 1, 3, c.formatValue(totalPercentageDiff,
    totalFormatString));

//
// We now demonstrate how to adjust the plot area positions, to allow space for the
// newly inserted left and right columns in the table.
//

// We layout the axis first in order to get the axis metrics (including table
// metrics)
c.layoutAxes();

// If the first column is wider than the left y-axis, we need to reserve for some
// left margin to ensure the first column stays within the chart.
int leftMargin = 0;
if (table.getColWidth(0) > c.yAxis().getThickness()) {
    leftMargin = table.getColWidth(0) - c.yAxis().getThickness();
}

// Similarly, we need to reserve some right margin for the last column
int rightMargin = table.getColWidth(table.getColCount() - 1);

// Adjust the plot area size, such that the bounding box (inclusive of axes) using
// the given left and right margin, plus 2 more pixels. Put the plot area 10 pixels
// below the title and use 2 pixels as the bottom margin. from the left, right and
// bottom edge, and is just under the legend box.
c.packPlotArea(leftMargin + 2, title.getHeight() + 10, c.getWidth() - 3 -
    rightMargin, c.getHeight() - 3);

// After determining the exact plot area position, we may adjust title position so
// that it is centered relative to the plot area (instead of the chart)
title.setPos(plotArea.getLeftX() + (plotArea.getWidth() - title.getWidth()) / 2,
    title.getTopY());

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='Revenue in {xLabel} {dataSetName}: US$ {value}M'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Data Table (2)
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/datatable2.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class datatable2 implements DemoModule
{
    //Name of demo program
    public String toString() { return "Data Table (2)"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the line chart
        double[] data0 = {410, 420, 500, 590};
        double[] data1 = {500, 370, 680, 850};
        String[] labels = {"Q1", "Q2", "Q3", "Q4"};

        // Create a XYChart object of size 600 x 400 pixels
        XYChart c = new XYChart(600, 400);

        // Add a title to the chart using 18 pts Times Bold Italic font
        TextBox title = c.addTitle("Product Line Global Revenue",
            "Times New Roman Bold Italic", 18);

        // Tentatively set the plotarea at (50, 55) and of (chart_width - 100) x
        // (chart_height - 150) pixels in size. Use a vertical gradient color from
        // sky blue (aaccff) t0 light blue (f9f9ff) as background. Set both
        // horizontal and vertical grid lines to dotted semi-transprent black
        // (aa000000).
        PlotArea plotArea = c.setPlotArea(50, 55, c.getWidth() - 100, c.getHeight() -
            150, c.linearGradientColor(0, 55, 0, 55 + c.getHeight() - 150, 0xaaccff,
            0xf9fcff), -1, -1, c.dashLineColor(0xaa000000, Chart.DotLine), -1);

        // Set y-axis title using 12 points Arial Bold Italic font, and set its
        // position 10 pixels from the axis.
        c.yAxis().setTitle("Revenue (USD millions)", "Arial Bold Italic", 12);
        c.yAxis().setTitlePos(Chart.Left, 10);

        // Set y-axis label style to 10 points Arial Bold and axis color to
        // transparent
        c.yAxis().setLabelStyle("Arial Bold", 10);
        c.yAxis().setColors(Chart.Transparent);

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

        // Add a bar layer to the chart with side layout
        BarLayer layer = c.addBarLayer2(Chart.Side);

        // Add two data sets to the bar layer
        layer.addDataSet(data0, 0xff6600, "FY 2007");
        layer.addDataSet(data1, 0x0088ff, "FY 2008");

        // Use soft lighting effect with light direction from the left
        layer.setBorderColor(Chart.Transparent, Chart.softLighting(Chart.Left));

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

        // Convert the labels on the x-axis to a CDMLTable
        CDMLTable table = c.xAxis().makeLabelTable();

        // Set the default left/right margins to 5 pixels and top/bottom margins to 3
        // pixels. Set the default font size to 10 points
        TextBox cellStyle = table.getStyle();
        cellStyle.setMargin2(5, 5, 4, 3);
        cellStyle.setFontSize(10);

        // Set the first row to use Arial Bold font, with a light grey (eeeeee)
        // background.
        TextBox firstRowStyle = table.getRowStyle(0);
        firstRowStyle.setFontStyle("Arial Bold");
        firstRowStyle.setBackground(0xeeeeee, Chart.LineColor);

        //
        // We can add more information to the table. In this sample code, we add the
        // data series and the legend icons to the table.
        //

        // Add 3 more rows to the table. Set the background of the 2nd row to light
        // grey (eeeeee).
        table.appendRow();
        table.appendRow().setBackground(0xeeeeee, Chart.LineColor);
        table.appendRow();

        // Put the values of the 2 data series in the first 2 rows. Put the
        // percentage differences in the 3rd row.
        for (int i = 0; i < data0.length; ++i) {
            table.setText(i, 1, String.valueOf(data0[i]));
            table.setText(i, 2, String.valueOf(data1[i]));

            double percentageDiff = 100.0 * (data1[i] - data0[i]) / data0[i];

            // Use red or green color depending on whether the difference is positive
            // or negative
            String formatString = "<*color=008800*>+{value|1}%";
            if (percentageDiff < 0) {
                formatString = "<*color=cc0000*>{value|1}%";
            }
            table.setText(i, 3, c.formatValue(percentageDiff, formatString));
        }

        // Insert a column on the left for the legend icons using Arial Bold font.
        table.insertCol(0).setFontStyle("Arial Bold");

        // The top cell is set to transparent, so it is invisible
        table.getCell(0, 0).setBackground(Chart.Transparent, Chart.Transparent);

        // The next 2 cells are set to the legend icons and names of the 2 data
        // series
        table.setText(0, 1, layer.getLegendIcon(0) + "  FY 2007");
        table.setText(0, 2, layer.getLegendIcon(1) + "  FY 2008");

        // The last cell is set to "Change"
        table.setText(0, 3, "Change");

        // Append a column on the right for the total values.
        table.appendCol();

        // Put "Total" in the top cell as the heading of this column
        table.setText(table.getColCount() - 1, 0, "Total");

        // The next two cells are the total of the data series
        double total0 = new ArrayMath(data0).sum();
        double total1 = new ArrayMath(data1).sum();
        table.setText(table.getColCount() - 1, 1, String.valueOf(total0));
        table.setText(table.getColCount() - 1, 2, String.valueOf(total1));

        // The last cell is the percentage differences of the total
        double totalPercentageDiff = (total1 - total0) / total0 * 100;

        // Use red or green color depending on whether the difference is positive or
        // negative
        String totalFormatString = "<*color=008800*>+{value|1}%";
        if (totalPercentageDiff < 0) {
            totalFormatString = "<*color=cc0000*>{value|1}%";
        }
        table.setText(table.getColCount() - 1, 3, c.formatValue(totalPercentageDiff,
            totalFormatString));

        //
        // We now demonstrate how to adjust the plot area positions, to allow space
        // for the newly inserted left and right columns in the table.
        //

        // We layout the axis first in order to get the axis metrics (including table
        // metrics)
        c.layoutAxes();

        // If the first column is wider than the left y-axis, we need to reserve for
        // some left margin to ensure the first column stays within the chart.
        int leftMargin = 0;
        if (table.getColWidth(0) > c.yAxis().getThickness()) {
            leftMargin = table.getColWidth(0) - c.yAxis().getThickness();
        }

        // Similarly, we need to reserve some right margin for the last column
        int rightMargin = table.getColWidth(table.getColCount() - 1);

        // Adjust the plot area size, such that the bounding box (inclusive of axes)
        // using the given left and right margin, plus 2 more pixels. Put the plot
        // area 10 pixels below the title and use 2 pixels as the bottom margin. from
        // the left, right and bottom edge, and is just under the legend box.
        c.packPlotArea(leftMargin + 2, title.getHeight() + 10, c.getWidth() - 3 -
            rightMargin, c.getHeight() - 3);

        // After determining the exact plot area position, we may adjust title
        // position so that it is centered relative to the plot area (instead of the
        // chart)
        title.setPos(plotArea.getLeftX() + (plotArea.getWidth() - title.getWidth()) /
            2, title.getTopY());

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='Revenue in {xLabel} {dataSetName}: US$ {value}M'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new datatable2();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/fontxy.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the chart
double[] data0 = {100, 125, 245, 147, 67};
double[] data1 = {85, 156, 179, 211, 123};
double[] data2 = {97, 87, 56, 267, 157};
String[] labels = {"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
XYChart c = new 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
BarLayer layer = c.addBarLayer2(Chart.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, Chart.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.
ChartDirector.TextBox 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(Chart.SameAsMainColor, Chart.Transparent, 1);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName} on {xLabel}: {value} MBytes/hour'");
%>
<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 color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/fontxy.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class fontxy implements DemoModule
{
    //Name of demo program
    public String toString() { return "Text Style and Colors"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the chart
        double[] data0 = {100, 125, 245, 147, 67};
        double[] data1 = {85, 156, 179, 211, 123};
        double[] data2 = {97, 87, 56, 267, 157};
        String[] labels = {"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
        XYChart c = new 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
        BarLayer layer = c.addBarLayer2(Chart.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, Chart.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.
        ChartDirector.TextBox 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(Chart.SameAsMainColor, Chart.Transparent, 1);

        // Output the chart
        viewer.setChart(c);

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

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new fontxy();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/background.jsp
<%@page import="ChartDirector.*" %>
<%@page import="javax.servlet.http.*" %>
<%!
// A simple structure to represent a chart image with an image map
private static class ImageWithHotSpot
{
    String imageURL;
    String imageMap;
}

// Function to create the demo charts
ImageWithHotSpot createChart(HttpServletRequest request, int index)
{
    // The data for the chart
    double[] data = {85, 156, 179.5, 211, 123};
    String[] labels = {"Mon", "Tue", "Wed", "Thu", "Fri"};

    // Create a XYChart object of size 270 x 270 pixels
    XYChart c = new XYChart(270, 270);

    //Set search path to current JSP directory for loading icon images
    c.setSearchPath(getServletConfig().getServletContext(), request);

    // Set the plot area at (40, 32) and of size 200 x 200 pixels
    PlotArea plotarea = c.setPlotArea(40, 32, 200, 200);

    // Set the background style based on the input parameter
    if (index == 0) {
        // Has wallpaper image
        c.setWallpaper("tile.gif");
    } else if (index == 1) {
        // Use a background image as the plot area background
        plotarea.setBackground2("bg.png");
    } else if (index == 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(Chart.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
    ImageWithHotSpot ret = new ImageWithHotSpot();
    ret.imageURL = c.makeSession(request, "chart" + index);

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

    return ret;
}
%>
<%
ImageWithHotSpot chart0 = createChart(request, 0);
ImageWithHotSpot chart1 = createChart(request, 1);
ImageWithHotSpot chart2 = createChart(request, 2);
ImageWithHotSpot chart3 = createChart(request, 3);
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Background and Wallpaper
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart0.imageURL)%>'
    usemap="#map0" border="0">
<map name="map0"><%=chart0.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1.imageURL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=chart1.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart2.imageURL)%>'
    usemap="#map2" border="0">
<map name="map2"><%=chart2.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart3.imageURL)%>'
    usemap="#map3" border="0">
<map name="map3"><%=chart3.imageMap%></map>
</body>
</html>

[Java Version] javademo/background.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class background implements DemoModule
{
    //Name of demo program
    public String toString() { return "Background and Wallpaper"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 4; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the chart
        double[] data = {85, 156, 179.5, 211, 123};
        String[] labels = {"Mon", "Tue", "Wed", "Thu", "Fri"};

        // Create a XYChart object of size 270 x 270 pixels
        XYChart c = new XYChart(270, 270);

        // Set the plot area at (40, 32) and of size 200 x 200 pixels
        PlotArea plotarea = c.setPlotArea(40, 32, 200, 200);

        // Set the background style based on the input parameter
        if (index == 0) {
            // Has wallpaper image
            c.setWallpaper("tile.gif");
        } else if (index == 1) {
            // Use a background image as the plot area background
            plotarea.setBackground2("bg.png");
        } else if (index == 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(Chart.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
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='Revenue for {xLabel}: US${value}K'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new background();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);
        frame.getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
        frame.setSize(800, 450);

        // Create the charts and put them in the content pane
        for (int i = 0; i < demo.getNoOfCharts(); ++i)
        {
            ChartViewer viewer = new ChartViewer();
            demo.createChart(viewer, i);
            frame.getContentPane().add(viewer);
        }

        // Display the window
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/logaxis.jsp
<%@page import="ChartDirector.*" %>
<%@page import="javax.servlet.http.*" %>
<%!
// A simple structure to represent a chart image with an image map
private static class ImageWithHotSpot
{
    String imageURL;
    String imageMap;
}

// Function to create the demo charts
ImageWithHotSpot createChart(HttpServletRequest request, int index)
{
    // The data for the chart
    double[] data = {100, 125, 260, 147, 67};
    String[] labels = {"Mon", "Tue", "Wed", "Thu", "Fri"};

    // Create a XYChart object of size 200 x 180 pixels
    XYChart c = new 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 (index == 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
    ImageWithHotSpot ret = new ImageWithHotSpot();
    ret.imageURL = c.makeSession(request, "chart" + index);

    // Include tool tip for the chart
    ret.imageMap = c.getHTMLImageMap("", "",
        "title='Mileage on {xLabel}: {value} miles'");

    return ret;
}
%>
<%
ImageWithHotSpot chart0 = createChart(request, 0);
ImageWithHotSpot chart1 = createChart(request, 1);
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Log Scale Axis
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart0.imageURL)%>'
    usemap="#map0" border="0">
<map name="map0"><%=chart0.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1.imageURL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=chart1.imageMap%></map>
</body>
</html>

[Java Version] javademo/logaxis.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class logaxis implements DemoModule
{
    //Name of demo program
    public String toString() { return "Log Scale Axis"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 2; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the chart
        double[] data = {100, 125, 260, 147, 67};
        String[] labels = {"Mon", "Tue", "Wed", "Thu", "Fri"};

        // Create a XYChart object of size 200 x 180 pixels
        XYChart c = new 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 (index == 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
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='Mileage on {xLabel}: {value} miles'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new logaxis();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);
        frame.getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
        frame.setSize(800, 450);

        // Create the charts and put them in the content pane
        for (int i = 0; i < demo.getNoOfCharts(); ++i)
        {
            ChartViewer viewer = new ChartViewer();
            demo.createChart(viewer, i);
            frame.getContentPane().add(viewer);
        }

        // Display the window
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/axisscale.jsp
<%@page import="ChartDirector.*" %>
<%@page import="javax.servlet.http.*" %>
<%!
// A simple structure to represent a chart image with an image map
private static class ImageWithHotSpot
{
    String imageURL;
    String imageMap;
}

// Function to create the demo charts
ImageWithHotSpot createChart(HttpServletRequest request, int index)
{
    // The data for the chart
    double[] data = {5.5, 3.5, -3.7, 1.7, -1.4, 3.3};
    String[] labels = {"Jan", "Feb", "Mar", "Apr", "May", "Jun"};

    // Create a XYChart object of size 200 x 190 pixels
    XYChart c = new XYChart(200, 190);

    // Set the plot area at (30, 20) and of size 140 x 140 pixels
    c.setPlotArea(30, 20, 140, 140);

    // Configure the axis as according to the input parameter
    if (index == 0) {
        c.addTitle("No Axis Extension", "Arial", 8);
    } else if (index == 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 (index == 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 (index == 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
    ImageWithHotSpot ret = new ImageWithHotSpot();
    ret.imageURL = c.makeSession(request, "chart" + index);

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

    return ret;
}
%>
<%
ImageWithHotSpot chart0 = createChart(request, 0);
ImageWithHotSpot chart1 = createChart(request, 1);
ImageWithHotSpot chart2 = createChart(request, 2);
ImageWithHotSpot chart3 = createChart(request, 3);
ImageWithHotSpot chart4 = createChart(request, 4);
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Y-Axis Scaling
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart0.imageURL)%>'
    usemap="#map0" border="0">
<map name="map0"><%=chart0.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1.imageURL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=chart1.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart2.imageURL)%>'
    usemap="#map2" border="0">
<map name="map2"><%=chart2.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart3.imageURL)%>'
    usemap="#map3" border="0">
<map name="map3"><%=chart3.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart4.imageURL)%>'
    usemap="#map4" border="0">
<map name="map4"><%=chart4.imageMap%></map>
</body>
</html>

[Java Version] javademo/axisscale.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class axisscale implements DemoModule
{
    //Name of demo program
    public String toString() { return "Y-Axis Scaling"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 5; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the chart
        double[] data = {5.5, 3.5, -3.7, 1.7, -1.4, 3.3};
        String[] labels = {"Jan", "Feb", "Mar", "Apr", "May", "Jun"};

        // Create a XYChart object of size 200 x 190 pixels
        XYChart c = new XYChart(200, 190);

        // Set the plot area at (30, 20) and of size 140 x 140 pixels
        c.setPlotArea(30, 20, 140, 140);

        // Configure the axis as according to the input parameter
        if (index == 0) {
            c.addTitle("No Axis Extension", "Arial", 8);
        } else if (index == 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 (index == 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 (index == 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
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='ROI for {xLabel}: {value}%'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new axisscale();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);
        frame.getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
        frame.setSize(800, 450);

        // Create the charts and put them in the content pane
        for (int i = 0; i < demo.getNoOfCharts(); ++i)
        {
            ChartViewer viewer = new ChartViewer();
            demo.createChart(viewer, i);
            frame.getContentPane().add(viewer);
        }

        // Display the window
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/ticks.jsp
<%@page import="ChartDirector.*" %>
<%@page import="javax.servlet.http.*" %>
<%!
// A simple structure to represent a chart image with an image map
private static class ImageWithHotSpot
{
    String imageURL;
    String imageMap;
}

// Function to create the demo charts
ImageWithHotSpot createChart(HttpServletRequest request, int index)
{
    // The data for the chart
    double[] data = {100, 125, 265, 147, 67, 105};
    String[] labels = {"Jan", "Feb", "Mar", "Apr", "May", "Jun"};

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

    // Set the plot area at (27, 25) and of size 200 x 200 pixels
    c.setPlotArea(27, 25, 200, 200);

    if (index == 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
    ImageWithHotSpot ret = new ImageWithHotSpot();
    ret.imageURL = c.makeSession(request, "chart" + index);

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

    return ret;
}
%>
<%
ImageWithHotSpot chart0 = createChart(request, 0);
ImageWithHotSpot chart1 = createChart(request, 1);
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Tick Density
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart0.imageURL)%>'
    usemap="#map0" border="0">
<map name="map0"><%=chart0.imageMap%></map>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1.imageURL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=chart1.imageMap%></map>
</body>
</html>

[Java Version] javademo/ticks.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class ticks implements DemoModule
{
    //Name of demo program
    public String toString() { return "Tick Density"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 2; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the chart
        double[] data = {100, 125, 265, 147, 67, 105};
        String[] labels = {"Jan", "Feb", "Mar", "Apr", "May", "Jun"};

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

        // Set the plot area at (27, 25) and of size 200 x 200 pixels
        c.setPlotArea(27, 25, 200, 200);

        if (index == 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
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='Revenue for {xLabel}: US${value}M'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new ticks();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);
        frame.getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
        frame.setSize(800, 450);

        // Create the charts and put them in the content pane
        for (int i = 0; i < demo.getNoOfCharts(); ++i)
        {
            ChartViewer viewer = new ChartViewer();
            demo.createChart(viewer, i);
            frame.getContentPane().add(viewer);
        }

        // Display the window
        frame.setVisible(true);
    }
}


Surface Charts

Surface Charts

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

Title | Description
Surface Chart (1) | Demonstrates the basic steps in creating surface charts.
Surface Chart (2) | Extends the Surface Chart (1) example by adding surface grid and contour lines, and using alternative view angles and continuous coloring.
Surface Chart (3) | Demonstrates using deep perspective. Also demonstrates surface grid lines of different line styles.
Scattered Data Surface Chart | Demonstrates using scattered data for the surface chart. Also demonstrates hiding the plot region walls and changing their thickness and colors.
Surface Chart Axis Types | The example demonstrates different axis scale types for the surface charts.
Surface Lighting | Demonstrates the effects of various surface lighting parameters, configured using SurfaceChart.setLighting.
Surface Shading | Demonstrates the effects of various surface shading methods, configured using SurfaceChart.setShadingMode.
Surface Wireframe | Demonstrates the rectangular and triangular wireframes of a surface at different interpolation levels, configured using SurfaceChart.setShadingMode and SurfaceChart.setInterpolation.
Surface Perspective | Demonstrates the effects of various perspective depth, configured using ThreeDChart.setPerspective.


Surface Chart (1)

Surface Chart (1)

This example demonstrates the basic steps in creating surface charts.

  • Create a SurfaceChart object using SurfaceChart.SurfaceChart.

  • Specify the position and size of the plot region using ThreeDChart.setPlotRegion.

  • Set data to the chart using SurfaceChart.setData.

  • Interpolate the data using SurfaceChart.setInterpolation for extra smoothness of the surface.

  • Set the position of the color axis (the color legend) using ThreeDChart.setColorAxis.

  • Add chart and axis titles using BaseChart.addTitle and Axis.setTitle.

  • Generate the chart using BaseChart.makeSession (JSP version) or BaseChart.makeImage (Java version).

Source Code Listing

[JSP Version] jspdemo/surface.jsp
<%@page import="ChartDirector.*" %>
<%
// The x and y coordinates of the grid
double[] dataX = {-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8,
    9, 10};
double[] dataY = {-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8,
    9, 10};

// The values at the grid points. In this example, we will compute the values using
// the formula z = x * sin(y) + y * sin(x).
double[] dataZ = new double[(dataX.length) * (dataY.length)];
for (int yIndex = 0; yIndex < dataY.length; ++yIndex) {
    double y = dataY[yIndex];
    for (int xIndex = 0; xIndex < dataX.length; ++xIndex) {
        double x = dataX[xIndex];
        dataZ[yIndex * (dataX.length) + xIndex] = x * Math.sin(y) + y * Math.sin(x);
    }
}

// Create a SurfaceChart object of size 720 x 600 pixels
SurfaceChart c = new SurfaceChart(720, 600);

// Add a title to the chart using 20 points Times New Roman Italic font
c.addTitle("Surface Energy Density   ", "Times New Roman Italic", 20);

// Set the center of the plot region at (350, 280), and set width x depth x height to
// 360 x 360 x 270 pixels
c.setPlotRegion(350, 280, 360, 360, 270);

// Set the data to use to plot the chart
c.setData(dataX, dataY, dataZ);

// Spline interpolate data to a 80 x 80 grid for a smooth surface
c.setInterpolation(80, 80);

// Add a color axis (the legend) in which the left center is anchored at (645, 270).
// Set the length to 200 pixels and the labels on the right side.
c.setColorAxis(645, 270, Chart.Left, 200, Chart.Right);

// Set the x, y and z axis titles using 10 points Arial Bold font
c.xAxis().setTitle("X (nm)", "Arial Bold", 10);
c.yAxis().setTitle("Y (nm)", "Arial Bold", 10);
c.zAxis().setTitle("Energy Density (J/m<*font,super*>2<*/font*>)", "Arial Bold", 10);

// Output the chart
String chart1URL = c.makeSession(request, "chart1", Chart.JPG);
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Surface Chart (1)
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'>
</body>
</html>

[Java Version] javademo/surface.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class surface implements DemoModule
{
    //Name of demo program
    public String toString() { return "Surface Chart (1)"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The x and y coordinates of the grid
        double[] dataX = {-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5,
            6, 7, 8, 9, 10};
        double[] dataY = {-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5,
            6, 7, 8, 9, 10};

        // The values at the grid points. In this example, we will compute the values
        // using the formula z = x * sin(y) + y * sin(x).
        double[] dataZ = new double[(dataX.length) * (dataY.length)];
        for (int yIndex = 0; yIndex < dataY.length; ++yIndex) {
            double y = dataY[yIndex];
            for (int xIndex = 0; xIndex < dataX.length; ++xIndex) {
                double x = dataX[xIndex];
                dataZ[yIndex * (dataX.length) + xIndex] = x * Math.sin(y) + y *
                    Math.sin(x);
            }
        }

        // Create a SurfaceChart object of size 720 x 600 pixels
        SurfaceChart c = new SurfaceChart(720, 600);

        // Add a title to the chart using 20 points Times New Roman Italic font
        c.addTitle("Surface Energy Density   ", "Times New Roman Italic", 20);

        // Set the center of the plot region at (350, 280), and set width x depth x
        // height to 360 x 360 x 270 pixels
        c.setPlotRegion(350, 280, 360, 360, 270);

        // Set the data to use to plot the chart
        c.setData(dataX, dataY, dataZ);

        // Spline interpolate data to a 80 x 80 grid for a smooth surface
        c.setInterpolation(80, 80);

        // Add a color axis (the legend) in which the left center is anchored at
        // (645, 270). Set the length to 200 pixels and the labels on the right side.
        c.setColorAxis(645, 270, Chart.Left, 200, Chart.Right);

        // Set the x, y and z axis titles using 10 points Arial Bold font
        c.xAxis().setTitle("X (nm)", "Arial Bold", 10);
        c.yAxis().setTitle("Y (nm)", "Arial Bold", 10);
        c.zAxis().setTitle("Energy Density (J/m<*font,super*>2<*/font*>)",
            "Arial Bold", 10);

        // Output the chart
        viewer.setChart(c);
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new surface();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


Surface Chart (2)

Surface Chart (2)

This example extends the Surface Chart (1) example by adding surface grid and contour lines, and using alternative view angles and continuous coloring.

  • The alternative view angles are set using ThreeDChart.setViewAngle.

  • The surface grid lines are added using SurfaceChart.setSurfaceAxisGrid.

  • The contour lines are added using SurfaceChart.setContourColor.

  • Note that for both the surface grid and contour lines, semi-transparent line colors are used to make the lines look thin and light.

  • Continuous coloring are configured using ColorAxis.setColorGradient.

Source Code Listing

[JSP Version] jspdemo/surface2.jsp
<%@page import="ChartDirector.*" %>
<%
// The x and y coordinates of the grid
double[] dataX = {0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0};
double[] dataY = {0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0};

// The values at the grid points. In this example, we will compute the values using
// the formula z = sin((x - 0.5) * 2 * pi) * sin((y - 0.5) * 2 * pi)
double[] dataZ = new double[(dataX.length) * (dataY.length)];
for (int yIndex = 0; yIndex < dataY.length; ++yIndex) {
    double y = (dataY[yIndex] - 0.5) * 2 * 3.1416;
    for (int xIndex = 0; xIndex < dataX.length; ++xIndex) {
        double x = (dataX[xIndex] - 0.5) * 2 * 3.1416;
        dataZ[yIndex * (dataX.length) + xIndex] = Math.sin(x) * Math.sin(y);
    }
}

// Create a SurfaceChart object of size 720 x 540 pixels
SurfaceChart c = new SurfaceChart(720, 540);

// Add a title to the chart using 20 points Times New Roman Italic font
c.addTitle("Quantum Wave Function", "Times New Roman Italic", 20);

// Set the center of the plot region at (360, 245), and set width x depth x height to
// 360 x 360 x 270 pixels
c.setPlotRegion(360, 245, 360, 360, 270);

// Set the elevation and rotation angles to 20 and 30 degrees
c.setViewAngle(20, 30);

// Set the data to use to plot the chart
c.setData(dataX, dataY, dataZ);

// Spline interpolate data to a 80 x 80 grid for a smooth surface
c.setInterpolation(80, 80);

// Set surface grid lines to semi-transparent black (dd000000)
c.setSurfaceAxisGrid(0xdd000000);

// Set contour lines to semi-transparent white (80ffffff)
c.setContourColor(0x80ffffff);

// Add a color axis (the legend) in which the left center is anchored at (645, 270).
// Set the length to 200 pixels and the labels on the right side. Use smooth gradient
// coloring.
c.setColorAxis(645, 270, Chart.Left, 200, Chart.Right).setColorGradient();

// Set the x, y and z axis titles using 10 points Arial Bold font
c.xAxis().setTitle("x/L(x)", "Arial Bold", 10);
c.yAxis().setTitle("y/L(y)", "Arial Bold", 10);
c.zAxis().setTitle("Wave Function Amplitude", "Arial Bold", 10);

// Output the chart
String chart1URL = c.makeSession(request, "chart1", Chart.JPG);
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Surface Chart (2)
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'>
</body>
</html>

[Java Version] javademo/surface2.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class surface2 implements DemoModule
{
    //Name of demo program
    public String toString() { return "Surface Chart (2)"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The x and y coordinates of the grid
        double[] dataX = {0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0};
        double[] dataY = {0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0};

        // The values at the grid points. In this example, we will compute the values
        // using the formula z = sin((x - 0.5) * 2 * pi) * sin((y - 0.5) * 2 * pi)
        double[] dataZ = new double[(dataX.length) * (dataY.length)];
        for (int yIndex = 0; yIndex < dataY.length; ++yIndex) {
            double y = (dataY[yIndex] - 0.5) * 2 * 3.1416;
            for (int xIndex = 0; xIndex < dataX.length; ++xIndex) {
                double x = (dataX[xIndex] - 0.5) * 2 * 3.1416;
                dataZ[yIndex * (dataX.length) + xIndex] = Math.sin(x) * Math.sin(y);
            }
        }

        // Create a SurfaceChart object of size 720 x 540 pixels
        SurfaceChart c = new SurfaceChart(720, 540);

        // Add a title to the chart using 20 points Times New Roman Italic font
        c.addTitle("Quantum Wave Function", "Times New Roman Italic", 20);

        // Set the center of the plot region at (360, 245), and set width x depth x
        // height to 360 x 360 x 270 pixels
        c.setPlotRegion(360, 245, 360, 360, 270);

        // Set the elevation and rotation angles to 20 and 30 degrees
        c.setViewAngle(20, 30);

        // Set the data to use to plot the chart
        c.setData(dataX, dataY, dataZ);

        // Spline interpolate data to a 80 x 80 grid for a smooth surface
        c.setInterpolation(80, 80);

        // Set surface grid lines to semi-transparent black (dd000000)
        c.setSurfaceAxisGrid(0xdd000000);

        // Set contour lines to semi-transparent white (80ffffff)
        c.setContourColor(0x80ffffff);

        // Add a color axis (the legend) in which the left center is anchored at
        // (645, 270). Set the length to 200 pixels and the labels on the right side.
        // Use smooth gradient coloring.
        c.setColorAxis(645, 270, Chart.Left, 200, Chart.Right).setColorGradient();

        // Set the x, y and z axis titles using 10 points Arial Bold font
        c.xAxis().setTitle("x/L(x)", "Arial Bold", 10);
        c.yAxis().setTitle("y/L(y)", "Arial Bold", 10);
        c.zAxis().setTitle("Wave Function Amplitude", "Arial Bold", 10);

        // Output the chart
        viewer.setChart(c);
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new surface2();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


Surface Chart (3)

Surface Chart (3)

This example demonstrates using deep perspective. It also demonstrates surface grid lines of different line styles.

  • The deep perspective in this example is configured using ThreeDChart.setPerspective.

  • Like all other lines in ChartDirector, "dash line colors" can be applied to surface grid lines to cause them to draw in dash line styles. In this example, BaseChart.dashLineColor is used to create a dash line color, which is used as the minor surface grid line color in SurfaceChart.setSurfaceAxisGrid.

Source Code Listing

[JSP Version] jspdemo/surface3.jsp
<%@page import="ChartDirector.*" %>
<%
// The x and y coordinates of the grid
double[] dataX = {-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8,
    9, 10};
double[] dataY = {-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8,
    9, 10};

// The values at the grid points. In this example, we will compute the values using
// the formula z = Sin(x * x / 128 - y * y / 256 + 3) * Cos(x / 4 + 1 - Exp(y / 8))
double[] dataZ = new double[(dataX.length) * (dataY.length)];
for (int yIndex = 0; yIndex < dataY.length; ++yIndex) {
    double y = dataY[yIndex];
    for (int xIndex = 0; xIndex < dataX.length; ++xIndex) {
        double x = dataX[xIndex];
        dataZ[yIndex * (dataX.length) + xIndex] = Math.sin(x * x / 128.0 - y * y /
            256.0 + 3) * Math.cos(x / 4.0 + 1 - Math.exp(y / 8.0));
    }
}

// Create a SurfaceChart object of size 750 x 600 pixels
SurfaceChart c = new SurfaceChart(750, 600);

// Add a title to the chart using 20 points Times New Roman Italic font
c.addTitle("Surface Energy Density       ", "Times New Roman Italic", 20);

// Set the center of the plot region at (380, 260), and set width x depth x height to
// 360 x 360 x 270 pixels
c.setPlotRegion(380, 260, 360, 360, 270);

// Set the elevation and rotation angles to 30 and 210 degrees
c.setViewAngle(30, 210);

// Set the perspective level to 60
c.setPerspective(60);

// Set the data to use to plot the chart
c.setData(dataX, dataY, dataZ);

// Spline interpolate data to a 80 x 80 grid for a smooth surface
c.setInterpolation(80, 80);

// Use semi-transparent black (c0000000) for x and y major surface grid lines. Use
// dotted style for x and y minor surface grid lines.
int majorGridColor = 0xc0000000;
int minorGridColor = c.dashLineColor(majorGridColor, Chart.DotLine);
c.setSurfaceAxisGrid(majorGridColor, majorGridColor, minorGridColor, minorGridColor);

// Set contour lines to semi-transparent white (80ffffff)
c.setContourColor(0x80ffffff);

// Add a color axis (the legend) in which the left center is anchored at (665, 280).
// Set the length to 200 pixels and the labels on the right side.
c.setColorAxis(665, 280, Chart.Left, 200, Chart.Right);

// Set the x, y and z axis titles using 12 points Arial Bold font
c.xAxis().setTitle("X Title\nPlaceholder", "Arial Bold", 12);
c.yAxis().setTitle("Y Title\nPlaceholder", "Arial Bold", 12);
c.zAxis().setTitle("Z Title Placeholder", "Arial Bold", 12);

// Output the chart
String chart1URL = c.makeSession(request, "chart1", Chart.JPG);
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Surface Chart (3)
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'>
</body>
</html>

[Java Version] javademo/surface3.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class surface3 implements DemoModule
{
    //Name of demo program
    public String toString() { return "Surface Chart (3)"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The x and y coordinates of the grid
        double[] dataX = {-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5,
            6, 7, 8, 9, 10};
        double[] dataY = {-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5,
            6, 7, 8, 9, 10};

        // The values at the grid points. In this example, we will compute the values
        // using the formula z = Sin(x * x / 128 - y * y / 256 + 3) * Cos(x / 4 + 1 -
        // Exp(y / 8))
        double[] dataZ = new double[(dataX.length) * (dataY.length)];
        for (int yIndex = 0; yIndex < dataY.length; ++yIndex) {
            double y = dataY[yIndex];
            for (int xIndex = 0; xIndex < dataX.length; ++xIndex) {
                double x = dataX[xIndex];
                dataZ[yIndex * (dataX.length) + xIndex] = Math.sin(x * x / 128.0 - y
                     * y / 256.0 + 3) * Math.cos(x / 4.0 + 1 - Math.exp(y / 8.0));
            }
        }

        // Create a SurfaceChart object of size 750 x 600 pixels
        SurfaceChart c = new SurfaceChart(750, 600);

        // Add a title to the chart using 20 points Times New Roman Italic font
        c.addTitle("Surface Energy Density       ", "Times New Roman Italic", 20);

        // Set the center of the plot region at (380, 260), and set width x depth x
        // height to 360 x 360 x 270 pixels
        c.setPlotRegion(380, 260, 360, 360, 270);

        // Set the elevation and rotation angles to 30 and 210 degrees
        c.setViewAngle(30, 210);

        // Set the perspective level to 60
        c.setPerspective(60);

        // Set the data to use to plot the chart
        c.setData(dataX, dataY, dataZ);

        // Spline interpolate data to a 80 x 80 grid for a smooth surface
        c.setInterpolation(80, 80);

        // Use semi-transparent black (c0000000) for x and y major surface grid
        // lines. Use dotted style for x and y minor surface grid lines.
        int majorGridColor = 0xc0000000;
        int minorGridColor = c.dashLineColor(majorGridColor, Chart.DotLine);
        c.setSurfaceAxisGrid(majorGridColor, majorGridColor, minorGridColor,
            minorGridColor);

        // Set contour lines to semi-transparent white (80ffffff)
        c.setContourColor(0x80ffffff);

        // Add a color axis (the legend) in which the left center is anchored at
        // (665, 280). Set the length to 200 pixels and the labels on the right side.
        c.setColorAxis(665, 280, Chart.Left, 200, Chart.Right);

        // Set the x, y and z axis titles using 12 points Arial Bold font
        c.xAxis().setTitle("X Title\nPlaceholder", "Arial Bold", 12);
        c.yAxis().setTitle("Y Title\nPlaceholder", "Arial Bold", 12);
        c.zAxis().setTitle("Z Title Placeholder", "Arial Bold", 12);

        // Output the chart
        viewer.setChart(c);
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new surface3();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


Scattered Data Surface Chart

Scattered Data Surface Chart

This example demonstrates using scattered data for the surface chart. It also demonstrates hiding the plot region walls and changing their thickness and colors.

In previous surface chart examples, the data are gridded, which means the (x, y) coordinates of the data points lie on a rectangular grid. ChartDirector also supports scattered data points, which means the data points can be at arbitrary positions. ChartDirector automatically detects if the data passed to the surface chart using SurfaceChart.setData are gridded or scattered.

In this example, 2 of the 3 plot region walls are hidden using ThreeDChart.setWallVisibility. For the visible wall, its color is set to black using ThreeDChart.setWallColor, its thickness is set to 0 using ThreeDChart.setWallThickness, and its major and minor grid lines are set to white and grey using ThreeDChart.setWallGrid.

Source Code Listing

[JSP Version] jspdemo/scattersurface.jsp
<%@page import="ChartDirector.*" %>
<%
// The (x, y, z) coordinates of the scattered data
double[] dataX = {0.5, 1.9, 4.9, 1.0, 8.9, 9.8, 5.9, 2.9, 6.8, 9.0, 0.0, 8.9, 1.9,
    4.8, 2.4, 3.4, 7.9, 7.5, 4.8, 7.5, 9.5, 0.4, 8.9, 0.9, 5.4, 9.4, 2.9, 8.9, 0.9,
    8.9, 10.0, 1.0, 6.8, 3.8, 9.0, 5.3, 6.4, 4.9, 4.5, 2.0, 5.4, 0.0, 10.0, 3.9, 5.4,
    5.9, 5.8, 0.3, 4.4, 8.3};
double[] dataY = {3.3, 3.0, 0.7, 1.0, 9.3, 4.5, 8.4, 0.1, 0.8, 0.1, 9.3, 1.8, 4.3,
    1.3, 2.3, 5.4, 6.9, 9.0, 9.8, 7.5, 1.8, 1.4, 4.5, 7.8, 3.8, 4.0, 2.9, 2.4, 3.9,
    2.9, 2.3, 9.3, 2.0, 3.4, 4.8, 2.3, 3.4, 2.3, 1.5, 7.8, 4.5, 0.9, 6.3, 2.4, 6.9,
    2.8, 1.3, 2.9, 6.4, 6.3};
double[] dataZ = {6.6, 12.5, 7.4, 6.2, 9.6, 13.6, 19.9, 2.2, 6.9, 3.4, 8.7, 8.4, 7.8,
    8.0, 9.4, 11.9, 9.6, 15.7, 12.0, 13.3, 9.6, 6.4, 9.0, 6.9, 4.6, 9.7, 10.6, 9.2,
    7.0, 6.9, 9.7, 8.6, 8.0, 13.6, 13.2, 5.9, 9.0, 3.2, 8.3, 9.7, 8.2, 6.1, 8.7, 5.6,
    14.9, 9.8, 9.3, 5.1, 10.8, 9.8};

// Create a SurfaceChart object of size 680 x 550 pixels. Set background to brushed
// silver and border to grey (888888). Set the top-left and bottom-right corners to
// rounded corners with 20 pixels radius.
SurfaceChart c = new SurfaceChart(680, 550, Chart.brushedSilverColor(), 0x888888);
c.setRoundedFrame(0xffffff, 20, 0, 20, 0);

// Add a title to the chart using 20 points Times New Roman Italic font. Set
// top/bottom margin to 8 pixels.
TextBox title = c.addTitle("Surface Created Using Scattered Data Points",
    "Times New Roman Italic", 20);
title.setMargin2(0, 0, 8, 8);

// Add a 2 pixel wide black (000000) separator line under the title
c.addLine(10, title.getHeight(), c.getWidth() - 10, title.getHeight(), 0x000000, 2);

// Set the center of the plot region at (290, 235), and set width x depth x height to
// 360 x 360 x 180 pixels
c.setPlotRegion(290, 235, 360, 360, 180);

// Set the elevation and rotation angles to 45 and -45 degrees
c.setViewAngle(45, -45);

// Set the perspective level to 30
c.setPerspective(30);

// Set the data to use to plot the chart
c.setData(dataX, dataY, dataZ);

// Add a color axis (the legend) in which the top right corner is anchored at (660,
// 80). Set the length to 200 pixels and the labels on the right side.
ColorAxis cAxis = c.setColorAxis(660, 80, Chart.TopRight, 200, Chart.Right);

// Set the color axis title with 12 points Arial Bold font
cAxis.setTitle("Z Title Placeholder", "Arial Bold", 12);

// Add a bounding box with light grey (eeeeee) background and grey (888888) border.
// Set the top-left and bottom-right corners to rounded corners of  10 pixels radius.
cAxis.setBoundingBox(0xeeeeee, 0x888888);
cAxis.setRoundedCorners(10, 0, 10, 0);

// Set surface grid lines to semi-transparent black (cc000000)
c.setSurfaceAxisGrid(0xcc000000);

// Set contour lines to semi-transparent white (80ffffff)
c.setContourColor(0x80ffffff);

// Set the walls to black in color
c.setWallColor(0x000000);

// Set the xyz major wall grid lines to white (ffffff), and minor wall grid lines to
// grey (888888)
c.setWallGrid(0xffffff, 0xffffff, 0xffffff, 0x888888, 0x888888, 0x888888);

// Set the wall thickness to 0
c.setWallThickness(0, 0, 0);

// Show only the xy wall, and hide the yz and zx walls.
c.setWallVisibility(true, false, false);

// Set the x, y and z axis titles using 12 points Arial Bold font
c.xAxis().setTitle("X Title\nPlaceholder", "Arial Bold", 12);
c.yAxis().setTitle("Y Title\nPlaceholder", "Arial Bold", 12);

// Output the chart
String chart1URL = c.makeSession(request, "chart1", Chart.JPG);
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Scattered Data Surface Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'>
</body>
</html>

[Java Version] javademo/scattersurface.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class scattersurface implements DemoModule
{
    //Name of demo program
    public String toString() { return "Scattered Data Surface Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The (x, y, z) coordinates of the scattered data
        double[] dataX = {0.5, 1.9, 4.9, 1.0, 8.9, 9.8, 5.9, 2.9, 6.8, 9.0, 0.0, 8.9,
            1.9, 4.8, 2.4, 3.4, 7.9, 7.5, 4.8, 7.5, 9.5, 0.4, 8.9, 0.9, 5.4, 9.4,
            2.9, 8.9, 0.9, 8.9, 10.0, 1.0, 6.8, 3.8, 9.0, 5.3, 6.4, 4.9, 4.5, 2.0,
            5.4, 0.0, 10.0, 3.9, 5.4, 5.9, 5.8, 0.3, 4.4, 8.3};
        double[] dataY = {3.3, 3.0, 0.7, 1.0, 9.3, 4.5, 8.4, 0.1, 0.8, 0.1, 9.3, 1.8,
            4.3, 1.3, 2.3, 5.4, 6.9, 9.0, 9.8, 7.5, 1.8, 1.4, 4.5, 7.8, 3.8, 4.0,
            2.9, 2.4, 3.9, 2.9, 2.3, 9.3, 2.0, 3.4, 4.8, 2.3, 3.4, 2.3, 1.5, 7.8,
            4.5, 0.9, 6.3, 2.4, 6.9, 2.8, 1.3, 2.9, 6.4, 6.3};
        double[] dataZ = {6.6, 12.5, 7.4, 6.2, 9.6, 13.6, 19.9, 2.2, 6.9, 3.4, 8.7,
            8.4, 7.8, 8.0, 9.4, 11.9, 9.6, 15.7, 12.0, 13.3, 9.6, 6.4, 9.0, 6.9, 4.6,
            9.7, 10.6, 9.2, 7.0, 6.9, 9.7, 8.6, 8.0, 13.6, 13.2, 5.9, 9.0, 3.2, 8.3,
            9.7, 8.2, 6.1, 8.7, 5.6, 14.9, 9.8, 9.3, 5.1, 10.8, 9.8};

        // Create a SurfaceChart object of size 680 x 550 pixels. Set background to
        // brushed silver and border to grey (888888). Set the top-left and
        // bottom-right corners to rounded corners with 20 pixels radius.
        SurfaceChart c = new SurfaceChart(680, 550, Chart.brushedSilverColor(),
            0x888888);
        c.setRoundedFrame(0xffffff, 20, 0, 20, 0);

        // Add a title to the chart using 20 points Times New Roman Italic font. Set
        // top/bottom margin to 8 pixels.
        TextBox title = c.addTitle("Surface Created Using Scattered Data Points",
            "Times New Roman Italic", 20);
        title.setMargin2(0, 0, 8, 8);

        // Add a 2 pixel wide black (000000) separator line under the title
        c.addLine(10, title.getHeight(), c.getWidth() - 10, title.getHeight(),
            0x000000, 2);

        // Set the center of the plot region at (290, 235), and set width x depth x
        // height to 360 x 360 x 180 pixels
        c.setPlotRegion(290, 235, 360, 360, 180);

        // Set the elevation and rotation angles to 45 and -45 degrees
        c.setViewAngle(45, -45);

        // Set the perspective level to 30
        c.setPerspective(30);

        // Set the data to use to plot the chart
        c.setData(dataX, dataY, dataZ);

        // Add a color axis (the legend) in which the top right corner is anchored at
        // (660, 80). Set the length to 200 pixels and the labels on the right side.
        ColorAxis cAxis = c.setColorAxis(660, 80, Chart.TopRight, 200, Chart.Right);

        // Set the color axis title with 12 points Arial Bold font
        cAxis.setTitle("Z Title Placeholder", "Arial Bold", 12);

        // Add a bounding box with light grey (eeeeee) background and grey (888888)
        // border. Set the top-left and bottom-right corners to rounded corners of
        // 10 pixels radius.
        cAxis.setBoundingBox(0xeeeeee, 0x888888);
        cAxis.setRoundedCorners(10, 0, 10, 0);

        // Set surface grid lines to semi-transparent black (cc000000)
        c.setSurfaceAxisGrid(0xcc000000);

        // Set contour lines to semi-transparent white (80ffffff)
        c.setContourColor(0x80ffffff);

        // Set the walls to black in color
        c.setWallColor(0x000000);

        // Set the xyz major wall grid lines to white (ffffff), and minor wall grid
        // lines to grey (888888)
        c.setWallGrid(0xffffff, 0xffffff, 0xffffff, 0x888888, 0x888888, 0x888888);

        // Set the wall thickness to 0
        c.setWallThickness(0, 0, 0);

        // Show only the xy wall, and hide the yz and zx walls.
        c.setWallVisibility(true, false, false);

        // Set the x, y and z axis titles using 12 points Arial Bold font
        c.xAxis().setTitle("X Title\nPlaceholder", "Arial Bold", 12);
        c.yAxis().setTitle("Y Title\nPlaceholder", "Arial Bold", 12);

        // Output the chart
        viewer.setChart(c);
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new scattersurface();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


Surface Chart Axis Types

Surface Chart Axis Types

The example demonstrates different axis scale types for the surface charts.

Like an XYChart, in a SurfaceChart, the axis scale can represent numbers, date/time or labels. In this example, the x-axis uses a date/time scale, the y-axis uses a label based scale, and the z-axis uses a numeric scale.

Source Code Listing

[JSP Version] jspdemo/surfaceaxis.jsp
<%@page import="ChartDirector.*" %>
<%@page import="java.util.*" %>
<%
// The x and y coordinates of the grid
Date[] dataX = {new GregorianCalendar(2008, 8, 1).getTime(), new GregorianCalendar(
    2008, 8, 2).getTime(), new GregorianCalendar(2008, 8, 3).getTime(),
    new GregorianCalendar(2008, 8, 4).getTime(), new GregorianCalendar(2008, 8, 5
    ).getTime(), new GregorianCalendar(2008, 8, 6).getTime()};
String[] dataY = {"Low", "Medium", "High"};

// The data series
double[] lowData = {24, 38, 33, 25, 28, 36};
double[] mediumData = {49, 42, 34, 47, 53, 50};
double[] highData = {44, 51, 38, 33, 47, 42};

// Create a SurfaceChart object of size 760 x 500 pixels
SurfaceChart c = new SurfaceChart(760, 500);

// Add a title to the chart using 18 points Arial font
c.addTitle("Surface Chart Axis Types", "Arial", 18);

// Set the center of the plot region at (385, 240), and set width x depth x height to
// 480 x 240 x 240 pixels
c.setPlotRegion(385, 240, 480, 240, 240);

// Set the elevation and rotation angles to 30 and -10 degrees
c.setViewAngle(30, -10);

// Set the data to use to plot the chart. As the y-data are text strings
// (enumerated), we will use an empty array for the y-coordinates. For the z data
// series, they are just the concatenation of the individual data series.
c.setData(Chart.CTime(dataX), null, new ArrayMath(lowData).insert(mediumData).insert(
    highData).result());

// Set the y-axis labels
c.yAxis().setLabels(dataY);

// Set x-axis tick density to 75 pixels. ChartDirector auto-scaling will use this as
// the guideline when putting ticks on the x-axis.
c.xAxis().setTickDensity(75);

// Spline interpolate data to a 80 x 40 grid for a smooth surface
c.setInterpolation(80, 40);

// Set surface grid lines to semi-transparent black (cc000000).
c.setSurfaceAxisGrid(0xcc000000);

// Set contour lines to the same color as the fill color at the contour level
c.setContourColor(Chart.SameAsMainColor);

// Add a color axis (the legend) in which the top right corner is anchored at (95,
// 100). Set the length to 160 pixels and the labels on the left side.
ColorAxis cAxis = c.setColorAxis(95, 100, Chart.TopRight, 160, Chart.Left);

// Add a bounding box with light grey (eeeeee) background and grey (888888) border.
cAxis.setBoundingBox(0xeeeeee, 0x888888);

// Set label style to Arial bold for all axes
c.xAxis().setLabelStyle("Arial Bold");
c.yAxis().setLabelStyle("Arial Bold");
c.zAxis().setLabelStyle("Arial Bold");
c.colorAxis().setLabelStyle("Arial Bold");

// Set the x, y and z axis titles using deep blue (000088) 15 points Arial font
c.xAxis().setTitle("Date/Time Axis", "Arial Italic", 15, 0x000088);
c.yAxis().setTitle("Label\nBased\nAxis", "Arial Italic", 15, 0x000088);
c.zAxis().setTitle("Numeric Axis", "Arial Italic", 15, 0x000088);

// Output the chart
String chart1URL = c.makeSession(request, "chart1", Chart.JPG);
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Surface Chart Axis Types
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'>
</body>
</html>

[Java Version] javademo/surfaceaxis.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import ChartDirector.*;

public class surfaceaxis implements DemoModule
{
    //Name of demo program
    public String toString() { return "Surface Chart Axis Types"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The x and y coordinates of the grid
        Date[] dataX = {new GregorianCalendar(2008, 8, 1).getTime(),
            new GregorianCalendar(2008, 8, 2).getTime(), new GregorianCalendar(2008,
            8, 3).getTime(), new GregorianCalendar(2008, 8, 4).getTime(),
            new GregorianCalendar(2008, 8, 5).getTime(), new GregorianCalendar(2008,
            8, 6).getTime()};
        String[] dataY = {"Low", "Medium", "High"};

        // The data series
        double[] lowData = {24, 38, 33, 25, 28, 36};
        double[] mediumData = {49, 42, 34, 47, 53, 50};
        double[] highData = {44, 51, 38, 33, 47, 42};

        // Create a SurfaceChart object of size 760 x 500 pixels
        SurfaceChart c = new SurfaceChart(760, 500);

        // Add a title to the chart using 18 points Arial font
        c.addTitle("Surface Chart Axis Types", "Arial", 18);

        // Set the center of the plot region at (385, 240), and set width x depth x
        // height to 480 x 240 x 240 pixels
        c.setPlotRegion(385, 240, 480, 240, 240);

        // Set the elevation and rotation angles to 30 and -10 degrees
        c.setViewAngle(30, -10);

        // Set the data to use to plot the chart. As the y-data are text strings
        // (enumerated), we will use an empty array for the y-coordinates. For the z
        // data series, they are just the concatenation of the individual data
        // series.
        c.setData(Chart.CTime(dataX), null, new ArrayMath(lowData).insert(mediumData
            ).insert(highData).result());

        // Set the y-axis labels
        c.yAxis().setLabels(dataY);

        // Set x-axis tick density to 75 pixels. ChartDirector auto-scaling will use
        // this as the guideline when putting ticks on the x-axis.
        c.xAxis().setTickDensity(75);

        // Spline interpolate data to a 80 x 40 grid for a smooth surface
        c.setInterpolation(80, 40);

        // Set surface grid lines to semi-transparent black (cc000000).
        c.setSurfaceAxisGrid(0xcc000000);

        // Set contour lines to the same color as the fill color at the contour level
        c.setContourColor(Chart.SameAsMainColor);

        // Add a color axis (the legend) in which the top right corner is anchored at
        // (95, 100). Set the length to 160 pixels and the labels on the left side.
        ColorAxis cAxis = c.setColorAxis(95, 100, Chart.TopRight, 160, Chart.Left);

        // Add a bounding box with light grey (eeeeee) background and grey (888888)
        // border.
        cAxis.setBoundingBox(0xeeeeee, 0x888888);

        // Set label style to Arial bold for all axes
        c.xAxis().setLabelStyle("Arial Bold");
        c.yAxis().setLabelStyle("Arial Bold");
        c.zAxis().setLabelStyle("Arial Bold");
        c.colorAxis().setLabelStyle("Arial Bold");

        // Set the x, y and z axis titles using deep blue (000088) 15 points Arial
        // font
        c.xAxis().setTitle("Date/Time Axis", "Arial Italic", 15, 0x000088);
        c.yAxis().setTitle("Label\nBased\nAxis", "Arial Italic", 15, 0x000088);
        c.zAxis().setTitle("Numeric Axis", "Arial Italic", 15, 0x000088);

        // Output the chart
        viewer.setChart(c);
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new surfaceaxis();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


Surface Lighting

Surface Lighting

This example demonstrates the effects of various surface lighting parameters, configured using SurfaceChart.setLighting.

Source Code Listing

[JSP Version] jspdemo/surfacelighting.jsp
<%@page import="ChartDirector.*" %>
<%@page import="javax.servlet.http.*" %>
<%!
// A simple structure to represent a chart image with an image map
private static class ImageWithHotSpot
{
    String imageURL;
    String imageMap;
}

// Function to create the demo charts
ImageWithHotSpot createChart(HttpServletRequest request, int index)
{
    // The x and y coordinates of the grid
    double[] dataX = {-10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10};
    double[] dataY = {-10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10};

    // The values at the grid points. In this example, we will compute the values
    // using the formula z = x * sin(y) + y * sin(x).
    double[] dataZ = new double[(dataX.length) * (dataY.length)];
    for (int yIndex = 0; yIndex < dataY.length; ++yIndex) {
        double y = dataY[yIndex];
        for (int xIndex = 0; xIndex < dataX.length; ++xIndex) {
            double x = dataX[xIndex];
            dataZ[yIndex * (dataX.length) + xIndex] = x * Math.sin(y) + y * Math.sin(
                x);
        }
    }

    // Create a SurfaceChart object of size 380 x 400 pixels, with white (ffffff)
    // background and grey (888888) border.
    SurfaceChart c = new SurfaceChart(380, 400, 0xffffff, 0x888888);

    // Demonstrate various lighting parameters
    if (index == 0) {
        c.addTitle(
            "Default Lighting<*br*><*size=10*>Ambient = 0.5, Diffuse = 0.5, " +
            "Specular = 1, Shininess = 8");
    } else if (index == 1) {
        c.addTitle(
            "Matte (Non-Glossy) Lighting<*br*><*size=10*>Ambient = 0.5, Diffuse = " +
            "0.5, Specular = 0, Shininess = 0");
        c.setLighting(0.5, 0.5, 0, 0);
    } else if (index == 2) {
        c.addTitle(
            "Flat Lighting<*br*><*size=10*>Ambient = 1, Diffuse = 0, Specular = " +
            "0, Shininess = 0");
        c.setLighting(1, 0, 0, 0);
    } else {
        c.addTitle(
            "Strong Glossy Lighting<*br*><*size=10*>Ambient = 0.5, Diffuse = 0.5, " +
            "Specular = 4, Shininess = 32");
        c.setLighting(0.5, 0.5, 4, 32);
    }

    // Set the center of the plot region at (175, 200), and set width x depth x
    // height to 200 x 200 x 160 pixels
    c.setPlotRegion(175, 200, 200, 200, 160);

    // Set the plot region wall thichness to 5 pixels
    c.setWallThickness(5);

    // Set the elevation and rotation angles to 45 and 60 degrees
    c.setViewAngle(45, 60);

    // Set the perspective level to 35
    c.setPerspective(35);

    // Set the data to use to plot the chart
    c.setData(dataX, dataY, dataZ);

    // Spline interpolate data to a 50 x 50 grid for a smooth surface
    c.setInterpolation(50, 50);

    // Set contour lines to semi-transparent black (c0000000)
    c.setContourColor(0xc0000000);

    // Output the chart
    ImageWithHotSpot ret = new ImageWithHotSpot();
    ret.imageURL = c.makeSession(request, "chart" + index, Chart.JPG);
    return ret;
}
%>
<%
ImageWithHotSpot chart0 = createChart(request, 0);
ImageWithHotSpot chart1 = createChart(request, 1);
ImageWithHotSpot chart2 = createChart(request, 2);
ImageWithHotSpot chart3 = createChart(request, 3);
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Surface Lighting
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart0.imageURL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1.imageURL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart2.imageURL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart3.imageURL)%>'>
</body>
</html>

[Java Version] javademo/surfacelighting.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class surfacelighting implements DemoModule
{
    //Name of demo program
    public String toString() { return "Surface Lighting"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 4; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The x and y coordinates of the grid
        double[] dataX = {-10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10};
        double[] dataY = {-10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10};

        // The values at the grid points. In this example, we will compute the values
        // using the formula z = x * sin(y) + y * sin(x).
        double[] dataZ = new double[(dataX.length) * (dataY.length)];
        for (int yIndex = 0; yIndex < dataY.length; ++yIndex) {
            double y = dataY[yIndex];
            for (int xIndex = 0; xIndex < dataX.length; ++xIndex) {
                double x = dataX[xIndex];
                dataZ[yIndex * (dataX.length) + xIndex] = x * Math.sin(y) + y *
                    Math.sin(x);
            }
        }

        // Create a SurfaceChart object of size 380 x 400 pixels, with white (ffffff)
        // background and grey (888888) border.
        SurfaceChart c = new SurfaceChart(380, 400, 0xffffff, 0x888888);

        // Demonstrate various lighting parameters
        if (index == 0) {
            c.addTitle(
                "Default Lighting<*br*><*size=10*>Ambient = 0.5, Diffuse = 0.5, " +
                "Specular = 1, Shininess = 8");
        } else if (index == 1) {
            c.addTitle(
                "Matte (Non-Glossy) Lighting<*br*><*size=10*>Ambient = 0.5, " +
                "Diffuse = 0.5, Specular = 0, Shininess = 0");
            c.setLighting(0.5, 0.5, 0, 0);
        } else if (index == 2) {
            c.addTitle(
                "Flat Lighting<*br*><*size=10*>Ambient = 1, Diffuse = 0, Specular " +
                "= 0, Shininess = 0");
            c.setLighting(1, 0, 0, 0);
        } else {
            c.addTitle(
                "Strong Glossy Lighting<*br*><*size=10*>Ambient = 0.5, Diffuse = " +
                "0.5, Specular = 4, Shininess = 32");
            c.setLighting(0.5, 0.5, 4, 32);
        }

        // Set the center of the plot region at (175, 200), and set width x depth x
        // height to 200 x 200 x 160 pixels
        c.setPlotRegion(175, 200, 200, 200, 160);

        // Set the plot region wall thichness to 5 pixels
        c.setWallThickness(5);

        // Set the elevation and rotation angles to 45 and 60 degrees
        c.setViewAngle(45, 60);

        // Set the perspective level to 35
        c.setPerspective(35);

        // Set the data to use to plot the chart
        c.setData(dataX, dataY, dataZ);

        // Spline interpolate data to a 50 x 50 grid for a smooth surface
        c.setInterpolation(50, 50);

        // Set contour lines to semi-transparent black (c0000000)
        c.setContourColor(0xc0000000);

        // Output the chart
        viewer.setChart(c);
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new surfacelighting();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);
        frame.getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
        frame.setSize(800, 450);

        // Create the charts and put them in the content pane
        for (int i = 0; i < demo.getNoOfCharts(); ++i)
        {
            ChartViewer viewer = new ChartViewer();
            demo.createChart(viewer, i);
            frame.getContentPane().add(viewer);
        }

        // Display the window
        frame.setVisible(true);
    }
}


Surface Shading

Surface Shading

This example demonstrates the effects of various surface shading methods, configured using SurfaceChart.setShadingMode.

Source Code Listing

[JSP Version] jspdemo/surfaceshading.jsp
<%@page import="ChartDirector.*" %>
<%@page import="javax.servlet.http.*" %>
<%!
// A simple structure to represent a chart image with an image map
private static class ImageWithHotSpot
{
    String imageURL;
    String imageMap;
}

// Function to create the demo charts
ImageWithHotSpot createChart(HttpServletRequest request, int index)
{
    // The x and y coordinates of the grid
    double[] dataX = {-10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10};
    double[] dataY = {-10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10};

    // The values at the grid points. In this example, we will compute the values
    // using the formula z = x * sin(y) + y * sin(x).
    double[] dataZ = new double[(dataX.length) * (dataY.length)];
    for (int yIndex = 0; yIndex < dataY.length; ++yIndex) {
        double y = dataY[yIndex];
        for (int xIndex = 0; xIndex < dataX.length; ++xIndex) {
            double x = dataX[xIndex];
            dataZ[yIndex * (dataX.length) + xIndex] = x * Math.sin(y) + y * Math.sin(
                x);
        }
    }

    // Create a SurfaceChart object of size 380 x 400 pixels, with white (ffffff)
    // background and grey (888888) border.
    SurfaceChart c = new SurfaceChart(380, 400, 0xffffff, 0x888888);

    // Demonstrate various shading methods
    if (index == 0) {
        c.addTitle("11 x 11 Data Points\nSmooth Shading");
    } else if (index == 1) {
        c.addTitle("11 x 11 Points - Spline Fitted to 50 x 50\nSmooth Shading");
        c.setInterpolation(50, 50);
    } else if (index == 2) {
        c.addTitle("11 x 11 Data Points\nRectangular Shading");
        c.setShadingMode(Chart.RectangularShading);
    } else {
        c.addTitle("11 x 11 Data Points\nTriangular Shading");
        c.setShadingMode(Chart.TriangularShading);
    }

    // Set the center of the plot region at (175, 200), and set width x depth x
    // height to 200 x 200 x 160 pixels
    c.setPlotRegion(175, 200, 200, 200, 160);

    // Set the plot region wall thichness to 5 pixels
    c.setWallThickness(5);

    // Set the elevation and rotation angles to 45 and 60 degrees
    c.setViewAngle(45, 60);

    // Set the perspective level to 35
    c.setPerspective(35);

    // Set the data to use to plot the chart
    c.setData(dataX, dataY, dataZ);

    // Set contour lines to semi-transparent black (c0000000)
    c.setContourColor(0xc0000000);

    // Output the chart
    ImageWithHotSpot ret = new ImageWithHotSpot();
    ret.imageURL = c.makeSession(request, "chart" + index, Chart.JPG);
    return ret;
}
%>
<%
ImageWithHotSpot chart0 = createChart(request, 0);
ImageWithHotSpot chart1 = createChart(request, 1);
ImageWithHotSpot chart2 = createChart(request, 2);
ImageWithHotSpot chart3 = createChart(request, 3);
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Surface Shading
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart0.imageURL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1.imageURL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart2.imageURL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart3.imageURL)%>'>
</body>
</html>

[Java Version] javademo/surfaceshading.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class surfaceshading implements DemoModule
{
    //Name of demo program
    public String toString() { return "Surface Shading"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 4; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The x and y coordinates of the grid
        double[] dataX = {-10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10};
        double[] dataY = {-10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10};

        // The values at the grid points. In this example, we will compute the values
        // using the formula z = x * sin(y) + y * sin(x).
        double[] dataZ = new double[(dataX.length) * (dataY.length)];
        for (int yIndex = 0; yIndex < dataY.length; ++yIndex) {
            double y = dataY[yIndex];
            for (int xIndex = 0; xIndex < dataX.length; ++xIndex) {
                double x = dataX[xIndex];
                dataZ[yIndex * (dataX.length) + xIndex] = x * Math.sin(y) + y *
                    Math.sin(x);
            }
        }

        // Create a SurfaceChart object of size 380 x 400 pixels, with white (ffffff)
        // background and grey (888888) border.
        SurfaceChart c = new SurfaceChart(380, 400, 0xffffff, 0x888888);

        // Demonstrate various shading methods
        if (index == 0) {
            c.addTitle("11 x 11 Data Points\nSmooth Shading");
        } else if (index == 1) {
            c.addTitle("11 x 11 Points - Spline Fitted to 50 x 50\nSmooth Shading");
            c.setInterpolation(50, 50);
        } else if (index == 2) {
            c.addTitle("11 x 11 Data Points\nRectangular Shading");
            c.setShadingMode(Chart.RectangularShading);
        } else {
            c.addTitle("11 x 11 Data Points\nTriangular Shading");
            c.setShadingMode(Chart.TriangularShading);
        }

        // Set the center of the plot region at (175, 200), and set width x depth x
        // height to 200 x 200 x 160 pixels
        c.setPlotRegion(175, 200, 200, 200, 160);

        // Set the plot region wall thichness to 5 pixels
        c.setWallThickness(5);

        // Set the elevation and rotation angles to 45 and 60 degrees
        c.setViewAngle(45, 60);

        // Set the perspective level to 35
        c.setPerspective(35);

        // Set the data to use to plot the chart
        c.setData(dataX, dataY, dataZ);

        // Set contour lines to semi-transparent black (c0000000)
        c.setContourColor(0xc0000000);

        // Output the chart
        viewer.setChart(c);
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new surfaceshading();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);
        frame.getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
        frame.setSize(800, 450);

        // Create the charts and put them in the content pane
        for (int i = 0; i < demo.getNoOfCharts(); ++i)
        {
            ChartViewer viewer = new ChartViewer();
            demo.createChart(viewer, i);
            frame.getContentPane().add(viewer);
        }

        // Display the window
        frame.setVisible(true);
    }
}


Surface Wireframe

Surface Wireframe

This example demonstrates the rectangular and triangular wireframes of a surface at different interpolation levels, configured using SurfaceChart.setShadingMode and SurfaceChart.setInterpolation.

Source Code Listing

[JSP Version] jspdemo/surfacewireframe.jsp
<%@page import="ChartDirector.*" %>
<%@page import="javax.servlet.http.*" %>
<%!
// A simple structure to represent a chart image with an image map
private static class ImageWithHotSpot
{
    String imageURL;
    String imageMap;
}

// Function to create the demo charts
ImageWithHotSpot createChart(HttpServletRequest request, int index)
{
    // The x and y coordinates of the grid
    double[] dataX = {-2, -1, 0, 1, 2};
    double[] dataY = {-2, -1, 0, 1, 2};

    // The values at the grid points. In this example, we will compute the values
    // using the formula z = square_root(15 - x * x - y * y).
    double[] dataZ = new double[(dataX.length) * (dataY.length)];
    for (int yIndex = 0; yIndex < dataY.length; ++yIndex) {
        double y = dataY[yIndex];
        for (int xIndex = 0; xIndex < dataX.length; ++xIndex) {
            double x = dataX[xIndex];
            dataZ[yIndex * (dataX.length) + xIndex] = Math.sqrt(15 - x * x - y * y);
        }
    }

    // Create a SurfaceChart object of size 380 x 340 pixels, with white (ffffff)
    // background and grey (888888) border.
    SurfaceChart c = new SurfaceChart(380, 340, 0xffffff, 0x888888);

    // Demonstrate various wireframes with and without interpolation
    if (index == 0) {
        // Original data without interpolation
        c.addTitle("5 x 5 Data Points\nStandard Shading", "Arial Bold", 12);
        c.setContourColor(0x80ffffff);
    } else if (index == 1) {
        // Original data, spline interpolated to 40 x 40 for smoothness
        c.addTitle("5 x 5 Points - Spline Fitted to 40 x 40\nStandard Shading",
            "Arial Bold", 12);
        c.setContourColor(0x80ffffff);
        c.setInterpolation(40, 40);
    } else if (index == 2) {
        // Rectangular wireframe of original data
        c.addTitle("5 x 5 Data Points\nRectangular Wireframe");
        c.setShadingMode(Chart.RectangularFrame);
    } else if (index == 3) {
        // Rectangular wireframe of original data spline interpolated to 40 x 40
        c.addTitle("5 x 5 Points - Spline Fitted to 40 x 40\nRectangular Wireframe");
        c.setShadingMode(Chart.RectangularFrame);
        c.setInterpolation(40, 40);
    } else if (index == 4) {
        // Triangular wireframe of original data
        c.addTitle("5 x 5 Data Points\nTriangular Wireframe");
        c.setShadingMode(Chart.TriangularFrame);
    } else {
        // Triangular wireframe of original data spline interpolated to 40 x 40
        c.addTitle("5 x 5 Points - Spline Fitted to 40 x 40\nTriangular Wireframe");
        c.setShadingMode(Chart.TriangularFrame);
        c.setInterpolation(40, 40);
    }

    // Set the center of the plot region at (200, 170), and set width x depth x
    // height to 200 x 200 x 150 pixels
    c.setPlotRegion(200, 170, 200, 200, 150);

    // Set the plot region wall thichness to 5 pixels
    c.setWallThickness(5);

    // Set the elevation and rotation angles to 20 and 30 degrees
    c.setViewAngle(20, 30);

    // Set the data to use to plot the chart
    c.setData(dataX, dataY, dataZ);

    // Output the chart
    ImageWithHotSpot ret = new ImageWithHotSpot();
    ret.imageURL = c.makeSession(request, "chart" + index, Chart.JPG);
    return ret;
}
%>
<%
ImageWithHotSpot chart0 = createChart(request, 0);
ImageWithHotSpot chart1 = createChart(request, 1);
ImageWithHotSpot chart2 = createChart(request, 2);
ImageWithHotSpot chart3 = createChart(request, 3);
ImageWithHotSpot chart4 = createChart(request, 4);
ImageWithHotSpot chart5 = createChart(request, 5);
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Surface Wireframe
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart0.imageURL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1.imageURL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart2.imageURL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart3.imageURL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart4.imageURL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart5.imageURL)%>'>
</body>
</html>

[Java Version] javademo/surfacewireframe.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class surfacewireframe implements DemoModule
{
    //Name of demo program
    public String toString() { return "Surface Wireframe"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 6; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The x and y coordinates of the grid
        double[] dataX = {-2, -1, 0, 1, 2};
        double[] dataY = {-2, -1, 0, 1, 2};

        // The values at the grid points. In this example, we will compute the values
        // using the formula z = square_root(15 - x * x - y * y).
        double[] dataZ = new double[(dataX.length) * (dataY.length)];
        for (int yIndex = 0; yIndex < dataY.length; ++yIndex) {
            double y = dataY[yIndex];
            for (int xIndex = 0; xIndex < dataX.length; ++xIndex) {
                double x = dataX[xIndex];
                dataZ[yIndex * (dataX.length) + xIndex] = Math.sqrt(15 - x * x - y *
                    y);
            }
        }

        // Create a SurfaceChart object of size 380 x 340 pixels, with white (ffffff)
        // background and grey (888888) border.
        SurfaceChart c = new SurfaceChart(380, 340, 0xffffff, 0x888888);

        // Demonstrate various wireframes with and without interpolation
        if (index == 0) {
            // Original data without interpolation
            c.addTitle("5 x 5 Data Points\nStandard Shading", "Arial Bold", 12);
            c.setContourColor(0x80ffffff);
        } else if (index == 1) {
            // Original data, spline interpolated to 40 x 40 for smoothness
            c.addTitle("5 x 5 Points - Spline Fitted to 40 x 40\nStandard Shading",
                "Arial Bold", 12);
            c.setContourColor(0x80ffffff);
            c.setInterpolation(40, 40);
        } else if (index == 2) {
            // Rectangular wireframe of original data
            c.addTitle("5 x 5 Data Points\nRectangular Wireframe");
            c.setShadingMode(Chart.RectangularFrame);
        } else if (index == 3) {
            // Rectangular wireframe of original data spline interpolated to 40 x 40
            c.addTitle(
                "5 x 5 Points - Spline Fitted to 40 x 40\nRectangular Wireframe");
            c.setShadingMode(Chart.RectangularFrame);
            c.setInterpolation(40, 40);
        } else if (index == 4) {
            // Triangular wireframe of original data
            c.addTitle("5 x 5 Data Points\nTriangular Wireframe");
            c.setShadingMode(Chart.TriangularFrame);
        } else {
            // Triangular wireframe of original data spline interpolated to 40 x 40
            c.addTitle(
                "5 x 5 Points - Spline Fitted to 40 x 40\nTriangular Wireframe");
            c.setShadingMode(Chart.TriangularFrame);
            c.setInterpolation(40, 40);
        }

        // Set the center of the plot region at (200, 170), and set width x depth x
        // height to 200 x 200 x 150 pixels
        c.setPlotRegion(200, 170, 200, 200, 150);

        // Set the plot region wall thichness to 5 pixels
        c.setWallThickness(5);

        // Set the elevation and rotation angles to 20 and 30 degrees
        c.setViewAngle(20, 30);

        // Set the data to use to plot the chart
        c.setData(dataX, dataY, dataZ);

        // Output the chart
        viewer.setChart(c);
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new surfacewireframe();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);
        frame.getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
        frame.setSize(800, 450);

        // Create the charts and put them in the content pane
        for (int i = 0; i < demo.getNoOfCharts(); ++i)
        {
            ChartViewer viewer = new ChartViewer();
            demo.createChart(viewer, i);
            frame.getContentPane().add(viewer);
        }

        // Display the window
        frame.setVisible(true);
    }
}


Surface Perspective

Surface Perspective

This example demonstrates the effects of various perspective depth, configured using ThreeDChart.setPerspective.

Source Code Listing

[JSP Version] jspdemo/surfaceperspective.jsp
<%@page import="ChartDirector.*" %>
<%@page import="javax.servlet.http.*" %>
<%!
// A simple structure to represent a chart image with an image map
private static class ImageWithHotSpot
{
    String imageURL;
    String imageMap;
}

// Function to create the demo charts
ImageWithHotSpot createChart(HttpServletRequest request, int index)
{
    // The x and y coordinates of the grid
    double[] dataX = {0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0};
    double[] dataY = {0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0};

    // The values at the grid points. In this example, we will compute the values
    // using the formula z = sin((x - 0.5) * 2 * pi) * sin((y - 0.5) * 2 * pi)
    double[] dataZ = new double[(dataX.length) * (dataY.length)];
    for (int yIndex = 0; yIndex < dataY.length; ++yIndex) {
        double y = (dataY[yIndex] - 0.5) * 2 * 3.1416;
        for (int xIndex = 0; xIndex < dataX.length; ++xIndex) {
            double x = (dataX[xIndex] - 0.5) * 2 * 3.1416;
            dataZ[yIndex * (dataX.length) + xIndex] = Math.sin(x) * Math.sin(y);
        }
    }

    // the perspective level
    int perspective = index * 12;

    // Create a SurfaceChart object of size 360 x 360 pixels, with white (ffffff)
    // background and grey (888888) border.
    SurfaceChart c = new SurfaceChart(360, 360, 0xffffff, 0x888888);

    // Set the perspective level
    c.setPerspective(perspective);
    c.addTitle("Perspective = " + perspective);

    // Set the center of the plot region at (195, 165), and set width x depth x
    // height to 200 x 200 x 150 pixels
    c.setPlotRegion(195, 165, 200, 200, 150);

    // Set the plot region wall thichness to 5 pixels
    c.setWallThickness(5);

    // Set the elevation and rotation angles to 30 and 30 degrees
    c.setViewAngle(30, 30);

    // Set the data to use to plot the chart
    c.setData(dataX, dataY, dataZ);

    // Spline interpolate data to a 40 x 40 grid for a smooth surface
    c.setInterpolation(40, 40);

    // Use smooth gradient coloring.
    c.colorAxis().setColorGradient();

    // Output the chart
    ImageWithHotSpot ret = new ImageWithHotSpot();
    ret.imageURL = c.makeSession(request, "chart" + index, Chart.JPG);
    return ret;
}
%>
<%
ImageWithHotSpot chart0 = createChart(request, 0);
ImageWithHotSpot chart1 = createChart(request, 1);
ImageWithHotSpot chart2 = createChart(request, 2);
ImageWithHotSpot chart3 = createChart(request, 3);
ImageWithHotSpot chart4 = createChart(request, 4);
ImageWithHotSpot chart5 = createChart(request, 5);
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Surface Perspective
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart0.imageURL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1.imageURL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart2.imageURL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart3.imageURL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart4.imageURL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart5.imageURL)%>'>
</body>
</html>

[Java Version] javademo/surfaceperspective.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class surfaceperspective implements DemoModule
{
    //Name of demo program
    public String toString() { return "Surface Perspective"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 6; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The x and y coordinates of the grid
        double[] dataX = {0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0};
        double[] dataY = {0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0};

        // The values at the grid points. In this example, we will compute the values
        // using the formula z = sin((x - 0.5) * 2 * pi) * sin((y - 0.5) * 2 * pi)
        double[] dataZ = new double[(dataX.length) * (dataY.length)];
        for (int yIndex = 0; yIndex < dataY.length; ++yIndex) {
            double y = (dataY[yIndex] - 0.5) * 2 * 3.1416;
            for (int xIndex = 0; xIndex < dataX.length; ++xIndex) {
                double x = (dataX[xIndex] - 0.5) * 2 * 3.1416;
                dataZ[yIndex * (dataX.length) + xIndex] = Math.sin(x) * Math.sin(y);
            }
        }

        // the perspective level
        int perspective = index * 12;

        // Create a SurfaceChart object of size 360 x 360 pixels, with white (ffffff)
        // background and grey (888888) border.
        SurfaceChart c = new SurfaceChart(360, 360, 0xffffff, 0x888888);

        // Set the perspective level
        c.setPerspective(perspective);
        c.addTitle("Perspective = " + perspective);

        // Set the center of the plot region at (195, 165), and set width x depth x
        // height to 200 x 200 x 150 pixels
        c.setPlotRegion(195, 165, 200, 200, 150);

        // Set the plot region wall thichness to 5 pixels
        c.setWallThickness(5);

        // Set the elevation and rotation angles to 30 and 30 degrees
        c.setViewAngle(30, 30);

        // Set the data to use to plot the chart
        c.setData(dataX, dataY, dataZ);

        // Spline interpolate data to a 40 x 40 grid for a smooth surface
        c.setInterpolation(40, 40);

        // Use smooth gradient coloring.
        c.colorAxis().setColorGradient();

        // Output the chart
        viewer.setChart(c);
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new surfaceperspective();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);
        frame.getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
        frame.setSize(800, 450);

        // Create the charts and put them in the content pane
        for (int i = 0; i < demo.getNoOfCharts(); ++i)
        {
            ChartViewer viewer = new ChartViewer();
            demo.createChart(viewer, i);
            frame.getContentPane().add(viewer);
        }

        // Display the window
        frame.setVisible(true);
    }
}


3D Scatter Charts

3D Scatter Charts

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

Title | Description
3D Scatter Chart (1) | Demonstrates the basic steps in creating 3D scatter charts.
3D Scatter Chart (2) | Extends the 3D Scatter Chart (1) example by including drop lines, using alternative view angles and continuous coloring.
3D Scatter Groups | Demonstrates multiple symbol groups by calling ThreeDScatterChart.addScatterGroup multiple times with different data and colors.
3D Scatter Axis Types | Demonstrates different axis scale types for the 3D scatter charts. Also demonstrates using different symbol shapes.


3D Scatter Chart (1)

3D Scatter Chart (1)

This example demonstrates the basic steps in creating 3D scatter charts.

  • Create a ThreeDScatterChart object using ThreeDScatterChart.ThreeDScatterChart.

  • Specify the position and size of the plot region using ThreeDChart.setPlotRegion.

  • Add a scatter group to the chart using ThreeDScatterChart.addScatterGroup. In this example, the symbol color is set to SameAsMainColor, which means the color depends on the z-coordinate as according to the color axis (color legend). The color axis can be accessed using ThreeDChart.colorAxis.

  • Set the position of the color axis (the color legend) using ThreeDChart.setColorAxis.

  • Add chart and axis titles using BaseChart.addTitle and Axis.setTitle.

  • Generate the chart using BaseChart.makeSession (JSP version) or BaseChart.makeImage (Java version).

Source Code Listing

[JSP Version] jspdemo/threedscatter.jsp
<%@page import="ChartDirector.*" %>
<%
// The XYZ data for the 3D scatter chart as 3 random data series
RanSeries r = new RanSeries(0);
double[] xData = r.getSeries2(100, 100, -10, 10);
double[] yData = r.getSeries2(100, 0, 0, 20);
double[] zData = r.getSeries2(100, 100, -10, 10);

// Create a ThreeDScatterChart object of size 720 x 600 pixels
ThreeDScatterChart c = new ThreeDScatterChart(720, 600);

// Add a title to the chart using 20 points Times New Roman Italic font
c.addTitle("3D Scatter Chart (1)  ", "Times New Roman Italic", 20);

// Set the center of the plot region at (350, 280), and set width x depth x height to
// 360 x 360 x 270 pixels
c.setPlotRegion(350, 280, 360, 360, 270);

// Add a scatter group to the chart using 11 pixels glass sphere symbols, in which
// the color depends on the z value of the symbol
c.addScatterGroup(xData, yData, zData, "", Chart.GlassSphere2Shape, 11,
    Chart.SameAsMainColor);

// Add a color axis (the legend) in which the left center is anchored at (645, 270).
// Set the length to 200 pixels and the labels on the right side.
c.setColorAxis(645, 270, Chart.Left, 200, Chart.Right);

// Set the x, y and z axis titles using 10 points Arial Bold font
c.xAxis().setTitle("X-Axis Place Holder", "Arial Bold", 10);
c.yAxis().setTitle("Y-Axis Place Holder", "Arial Bold", 10);
c.zAxis().setTitle("Z-Axis Place Holder", "Arial Bold", 10);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "", "title='(x={x|p}, y={y|p}, z={z|p}'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    3D Scatter Chart (1)
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/threedscatter.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class threedscatter implements DemoModule
{
    //Name of demo program
    public String toString() { return "3D Scatter Chart (1)"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The XYZ data for the 3D scatter chart as 3 random data series
        RanSeries r = new RanSeries(0);
        double[] xData = r.getSeries2(100, 100, -10, 10);
        double[] yData = r.getSeries2(100, 0, 0, 20);
        double[] zData = r.getSeries2(100, 100, -10, 10);

        // Create a ThreeDScatterChart object of size 720 x 600 pixels
        ThreeDScatterChart c = new ThreeDScatterChart(720, 600);

        // Add a title to the chart using 20 points Times New Roman Italic font
        c.addTitle("3D Scatter Chart (1)  ", "Times New Roman Italic", 20);

        // Set the center of the plot region at (350, 280), and set width x depth x
        // height to 360 x 360 x 270 pixels
        c.setPlotRegion(350, 280, 360, 360, 270);

        // Add a scatter group to the chart using 11 pixels glass sphere symbols, in
        // which the color depends on the z value of the symbol
        c.addScatterGroup(xData, yData, zData, "", Chart.GlassSphere2Shape, 11,
            Chart.SameAsMainColor);

        // Add a color axis (the legend) in which the left center is anchored at
        // (645, 270). Set the length to 200 pixels and the labels on the right side.
        c.setColorAxis(645, 270, Chart.Left, 200, Chart.Right);

        // Set the x, y and z axis titles using 10 points Arial Bold font
        c.xAxis().setTitle("X-Axis Place Holder", "Arial Bold", 10);
        c.yAxis().setTitle("Y-Axis Place Holder", "Arial Bold", 10);
        c.zAxis().setTitle("Z-Axis Place Holder", "Arial Bold", 10);

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='(x={x|p}, y={y|p}, z={z|p}'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new threedscatter();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


3D Scatter Chart (2)

3D Scatter Chart (2)

This example extends the 3D Scatter Chart (1) example by including drop lines, using alternative view angles and continuous coloring.

Drop lines are lines that drop from the data points to the XY plane. They help to visualize the "height" (the z-coordinate) of the points and can be useful if there are not too many data points.

  • The alternative view angles are set using ThreeDChart.setViewAngle.

  • The drop lines are added using ThreeDScatterGroup.setDropLine.

  • Continuous coloring are configured using ColorAxis.setColorGradient.

Source Code Listing

[JSP Version] jspdemo/threedscatter2.jsp
<%@page import="ChartDirector.*" %>
<%
// The XYZ data for the 3D scatter chart as 3 random data series
RanSeries r = new RanSeries(3);
double[] xData = r.getSeries2(20, 100, -10, 10);
double[] yData = r.getSeries2(20, 100, -10, 10);
double[] zData = r.getSeries2(20, 100, -10, 10);

// Create a ThreeDScatterChart object of size 720 x 520 pixels
ThreeDScatterChart c = new ThreeDScatterChart(720, 520);

// Add a title to the chart using 20 points Times New Roman Italic font
c.addTitle("3D Scatter Chart (2)  ", "Times New Roman Italic", 20);

// Set the center of the plot region at (350, 240), and set width x depth x height to
// 360 x 360 x 270 pixels
c.setPlotRegion(350, 240, 360, 360, 270);

// Set the elevation and rotation angles to 15 and 30 degrees
c.setViewAngle(15, 30);

// Add a scatter group to the chart using 13 pixels glass sphere symbols, in which
// the color depends on the z value of the symbol
ThreeDScatterGroup g = c.addScatterGroup(xData, yData, zData, "",
    Chart.GlassSphere2Shape, 13, Chart.SameAsMainColor);

// Add grey (888888) drop lines to the symbols
g.setDropLine(0x888888);

// Add a color axis (the legend) in which the left center is anchored at (645, 220).
// Set the length to 200 pixels and the labels on the right side. Use smooth gradient
// coloring.
c.setColorAxis(645, 220, Chart.Left, 200, Chart.Right).setColorGradient();

// Set the x, y and z axis titles using 10 points Arial Bold font
c.xAxis().setTitle("X-Axis Place Holder", "Arial Bold", 10);
c.yAxis().setTitle("Y-Axis Place Holder", "Arial Bold", 10);
c.zAxis().setTitle("Z-Axis Place Holder", "Arial Bold", 10);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "", "title='(x={x|p}, y={y|p}, z={z|p}'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    3D Scatter Chart (2)
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/threedscatter2.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class threedscatter2 implements DemoModule
{
    //Name of demo program
    public String toString() { return "3D Scatter Chart (2)"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The XYZ data for the 3D scatter chart as 3 random data series
        RanSeries r = new RanSeries(3);
        double[] xData = r.getSeries2(20, 100, -10, 10);
        double[] yData = r.getSeries2(20, 100, -10, 10);
        double[] zData = r.getSeries2(20, 100, -10, 10);

        // Create a ThreeDScatterChart object of size 720 x 520 pixels
        ThreeDScatterChart c = new ThreeDScatterChart(720, 520);

        // Add a title to the chart using 20 points Times New Roman Italic font
        c.addTitle("3D Scatter Chart (2)  ", "Times New Roman Italic", 20);

        // Set the center of the plot region at (350, 240), and set width x depth x
        // height to 360 x 360 x 270 pixels
        c.setPlotRegion(350, 240, 360, 360, 270);

        // Set the elevation and rotation angles to 15 and 30 degrees
        c.setViewAngle(15, 30);

        // Add a scatter group to the chart using 13 pixels glass sphere symbols, in
        // which the color depends on the z value of the symbol
        ThreeDScatterGroup g = c.addScatterGroup(xData, yData, zData, "",
            Chart.GlassSphere2Shape, 13, Chart.SameAsMainColor);

        // Add grey (888888) drop lines to the symbols
        g.setDropLine(0x888888);

        // Add a color axis (the legend) in which the left center is anchored at
        // (645, 220). Set the length to 200 pixels and the labels on the right side.
        // Use smooth gradient coloring.
        c.setColorAxis(645, 220, Chart.Left, 200, Chart.Right).setColorGradient();

        // Set the x, y and z axis titles using 10 points Arial Bold font
        c.xAxis().setTitle("X-Axis Place Holder", "Arial Bold", 10);
        c.yAxis().setTitle("Y-Axis Place Holder", "Arial Bold", 10);
        c.zAxis().setTitle("Z-Axis Place Holder", "Arial Bold", 10);

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='(x={x|p}, y={y|p}, z={z|p}'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new threedscatter2();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


3D Scatter Groups

3D Scatter Groups

This example demonstrates multiple symbol groups by calling ThreeDScatterChart.addScatterGroup multiple times with different data and colors.

Source Code Listing

[JSP Version] jspdemo/threedscattergroups.jsp
<%@page import="ChartDirector.*" %>
<%
// The random XYZ data for the first 3D scatter group
RanSeries r0 = new RanSeries(7);
double[] xData0 = r0.getSeries2(100, 100, -10, 10);
double[] yData0 = r0.getSeries2(100, 0, 0, 20);
double[] zData0 = r0.getSeries2(100, 100, -10, 10);

// The random XYZ data for the second 3D scatter group
RanSeries r1 = new RanSeries(4);
double[] xData1 = r1.getSeries2(100, 100, -10, 10);
double[] yData1 = r1.getSeries2(100, 0, 0, 20);
double[] zData1 = r1.getSeries2(100, 100, -10, 10);

// The random XYZ data for the third 3D scatter group
RanSeries r2 = new RanSeries(8);
double[] xData2 = r2.getSeries2(100, 100, -10, 10);
double[] yData2 = r2.getSeries2(100, 0, 0, 20);
double[] zData2 = r2.getSeries2(100, 100, -10, 10);

// Create a ThreeDScatterChart object of size 800 x 520 pixels
ThreeDScatterChart c = new ThreeDScatterChart(800, 520);

// Add a title to the chart using 20 points Times New Roman Italic font
c.addTitle("3D Scatter Groups                    ", "Times New Roman Italic", 20);

// Set the center of the plot region at (350, 240), and set width x depth x height to
// 360 x 360 x 270 pixels
c.setPlotRegion(350, 240, 360, 360, 270);

// Set the elevation and rotation angles to 15 and 30 degrees
c.setViewAngle(15, 30);

// Add a legend box at (640, 180)
c.addLegend(640, 180);

// Add 3 scatter groups to the chart with 9 pixels glass sphere symbols of red
// (ff0000), green (00ff00) and blue (0000ff) colors
c.addScatterGroup(xData0, yData0, zData0, "Alpha", Chart.GlassSphere2Shape, 9,
    0xff0000);
c.addScatterGroup(xData1, yData1, zData1, "Beta", Chart.GlassSphere2Shape, 9,
    0x00ff00);
c.addScatterGroup(xData2, yData2, zData2, "Gamma", Chart.GlassSphere2Shape, 9,
    0x0000ff);

// Set the x, y and z axis titles
c.xAxis().setTitle("X-Axis Place Holder");
c.yAxis().setTitle("Y-Axis Place Holder");
c.zAxis().setTitle("Z-Axis Place Holder");

// Output the chart
String chart1URL = c.makeSession(request, "chart1");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    3D Scatter Groups
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'>
</body>
</html>

[Java Version] javademo/threedscattergroups.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class threedscattergroups implements DemoModule
{
    //Name of demo program
    public String toString() { return "3D Scatter Groups"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The random XYZ data for the first 3D scatter group
        RanSeries r0 = new RanSeries(7);
        double[] xData0 = r0.getSeries2(100, 100, -10, 10);
        double[] yData0 = r0.getSeries2(100, 0, 0, 20);
        double[] zData0 = r0.getSeries2(100, 100, -10, 10);

        // The random XYZ data for the second 3D scatter group
        RanSeries r1 = new RanSeries(4);
        double[] xData1 = r1.getSeries2(100, 100, -10, 10);
        double[] yData1 = r1.getSeries2(100, 0, 0, 20);
        double[] zData1 = r1.getSeries2(100, 100, -10, 10);

        // The random XYZ data for the third 3D scatter group
        RanSeries r2 = new RanSeries(8);
        double[] xData2 = r2.getSeries2(100, 100, -10, 10);
        double[] yData2 = r2.getSeries2(100, 0, 0, 20);
        double[] zData2 = r2.getSeries2(100, 100, -10, 10);

        // Create a ThreeDScatterChart object of size 800 x 520 pixels
        ThreeDScatterChart c = new ThreeDScatterChart(800, 520);

        // Add a title to the chart using 20 points Times New Roman Italic font
        c.addTitle("3D Scatter Groups                    ", "Times New Roman Italic",
            20);

        // Set the center of the plot region at (350, 240), and set width x depth x
        // height to 360 x 360 x 270 pixels
        c.setPlotRegion(350, 240, 360, 360, 270);

        // Set the elevation and rotation angles to 15 and 30 degrees
        c.setViewAngle(15, 30);

        // Add a legend box at (640, 180)
        c.addLegend(640, 180);

        // Add 3 scatter groups to the chart with 9 pixels glass sphere symbols of
        // red (ff0000), green (00ff00) and blue (0000ff) colors
        c.addScatterGroup(xData0, yData0, zData0, "Alpha", Chart.GlassSphere2Shape,
            9, 0xff0000);
        c.addScatterGroup(xData1, yData1, zData1, "Beta", Chart.GlassSphere2Shape, 9,
            0x00ff00);
        c.addScatterGroup(xData2, yData2, zData2, "Gamma", Chart.GlassSphere2Shape,
            9, 0x0000ff);

        // Set the x, y and z axis titles
        c.xAxis().setTitle("X-Axis Place Holder");
        c.yAxis().setTitle("Y-Axis Place Holder");
        c.zAxis().setTitle("Z-Axis Place Holder");

        // Output the chart
        viewer.setChart(c);
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new threedscattergroups();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


3D Scatter Axis Types

3D Scatter Axis Types

This example demonstrates different axis scale types for the 3D scatter charts. It also demonstrates using different symbol shapes.

Like an XYChart, in a ThreeDScatterChart, the axis scale can represent numbers, date/time or labels. In this example, the x-axis uses a date/time scale, the y-axis uses a label based scale, and the z-axis uses a numeric scale.

Source Code Listing

[JSP Version] jspdemo/threedscatteraxis.jsp
<%@page import="ChartDirector.*" %>
<%@page import="java.util.*" %>
<%

// The x coordinates for the 2 scatter groups
Date[] dataX = {new GregorianCalendar(2011, 8, 1).getTime(), new GregorianCalendar(
    2011, 8, 2).getTime(), new GregorianCalendar(2011, 8, 3).getTime(),
    new GregorianCalendar(2011, 8, 4).getTime(), new GregorianCalendar(2011, 8, 5
    ).getTime(), new GregorianCalendar(2011, 8, 6).getTime(), new GregorianCalendar(
    2011, 8, 7).getTime(), new GregorianCalendar(2011, 8, 8).getTime(),
    new GregorianCalendar(2011, 8, 9).getTime(), new GregorianCalendar(2011, 8, 10
    ).getTime(), new GregorianCalendar(2011, 8, 11).getTime()};

// The y and z coordinates for the first scatter group
double[] dataY0 = {0.4, 0.2, 0.5, 0.4, 0.7, 1.3, 1.1, 1.0, 0.6, 0.4, 0.5};
double[] dataZ0 = {43, 38, 33, 23.4, 28, 36, 34, 47, 53, 45, 40};

// The y and z coordinates for the second scatter group
double[] dataY1 = {1.4, 1.0, 1.8, 1.9, 1.5, 1.0, 0.6, 0.7, 1.2, 1.7, 1.5};
double[] dataZ1 = {46, 41, 33, 37, 28, 29, 34, 37, 41, 52, 50};

// Instead of displaying numeric values, labels are used for the y-axis
String[] labelsY = {"Low", "Medium", "High"};

// Create a ThreeDScatterChart object of size 760 x 520 pixels
ThreeDScatterChart c = new ThreeDScatterChart(760, 520);

// Add a title to the chart using 18 points Arial font
c.addTitle("3D Scatter Chart Axis Types", "Arial", 18);

// Set the center of the plot region at (385, 270), and set width x depth x height to
// 480 x 240 x 240 pixels
c.setPlotRegion(385, 270, 480, 240, 240);

// Set the elevation and rotation angles to 30 and -10 degrees
c.setViewAngle(30, -10);

// Add a legend box at (380, 40) with horizontal layout. Use 9 pts Arial Bold font.
LegendBox b = c.addLegend(380, 40, false, "Arial Bold", 9);
b.setAlignment(Chart.TopCenter);
b.setRoundedCorners();

// Add a scatter group to the chart using 13 pixels red (ff0000) glass sphere
// symbols, with dotted drop lines
ThreeDScatterGroup g0 = c.addScatterGroup(Chart.CTime(dataX), dataY0, dataZ0,
    "Alpha Series", Chart.GlassSphere2Shape, 13, 0xff0000);
g0.setDropLine(c.dashLineColor(Chart.SameAsMainColor, Chart.DotLine));

// Add a scatter group to the chart using 13 pixels blue (00cc00) cross symbols, with
// dotted drop lines
ThreeDScatterGroup g1 = c.addScatterGroup(Chart.CTime(dataX), dataY1, dataZ1,
    "Beta Series", Chart.Cross2Shape(), 13, 0x00cc00);
g1.setDropLine(c.dashLineColor(Chart.SameAsMainColor, Chart.DotLine));

// Set x-axis tick density to 50 pixels. ChartDirector auto-scaling will use this as
// the guideline when putting ticks on the x-axis.
c.xAxis().setTickDensity(50);

// Set the y-axis labels
c.yAxis().setLabels(labelsY);

// Set label style to Arial bold for all axes
c.xAxis().setLabelStyle("Arial Bold");
c.yAxis().setLabelStyle("Arial Bold");
c.zAxis().setLabelStyle("Arial Bold");

// Set the x, y and z axis titles using deep blue (000088) 15 points Arial font
c.xAxis().setTitle("Date/Time Axis", "Arial Italic", 15, 0x000088);
c.yAxis().setTitle("Label\nBased\nAxis", "Arial Italic", 15, 0x000088);
c.zAxis().setTitle("Numeric Axis", "Arial Italic", 15, 0x000088);

// Output the chart
String chart1URL = c.makeSession(request, "chart1");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    3D Scatter Axis Types
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'>
</body>
</html>

[Java Version] javademo/threedscatteraxis.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import ChartDirector.*;

public class threedscatteraxis implements DemoModule
{
    //Name of demo program
    public String toString() { return "3D Scatter Axis Types"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {

        // The x coordinates for the 2 scatter groups
        Date[] dataX = {new GregorianCalendar(2011, 8, 1).getTime(),
            new GregorianCalendar(2011, 8, 2).getTime(), new GregorianCalendar(2011,
            8, 3).getTime(), new GregorianCalendar(2011, 8, 4).getTime(),
            new GregorianCalendar(2011, 8, 5).getTime(), new GregorianCalendar(2011,
            8, 6).getTime(), new GregorianCalendar(2011, 8, 7).getTime(),
            new GregorianCalendar(2011, 8, 8).getTime(), new GregorianCalendar(2011,
            8, 9).getTime(), new GregorianCalendar(2011, 8, 10).getTime(),
            new GregorianCalendar(2011, 8, 11).getTime()};

        // The y and z coordinates for the first scatter group
        double[] dataY0 = {0.4, 0.2, 0.5, 0.4, 0.7, 1.3, 1.1, 1.0, 0.6, 0.4, 0.5};
        double[] dataZ0 = {43, 38, 33, 23.4, 28, 36, 34, 47, 53, 45, 40};

        // The y and z coordinates for the second scatter group
        double[] dataY1 = {1.4, 1.0, 1.8, 1.9, 1.5, 1.0, 0.6, 0.7, 1.2, 1.7, 1.5};
        double[] dataZ1 = {46, 41, 33, 37, 28, 29, 34, 37, 41, 52, 50};

        // Instead of displaying numeric values, labels are used for the y-axis
        String[] labelsY = {"Low", "Medium", "High"};

        // Create a ThreeDScatterChart object of size 760 x 520 pixels
        ThreeDScatterChart c = new ThreeDScatterChart(760, 520);

        // Add a title to the chart using 18 points Arial font
        c.addTitle("3D Scatter Chart Axis Types", "Arial", 18);

        // Set the center of the plot region at (385, 270), and set width x depth x
        // height to 480 x 240 x 240 pixels
        c.setPlotRegion(385, 270, 480, 240, 240);

        // Set the elevation and rotation angles to 30 and -10 degrees
        c.setViewAngle(30, -10);

        // Add a legend box at (380, 40) with horizontal layout. Use 9 pts Arial Bold
        // font.
        LegendBox b = c.addLegend(380, 40, false, "Arial Bold", 9);
        b.setAlignment(Chart.TopCenter);
        b.setRoundedCorners();

        // Add a scatter group to the chart using 13 pixels red (ff0000) glass sphere
        // symbols, with dotted drop lines
        ThreeDScatterGroup g0 = c.addScatterGroup(Chart.CTime(dataX), dataY0, dataZ0,
            "Alpha Series", Chart.GlassSphere2Shape, 13, 0xff0000);
        g0.setDropLine(c.dashLineColor(Chart.SameAsMainColor, Chart.DotLine));

        // Add a scatter group to the chart using 13 pixels blue (00cc00) cross
        // symbols, with dotted drop lines
        ThreeDScatterGroup g1 = c.addScatterGroup(Chart.CTime(dataX), dataY1, dataZ1,
            "Beta Series", Chart.Cross2Shape(), 13, 0x00cc00);
        g1.setDropLine(c.dashLineColor(Chart.SameAsMainColor, Chart.DotLine));

        // Set x-axis tick density to 50 pixels. ChartDirector auto-scaling will use
        // this as the guideline when putting ticks on the x-axis.
        c.xAxis().setTickDensity(50);

        // Set the y-axis labels
        c.yAxis().setLabels(labelsY);

        // Set label style to Arial bold for all axes
        c.xAxis().setLabelStyle("Arial Bold");
        c.yAxis().setLabelStyle("Arial Bold");
        c.zAxis().setLabelStyle("Arial Bold");

        // Set the x, y and z axis titles using deep blue (000088) 15 points Arial
        // font
        c.xAxis().setTitle("Date/Time Axis", "Arial Italic", 15, 0x000088);
        c.yAxis().setTitle("Label\nBased\nAxis", "Arial Italic", 15, 0x000088);
        c.zAxis().setTitle("Numeric Axis", "Arial Italic", 15, 0x000088);

        // Output the chart
        viewer.setChart(c);
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new threedscatteraxis();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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 (JSP version) or BaseChart.makeImage (Java version).

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

Source Code Listing

[JSP Version] jspdemo/simpleradar.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the chart
double[] data = {90, 60, 65, 75, 40};

// The labels for the chart
String[] labels = {"Speed", "Reliability", "Comfort", "Safety", "Efficiency"};

// Create a PolarChart object of size 450 x 350 pixels
PolarChart c = new 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
String chart1URL = c.makeSession(request, "chart1");

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "", "title='{label}: score = {value}'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Simple Radar Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/simpleradar.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class simpleradar implements DemoModule
{
    //Name of demo program
    public String toString() { return "Simple Radar Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the chart
        double[] data = {90, 60, 65, 75, 40};

        // The labels for the chart
        String[] labels = {"Speed", "Reliability", "Comfort", "Safety", "Efficiency"}
            ;

        // Create a PolarChart object of size 450 x 350 pixels
        PolarChart c = new 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
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='{label}: score = {value}'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new simpleradar();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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 Chart.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 Chart.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 (JSP version) or BaseChart.makeImage (Java version).

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

Source Code Listing

[JSP Version] jspdemo/multiradar.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the chart
double[] data0 = {90, 60, 85, 75, 55};
double[] data1 = {60, 80, 70, 80, 85};

// The labels for the chart
String[] labels = {"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
PolarChart c = new PolarChart(480, 380, Chart.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.
LegendBox b = c.addLegend(470, 35, true, "Arial Bold", 10);
b.setAlignment(Chart.TopRight);
b.setBackground(Chart.silverColor(), Chart.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
String chart1URL = c.makeSession(request, "chart1");

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='[{dataSetName}] {label}: score = {value}'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Multi Radar Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/multiradar.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class multiradar implements DemoModule
{
    //Name of demo program
    public String toString() { return "Multi Radar Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the chart
        double[] data0 = {90, 60, 85, 75, 55};
        double[] data1 = {60, 80, 70, 80, 85};

        // The labels for the chart
        String[] labels = {"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
        PolarChart c = new PolarChart(480, 380, Chart.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.
        LegendBox b = c.addLegend(470, 35, true, "Arial Bold", 10);
        b.setAlignment(Chart.TopRight);
        b.setBackground(Chart.silverColor(), Chart.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
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='[{dataSetName}] {label}: score = {value}'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new multiradar();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/stackradar.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the chart
double[] data0 = {100, 100, 100, 100, 100};
double[] data1 = {90, 85, 85, 80, 70};
double[] data2 = {80, 65, 65, 75, 45};

// The labels for the chart
String[] labels = {"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
PolarChart c = new PolarChart(480, 460, Chart.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.
LegendBox b = c.addLegend(240, 35, false, "Arial Bold", 10);
b.setAlignment(Chart.TopCenter);
b.setBackground(Chart.silverColor(), Chart.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, Chart.Transparent);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='Current {label}: {value}% in {dataSetName}'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Stacked Radar Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/stackradar.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class stackradar implements DemoModule
{
    //Name of demo program
    public String toString() { return "Stacked Radar Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the chart
        double[] data0 = {100, 100, 100, 100, 100};
        double[] data1 = {90, 85, 85, 80, 70};
        double[] data2 = {80, 65, 65, 75, 45};

        // The labels for the chart
        String[] labels = {"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
        PolarChart c = new PolarChart(480, 460, Chart.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.
        LegendBox b = c.addLegend(240, 35, false, "Arial Bold", 10);
        b.setAlignment(Chart.TopCenter);
        b.setBackground(Chart.silverColor(), Chart.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, Chart.Transparent);

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='Current {label}: {value}% in {dataSetName}'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new stackradar();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/polarline.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the chart
double[] data0 = {90, 25, 40, 55, 68, 44, 79, 85, 50};
double[] angles0 = {15, 60, 110, 180, 230, 260, 260, 310, 340};

double[] data1 = {80, 91, 66, 80, 92, 87};
double[] angles1 = {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
PolarChart c = new PolarChart(460, 500, 0xe0e0e0, 0x000000, 1);

//Set search path to current JSP directory for loading icon images
c.setSearchPath(getServletConfig().getServletContext(), request);

// 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.
LegendBox b = c.addLegend(230, 35, false, "Arial Bold", 9);
b.setAlignment(Chart.TopCenter);
b.setBackground(Chart.Transparent, Chart.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)
PolarLineLayer 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(Chart.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, Chart.Transparent, 1);

// Add a red (0xff0000) line layer to the chart using (data1, angle1)
PolarLineLayer 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(Chart.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, Chart.Transparent, 1);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='[{dataSetName}] ({radius}, {angle})'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Polar Line Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/polarline.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class polarline implements DemoModule
{
    //Name of demo program
    public String toString() { return "Polar Line Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the chart
        double[] data0 = {90, 25, 40, 55, 68, 44, 79, 85, 50};
        double[] angles0 = {15, 60, 110, 180, 230, 260, 260, 310, 340};

        double[] data1 = {80, 91, 66, 80, 92, 87};
        double[] angles1 = {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
        PolarChart c = new PolarChart(460, 500, 0xe0e0e0, 0x000000, 1);

        // 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.
        LegendBox b = c.addLegend(230, 35, false, "Arial Bold", 9);
        b.setAlignment(Chart.TopCenter);
        b.setBackground(Chart.Transparent, Chart.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)
        PolarLineLayer 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(Chart.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, Chart.Transparent, 1);

        // Add a red (0xff0000) line layer to the chart using (data1, angle1)
        PolarLineLayer 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(Chart.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, Chart.Transparent, 1);

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='[{dataSetName}] ({radius}, {angle})'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new polarline();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/polararea.jsp
<%@page import="ChartDirector.*" %>
<%
// Data for the chart
double[] data0 = {5, 3, 10, 4, 3, 5, 2, 5};
double[] data1 = {12, 6, 17, 6, 7, 9, 4, 7};
double[] data2 = {17, 7, 22, 7, 18, 13, 5, 11};

String[] labels = {"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
PolarChart c = new PolarChart(460, 500, 0xe0e0e0, 0x000000, 1);

//Set search path to current JSP directory for loading icon images
c.setSearchPath(getServletConfig().getServletContext(), request);

// 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.
LegendBox b = c.addLegend(230, 35, false, "Arial Bold", 9);
b.setAlignment(Chart.TopCenter);
b.setBackground(Chart.Transparent, Chart.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
String chart1URL = c.makeSession(request, "chart1");

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='[{label}] {dataSetName}: {value}%'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Polar Area Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/polararea.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class polararea implements DemoModule
{
    //Name of demo program
    public String toString() { return "Polar Area Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // Data for the chart
        double[] data0 = {5, 3, 10, 4, 3, 5, 2, 5};
        double[] data1 = {12, 6, 17, 6, 7, 9, 4, 7};
        double[] data2 = {17, 7, 22, 7, 18, 13, 5, 11};

        String[] labels = {"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
        PolarChart c = new PolarChart(460, 500, 0xe0e0e0, 0x000000, 1);

        // 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.
        LegendBox b = c.addLegend(230, 35, false, "Arial Bold", 9);
        b.setAlignment(Chart.TopCenter);
        b.setBackground(Chart.Transparent, Chart.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
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='[{label}] {dataSetName}: {value}%'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new polararea();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/polarspline.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the chart
double[] data0 = {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};
double[] angles0 = {0, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180, 195,
    210, 225, 240, 255, 270, 285, 300, 315, 330, 345};

double[] data1 = {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};
double[] angles1 = {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
PolarChart c = new PolarChart(460, 460);

// Add a title to the chart at the top left corner using 15pts Arial Bold Italic font
c.addTitle2(Chart.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(Chart.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)
PolarSplineLineLayer layer1 = c.addSplineLineLayer(data1, 0x0000ff, "Below 100MHz");
layer1.setAngles(angles1);

// Set the line width to 3 pixels
layer1.setLineWidth(3);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName} EM field at {angle} deg: {value} Watt'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Polar Spline Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/polarspline.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class polarspline implements DemoModule
{
    //Name of demo program
    public String toString() { return "Polar Spline Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the chart
        double[] data0 = {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};
        double[] angles0 = {0, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180,
            195, 210, 225, 240, 255, 270, 285, 300, 315, 330, 345};

        double[] data1 = {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};
        double[] angles1 = {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
        PolarChart c = new PolarChart(460, 460);

        // Add a title to the chart at the top left corner using 15pts Arial Bold
        // Italic font
        c.addTitle2(Chart.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(Chart.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)
        PolarSplineLineLayer layer1 = c.addSplineLineLayer(data1, 0x0000ff,
            "Below 100MHz");
        layer1.setAngles(angles1);

        // Set the line width to 3 pixels
        layer1.setLineWidth(3);

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='{dataSetName} EM field at {angle} deg: {value} Watt'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new polarspline();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/polarscatter.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the chart
double[] data0 = {43, 89, 76, 64, 48, 18, 92, 68, 44, 79, 71, 85};
double[] angles0 = {45, 96, 169, 258, 15, 30, 330, 260, 60, 75, 110, 140};

double[] data1 = {50, 91, 26, 29, 80, 53, 62, 87, 19, 40};
double[] angles1 = {230, 210, 240, 310, 179, 250, 244, 199, 89, 160};

double[] data2 = {88, 65, 76, 49, 80, 53};
double[] angles2 = {340, 310, 340, 210, 30, 300};

// The labels on the angular axis (spokes)
String[] labels = {"North", "North\nEast", "East", "South\nEast", "South",
    "South\nWest", "West", "North\nWest"};

// Create a PolarChart object of size 460 x 460 pixels
PolarChart c = new PolarChart(460, 460);

// Add a title to the chart at the top left corner using 15pts Arial Bold Italic font
c.addTitle2(Chart.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(Chart.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)
PolarLineLayer layer0 = c.addLineLayer(data0, 0x0000ff, "Immortal Weed");
layer0.setAngles(angles0);

layer0.setLineWidth(0);
layer0.setDataSymbol(Chart.TriangleSymbol, 11);

// Add a red (0xff0000) polar line layer to the chart using (data1, angles1)
PolarLineLayer 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(Chart.DiamondSymbol, 11);

// Add a green (0x00ff00) polar line layer to the chart using (data2, angles2)
PolarLineLayer 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(Chart.SquareSymbol, 9);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName} at ({value} km, {angle} deg)'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Polar Scatter Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/polarscatter.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class polarscatter implements DemoModule
{
    //Name of demo program
    public String toString() { return "Polar Scatter Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the chart
        double[] data0 = {43, 89, 76, 64, 48, 18, 92, 68, 44, 79, 71, 85};
        double[] angles0 = {45, 96, 169, 258, 15, 30, 330, 260, 60, 75, 110, 140};

        double[] data1 = {50, 91, 26, 29, 80, 53, 62, 87, 19, 40};
        double[] angles1 = {230, 210, 240, 310, 179, 250, 244, 199, 89, 160};

        double[] data2 = {88, 65, 76, 49, 80, 53};
        double[] angles2 = {340, 310, 340, 210, 30, 300};

        // The labels on the angular axis (spokes)
        String[] labels = {"North", "North\nEast", "East", "South\nEast", "South",
            "South\nWest", "West", "North\nWest"};

        // Create a PolarChart object of size 460 x 460 pixels
        PolarChart c = new PolarChart(460, 460);

        // Add a title to the chart at the top left corner using 15pts Arial Bold
        // Italic font
        c.addTitle2(Chart.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(Chart.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)
        PolarLineLayer layer0 = c.addLineLayer(data0, 0x0000ff, "Immortal Weed");
        layer0.setAngles(angles0);

        layer0.setLineWidth(0);
        layer0.setDataSymbol(Chart.TriangleSymbol, 11);

        // Add a red (0xff0000) polar line layer to the chart using (data1, angles1)
        PolarLineLayer 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(Chart.DiamondSymbol, 11);

        // Add a green (0x00ff00) polar line layer to the chart using (data2,
        // angles2)
        PolarLineLayer 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(Chart.SquareSymbol, 9);

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='{dataSetName} at ({value} km, {angle} deg)'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new polarscatter();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/polarbubble.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the chart
double[] data0 = {6, 12.5, 18.2, 15};
double[] angles0 = {45, 96, 169, 258};
double[] size0 = {41, 105, 12, 20};

double[] data1 = {18, 16, 11, 14};
double[] angles1 = {30, 210, 240, 310};
double[] size1 = {30, 45, 12, 90};

// Create a PolarChart object of size 460 x 460 pixels
PolarChart c = new PolarChart(460, 460);

// Add a title to the chart at the top left corner using 15pts Arial Bold Italic font
c.addTitle2(Chart.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(Chart.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)
PolarLineLayer 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(Chart.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)
PolarLineLayer 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(Chart.CircleSymbol, 11);

// Modulate the symbol size by size1 to produce a bubble chart effect
layer1.setSymbolScale(size1);

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName} at ({value} km, {angle} deg)\nStrength = {z} Watt'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Polar Bubble Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/polarbubble.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class polarbubble implements DemoModule
{
    //Name of demo program
    public String toString() { return "Polar Bubble Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the chart
        double[] data0 = {6, 12.5, 18.2, 15};
        double[] angles0 = {45, 96, 169, 258};
        double[] size0 = {41, 105, 12, 20};

        double[] data1 = {18, 16, 11, 14};
        double[] angles1 = {30, 210, 240, 310};
        double[] size1 = {30, 45, 12, 90};

        // Create a PolarChart object of size 460 x 460 pixels
        PolarChart c = new PolarChart(460, 460);

        // Add a title to the chart at the top left corner using 15pts Arial Bold
        // Italic font
        c.addTitle2(Chart.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(Chart.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)
        PolarLineLayer 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(Chart.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)
        PolarLineLayer 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(Chart.CircleSymbol, 11);

        // Modulate the symbol size by size1 to produce a bubble chart effect
        layer1.setSymbolScale(size1);

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='{dataSetName} at ({value} km, {angle} deg) Strength = {z} Watt'")
            );
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new polarbubble();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/polarvector.jsp
<%@page import="ChartDirector.*" %>
<%
// Coordinates of the starting points of the vectors
double[] radius = {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};
double[] angle = {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
double[] magnitude = {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};
double[] direction = {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
PolarChart c = new 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, Chart.RadialAxisScale, 0x0000ff
    );

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='Vector at ({value}, {angle} deg): Length = {len}, Angle = {dir} deg'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Polar Vector Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/polarvector.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class polarvector implements DemoModule
{
    //Name of demo program
    public String toString() { return "Polar Vector Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // Coordinates of the starting points of the vectors
        double[] radius = {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};
        double[] angle = {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
        double[] magnitude = {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};
        double[] direction = {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
        PolarChart c = new 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, Chart.RadialAxisScale,
            0x0000ff);

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='Vector at ({value}, {angle} deg): Length = {len}, Angle = " +
            "{dir} deg'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new polarvector();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/rose.jsp
<%@page import="ChartDirector.*" %>
<%
// Data for the chart
double[] data = {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};
double[] angles = {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
PolarChart c = new PolarChart(460, 460, Chart.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 (int i = 0; i < data.length; ++i) {
    c.angularAxis().addZone(angles[i], angles[i] + 15, 0, data[i], 0x33ff33, 0x008000
        );
}

// Add an Transparent invisible layer to ensure the axis is auto-scaled using the
// data
c.addLineLayer(data, Chart.Transparent);

// Output the chart
String chart1URL = c.makeSession(request, "chart1");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Simple Rose Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'>
</body>
</html>

[Java Version] javademo/rose.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class rose implements DemoModule
{
    //Name of demo program
    public String toString() { return "Simple Rose Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // Data for the chart
        double[] data = {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};
        double[] angles = {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
        PolarChart c = new PolarChart(460, 460, Chart.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 (int i = 0; i < data.length; ++i) {
            c.angularAxis().addZone(angles[i], angles[i] + 15, 0, data[i], 0x33ff33,
                0x008000);
        }

        // Add an Transparent invisible layer to ensure the axis is auto-scaled using
        // the data
        c.addLineLayer(data, Chart.Transparent);

        // Output the chart
        viewer.setChart(c);
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new rose();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/stackrose.jsp
<%@page import="ChartDirector.*" %>
<%
// Data for the chart
double[] data0 = {5, 3, 10, 4, 3, 5, 2, 5};
double[] data1 = {12, 6, 17, 6, 7, 9, 4, 7};
double[] data2 = {17, 7, 22, 7, 18, 13, 5, 11};

double[] angles = {0, 45, 90, 135, 180, 225, 270, 315};
String[] labels = {"North", "North\nEast", "East", "South\nEast", "South",
    "South\nWest", "West", "North\nWest"};

// Create a PolarChart object of size 460 x 500 pixels, with a grey (e0e0e0)
// background and a 1 pixel 3D border
PolarChart c = new 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 legendBox = c.addLegend(230, 35, false, "Arial Bold", 9);
legendBox.setAlignment(Chart.TopCenter);
legendBox.setBackground(Chart.Transparent, Chart.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 (int i = 0; i < angles.length; ++i) {
    c.angularAxis().addZone(angles[i] - 10, angles[i] + 10, 0, data0[i], 0x3333ff, 0)
        ;
    c.angularAxis().addZone(angles[i] - 10, angles[i] + 10, data0[i], data1[i],
        0x33ff33, 0);
    c.angularAxis().addZone(angles[i] - 10, angles[i] + 10, data1[i], data2[i],
        0xff3333, 0);
}

// Add an Transparent invisible layer to ensure the axis is auto-scaled using the
// data
c.addLineLayer(data2, Chart.Transparent);

// Output the chart
String chart1URL = c.makeSession(request, "chart1");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Stacked Rose Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'>
</body>
</html>

[Java Version] javademo/stackrose.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class stackrose implements DemoModule
{
    //Name of demo program
    public String toString() { return "Stacked Rose Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // Data for the chart
        double[] data0 = {5, 3, 10, 4, 3, 5, 2, 5};
        double[] data1 = {12, 6, 17, 6, 7, 9, 4, 7};
        double[] data2 = {17, 7, 22, 7, 18, 13, 5, 11};

        double[] angles = {0, 45, 90, 135, 180, 225, 270, 315};
        String[] labels = {"North", "North\nEast", "East", "South\nEast", "South",
            "South\nWest", "West", "North\nWest"};

        // Create a PolarChart object of size 460 x 500 pixels, with a grey (e0e0e0)
        // background and a 1 pixel 3D border
        PolarChart c = new 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 legendBox = c.addLegend(230, 35, false, "Arial Bold", 9);
        legendBox.setAlignment(Chart.TopCenter);
        legendBox.setBackground(Chart.Transparent, Chart.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 (int i = 0; i < angles.length; ++i) {
            c.angularAxis().addZone(angles[i] - 10, angles[i] + 10, 0, data0[i],
                0x3333ff, 0);
            c.angularAxis().addZone(angles[i] - 10, angles[i] + 10, data0[i], data1[i
                ], 0x33ff33, 0);
            c.angularAxis().addZone(angles[i] - 10, angles[i] + 10, data1[i], data2[i
                ], 0xff3333, 0);
        }

        // Add an Transparent invisible layer to ensure the axis is auto-scaled using
        // the data
        c.addLineLayer(data2, Chart.Transparent);

        // Output the chart
        viewer.setChart(c);
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new stackrose();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/polarzones.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the chart
double[] data = {51, 15, 51, 40, 17, 87, 94, 21, 35, 88, 50, 60};

// The labels for the chart
String[] labels = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept",
    "Oct", "Nov", "Dec"};

// Create a PolarChart object of size 400 x 420 pixels
PolarChart c = new 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(new int[]{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(new int[]{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 legendBox = c.addLegend(200, 30, false, "Arial Bold", 9);
legendBox.setAlignment(Chart.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
PolarSplineLineLayer layer = c.addSplineLineLayer(data, 0x000080);
layer.setLineWidth(3);
layer.setDataSymbol(Chart.CircleShape, 11, 0xffff00);

// Set the labels to the angular axis as spokes.
c.angularAxis().setLabels(labels);

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

// Include tool tip for the chart.
String imageMap1 = layer.getHTMLImageMap("", "",
    "title='Concentration on {label}: {value} ppm'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Circular Zones
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/polarzones.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class polarzones implements DemoModule
{
    //Name of demo program
    public String toString() { return "Circular Zones"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the chart
        double[] data = {51, 15, 51, 40, 17, 87, 94, 21, 35, 88, 50, 60};

        // The labels for the chart
        String[] labels = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
            "Sept", "Oct", "Nov", "Dec"};

        // Create a PolarChart object of size 400 x 420 pixels
        PolarChart c = new 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(new int[]{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(new int[]{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 legendBox = c.addLegend(200, 30, false, "Arial Bold", 9);
        legendBox.setAlignment(Chart.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
        PolarSplineLineLayer layer = c.addSplineLineLayer(data, 0x000080);
        layer.setLineWidth(3);
        layer.setDataSymbol(Chart.CircleShape, 11, 0xffff00);

        // Set the labels to the angular axis as spokes.
        c.angularAxis().setLabels(labels);

        // Output the chart
        viewer.setChart(c);

        // Include tool tip for the chart.
        viewer.setImageMap(layer.getHTMLImageMap("clickable", "",
            "title='Concentration on {label}: {value} ppm'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new polarzones();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/polarzones2.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the chart
double[] data = {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
String[] labels = {"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
PolarChart c = new PolarChart(400, 420, Chart.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 legendBox = c.addLegend(200, 30, false, "Arial Bold", 9);
legendBox.setAlignment(Chart.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
PolarLineLayer layer = c.addLineLayer(data, 0x000080);
layer.setLineWidth(3);
layer.setDataSymbol(Chart.Cross2Shape(), 15, 0xff00ff);

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

// Include tool tip for the chart.
String imageMap1 = layer.getHTMLImageMap("", "",
    "title='Concentration on {label}: {value} ppm'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Sector Zones
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/polarzones2.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class polarzones2 implements DemoModule
{
    //Name of demo program
    public String toString() { return "Sector Zones"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the chart
        double[] data = {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
        String[] labels = {"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
        PolarChart c = new PolarChart(400, 420, Chart.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 legendBox = c.addLegend(200, 30, false, "Arial Bold", 9);
        legendBox.setAlignment(Chart.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
        PolarLineLayer layer = c.addLineLayer(data, 0x000080);
        layer.setLineWidth(3);
        layer.setDataSymbol(Chart.Cross2Shape(), 15, 0xff00ff);

        // Output the chart
        viewer.setChart(c);

        // Include tool tip for the chart.
        viewer.setImageMap(layer.getHTMLImageMap("clickable", "",
            "title='Concentration on {label}: {value} ppm'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new polarzones2();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


Pyramids/Cones/Funnels

Pyramids/Cones/Funnels

In this section, we will discuss how to create pyramid/cone/funnel charts using ChartDirector through a number of examples.

Title | Description
Simple Pyramid Chart | Demonstrates the basic steps in creating pyramid charts.
3D Pyramid Chart | Extends the Simple Pyramid Chart example by viewing the pyramid in 3D, using custom colors, inserting gaps between pyramid layers, and adding labels to both the center and the right side of the pyramid layers.
Rotated Pyramid Chart | Demonstrates a semi-transparent pyramid viewed at elevation and rotation angles. Also demonstrates adding a legend box to the pyramid chart.
Cone Chart | Demonstrates using PyramidChart.setConeSize to specify using a cone instead of a pyramid to represent the data.
Funnel Chart | Demonstrates using PyramidChart.setFunnelSize to specify using a funnel instead of a pyramid to represent the data.
Pyramid Elevation | Demonstrates viewing the pyramid at different elevation angles, configured with PyramidChart.setViewAngle.
Pyramid Rotation | Demonstrates viewing the pyramid at different rotation angles, configured with PyramidChart.setViewAngle.
Pyramid Gap | Demonstrates the effects of different pyramid layer gap sizes, configured with PyramidChart.setLayerGap.


Simple Pyramid Chart

Simple Pyramid Chart

This example demonstrates the basic steps in creating pyramid charts.

  • Create a PyramidChart object using PyramidChart.PyramidChart.

  • Specify the center and radius of the pie using PyramidChart.setPyramidSize.

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

  • Add labels at the center of the pyramid layers using PyramidChart.setCenterLabel

  • Generate the chart using BaseChart.makeSession (JSP version) or BaseChart.makeImage (Java version).

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

Source Code Listing

[JSP Version] jspdemo/simplepyramid.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the pyramid chart
double[] data = {156, 123, 211, 179};

// The labels for the pyramid chart
String[] labels = {"Funds", "Bonds", "Stocks", "Cash"};

// Create a PyramidChart object of size 360 x 360 pixels
PyramidChart c = new PyramidChart(360, 360);

// Set the pyramid center at (180, 180), and width x height to 150 x 180 pixels
c.setPyramidSize(180, 180, 150, 300);

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

// Add labels at the center of the pyramid layers using Arial Bold font. The labels
// will have two lines showing the layer name and percentage.
c.setCenterLabel("{label}\n{percent}%", "Arial Bold");

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{label}: US$ {value}M ({percent}%)'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Simple Pyramid Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/simplepyramid.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class simplepyramid implements DemoModule
{
    //Name of demo program
    public String toString() { return "Simple Pyramid Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the pyramid chart
        double[] data = {156, 123, 211, 179};

        // The labels for the pyramid chart
        String[] labels = {"Funds", "Bonds", "Stocks", "Cash"};

        // Create a PyramidChart object of size 360 x 360 pixels
        PyramidChart c = new PyramidChart(360, 360);

        // Set the pyramid center at (180, 180), and width x height to 150 x 180
        // pixels
        c.setPyramidSize(180, 180, 150, 300);

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

        // Add labels at the center of the pyramid layers using Arial Bold font. The
        // labels will have two lines showing the layer name and percentage.
        c.setCenterLabel("{label}\n{percent}%", "Arial Bold");

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='{label}: US$ {value}M ({percent}%)'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new simplepyramid();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


3D Pyramid Chart

3D Pyramid Chart

This example extends the Simple Pyramid Chart example by viewing the pyramid in 3D, using custom colors, inserting gaps between pyramid layers, and adding labels to both the center and the right side of the pyramid layers.

  • Specify 3D viewing angles using PyramidChart.setViewAngle.

  • Specify custom colors using BaseChart.setColors.

  • Insert gaps between pyramid layers using PyramidChart.setLayerGap

  • Add labels to the center and to the right side of the pyramid layers using PyramidChart.setCenterLabel and PyramidChart.setRightLabel.

Source Code Listing

[JSP Version] jspdemo/threedpyramid.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the pyramid chart
double[] data = {156, 123, 211, 179};

// The labels for the pyramid chart
String[] labels = {"Corporate Tax", "Working Capital", "Re-investment", "Dividend"};

// The colors for the pyramid layers
int[] colors = {0x66aaee, 0xeebb22, 0xcccccc, 0xcc88ff};

// Create a PyramidChart object of size 500 x 400 pixels
PyramidChart c = new PyramidChart(500, 400);

// Set the pyramid center at (200, 180), and width x height to 150 x 300 pixels
c.setPyramidSize(200, 180, 150, 300);

// Set the elevation to 15 degrees
c.setViewAngle(15);

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

// Set the layer colors to the given colors
c.setColors2(Chart.DataColor, colors);

// Leave 1% gaps between layers
c.setLayerGap(0.01);

// Add labels at the center of the pyramid layers using Arial Bold font. The labels
// will show the percentage of the layers.
c.setCenterLabel("{percent}%", "Arial Bold");

// Add labels at the right side of the pyramid layers using Arial Bold font. The
// labels will have two lines showing the layer name and value.
c.setRightLabel("{label}\nUS$ {value}M", "Arial Bold");

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{label}: US$ {value}M ({percent}%)'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    3D Pyramid Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/threedpyramid.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class threedpyramid implements DemoModule
{
    //Name of demo program
    public String toString() { return "3D Pyramid Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the pyramid chart
        double[] data = {156, 123, 211, 179};

        // The labels for the pyramid chart
        String[] labels = {"Corporate Tax", "Working Capital", "Re-investment",
            "Dividend"};

        // The colors for the pyramid layers
        int[] colors = {0x66aaee, 0xeebb22, 0xcccccc, 0xcc88ff};

        // Create a PyramidChart object of size 500 x 400 pixels
        PyramidChart c = new PyramidChart(500, 400);

        // Set the pyramid center at (200, 180), and width x height to 150 x 300
        // pixels
        c.setPyramidSize(200, 180, 150, 300);

        // Set the elevation to 15 degrees
        c.setViewAngle(15);

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

        // Set the layer colors to the given colors
        c.setColors2(Chart.DataColor, colors);

        // Leave 1% gaps between layers
        c.setLayerGap(0.01);

        // Add labels at the center of the pyramid layers using Arial Bold font. The
        // labels will show the percentage of the layers.
        c.setCenterLabel("{percent}%", "Arial Bold");

        // Add labels at the right side of the pyramid layers using Arial Bold font.
        // The labels will have two lines showing the layer name and value.
        c.setRightLabel("{label}\nUS$ {value}M", "Arial Bold");

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='{label}: US$ {value}M ({percent}%)'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new threedpyramid();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


Rotated Pyramid Chart

Rotated Pyramid Chart

This example demonstrates a semi-transparent pyramid viewed at elevation and rotation angles. It also demonstrates adding a legend box to the pyramid chart.

The elevation and rotation angles are set using PyramidChart.setViewAngle. The legend box is added using BaseChart.addLegend. Semi-transparent colors are used to make the pyramid semi-transparent.

Source Code Listing

[JSP Version] jspdemo/rotatedpyramid.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the pyramid chart
double[] data = {156, 123, 211, 179};

// The labels for the pyramid chart
String[] labels = {"Funds", "Bonds", "Stocks", "Cash"};

// The semi-transparent colors for the pyramid layers
int[] colors = {0x400000cc, 0x4066aaee, 0x40ffbb00, 0x40ee6622};

// Create a PyramidChart object of size 450 x 400 pixels
PyramidChart c = new PyramidChart(450, 400);

// Set the pyramid center at (220, 180), and width x height to 150 x 300 pixels
c.setPyramidSize(220, 180, 150, 300);

// Set the elevation to 15 degrees and rotation to 75 degrees
c.setViewAngle(15, 75);

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

// Set the layer colors to the given colors
c.setColors2(Chart.DataColor, colors);

// Leave 1% gaps between layers
c.setLayerGap(0.01);

// Add a legend box at (320, 60), with light grey (eeeeee) background and grey
// (888888) border. Set the top-left and bottom-right corners to rounded corners of
// 10 pixels radius.
LegendBox legendBox = c.addLegend(320, 60);
legendBox.setBackground(0xeeeeee, 0x888888);
legendBox.setRoundedCorners(10, 0, 10, 0);

// Add labels at the center of the pyramid layers using Arial Bold font. The labels
// will show the percentage of the layers.
c.setCenterLabel("{percent}%", "Arial Bold");

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{label}: US$ {value}M ({percent}%)'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Rotated Pyramid Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/rotatedpyramid.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class rotatedpyramid implements DemoModule
{
    //Name of demo program
    public String toString() { return "Rotated Pyramid Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the pyramid chart
        double[] data = {156, 123, 211, 179};

        // The labels for the pyramid chart
        String[] labels = {"Funds", "Bonds", "Stocks", "Cash"};

        // The semi-transparent colors for the pyramid layers
        int[] colors = {0x400000cc, 0x4066aaee, 0x40ffbb00, 0x40ee6622};

        // Create a PyramidChart object of size 450 x 400 pixels
        PyramidChart c = new PyramidChart(450, 400);

        // Set the pyramid center at (220, 180), and width x height to 150 x 300
        // pixels
        c.setPyramidSize(220, 180, 150, 300);

        // Set the elevation to 15 degrees and rotation to 75 degrees
        c.setViewAngle(15, 75);

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

        // Set the layer colors to the given colors
        c.setColors2(Chart.DataColor, colors);

        // Leave 1% gaps between layers
        c.setLayerGap(0.01);

        // Add a legend box at (320, 60), with light grey (eeeeee) background and
        // grey (888888) border. Set the top-left and bottom-right corners to rounded
        // corners of 10 pixels radius.
        LegendBox legendBox = c.addLegend(320, 60);
        legendBox.setBackground(0xeeeeee, 0x888888);
        legendBox.setRoundedCorners(10, 0, 10, 0);

        // Add labels at the center of the pyramid layers using Arial Bold font. The
        // labels will show the percentage of the layers.
        c.setCenterLabel("{percent}%", "Arial Bold");

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='{label}: US$ {value}M ({percent}%)'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new rotatedpyramid();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


Cone Chart

Cone Chart

This example demonstrates using PyramidChart.setConeSize to specify using a cone instead of a pyramid to represent the data.

Source Code Listing

[JSP Version] jspdemo/cone.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the pyramid chart
double[] data = {156, 123, 211, 179};

// The labels for the pyramid chart
String[] labels = {"Funds", "Bonds", "Stocks", "Cash"};

// The semi-transparent colors for the pyramid layers
int[] colors = {0x60000088, 0x6066aaee, 0x60ffbb00, 0x60ee6622};

// Create a PyramidChart object of size 480 x 400 pixels
PyramidChart c = new PyramidChart(480, 400);

// Set the cone center at (280, 180), and width x height to 150 x 300 pixels
c.setConeSize(280, 180, 150, 300);

// Set the elevation to 15 degrees
c.setViewAngle(15);

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

// Set the layer colors to the given colors
c.setColors2(Chart.DataColor, colors);

// Leave 1% gaps between layers
c.setLayerGap(0.01);

// Add labels at the left side of the pyramid layers using Arial Bold font. The
// labels will have 3 lines showing the layer name, value and percentage.
c.setLeftLabel("{label}\nUS ${value}K\n({percent}%)", "Arial Bold");

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{label}: US$ {value}K ({percent}%)'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Cone Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/cone.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class cone implements DemoModule
{
    //Name of demo program
    public String toString() { return "Cone Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the pyramid chart
        double[] data = {156, 123, 211, 179};

        // The labels for the pyramid chart
        String[] labels = {"Funds", "Bonds", "Stocks", "Cash"};

        // The semi-transparent colors for the pyramid layers
        int[] colors = {0x60000088, 0x6066aaee, 0x60ffbb00, 0x60ee6622};

        // Create a PyramidChart object of size 480 x 400 pixels
        PyramidChart c = new PyramidChart(480, 400);

        // Set the cone center at (280, 180), and width x height to 150 x 300 pixels
        c.setConeSize(280, 180, 150, 300);

        // Set the elevation to 15 degrees
        c.setViewAngle(15);

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

        // Set the layer colors to the given colors
        c.setColors2(Chart.DataColor, colors);

        // Leave 1% gaps between layers
        c.setLayerGap(0.01);

        // Add labels at the left side of the pyramid layers using Arial Bold font.
        // The labels will have 3 lines showing the layer name, value and percentage.
        c.setLeftLabel("{label}\nUS ${value}K\n({percent}%)", "Arial Bold");

        // Output the chart
        viewer.setChart(c);

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

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new cone();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


Funnel Chart

Funnel Chart

This example demonstrates using PyramidChart.setFunnelSize to specify using a funnel instead of a pyramid to represent the data.

Source Code Listing

[JSP Version] jspdemo/funnel.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the pyramid chart
double[] data = {156, 123, 211, 179};

// The labels for the pyramid chart
String[] labels = {"Corporate Tax", "Working Capital", "Re-investment", "Dividend"};

// The colors for the pyramid layers
int[] colors = {0x66aaee, 0xeebb22, 0xcccccc, 0xcc88ff};

// Create a PyramidChart object of size 500 x 400 pixels
PyramidChart c = new PyramidChart(500, 400);

// Set the funnel center at (200, 210), and width x height to 150 x 300 pixels
c.setFunnelSize(200, 210, 150, 300);

// Set the elevation to 5 degrees
c.setViewAngle(5);

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

// Set the layer colors to the given colors
c.setColors2(Chart.DataColor, colors);

// Leave 1% gaps between layers
c.setLayerGap(0.01);

// Add labels at the right side of the pyramid layers using Arial Bold font. The
// labels will have 3 lines showing the layer name, value and percentage.
c.setRightLabel("{label}\nUS ${value}K\n({percent}%)", "Arial Bold");

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

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{label}: US$ {value}M ({percent}%)'");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Funnel Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>
</body>
</html>

[Java Version] javademo/funnel.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class funnel implements DemoModule
{
    //Name of demo program
    public String toString() { return "Funnel Chart"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the pyramid chart
        double[] data = {156, 123, 211, 179};

        // The labels for the pyramid chart
        String[] labels = {"Corporate Tax", "Working Capital", "Re-investment",
            "Dividend"};

        // The colors for the pyramid layers
        int[] colors = {0x66aaee, 0xeebb22, 0xcccccc, 0xcc88ff};

        // Create a PyramidChart object of size 500 x 400 pixels
        PyramidChart c = new PyramidChart(500, 400);

        // Set the funnel center at (200, 210), and width x height to 150 x 300
        // pixels
        c.setFunnelSize(200, 210, 150, 300);

        // Set the elevation to 5 degrees
        c.setViewAngle(5);

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

        // Set the layer colors to the given colors
        c.setColors2(Chart.DataColor, colors);

        // Leave 1% gaps between layers
        c.setLayerGap(0.01);

        // Add labels at the right side of the pyramid layers using Arial Bold font.
        // The labels will have 3 lines showing the layer name, value and percentage.
        c.setRightLabel("{label}\nUS ${value}K\n({percent}%)", "Arial Bold");

        // Output the chart
        viewer.setChart(c);

        //include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap("clickable", "",
            "title='{label}: US$ {value}M ({percent}%)'"));
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new funnel();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


Pyramid Elevation

Pyramid Elevation

This example demonstrates viewing the pyramid at different elevation angles, configured with PyramidChart.setViewAngle.

Source Code Listing

[JSP Version] jspdemo/pyramidelevation.jsp
<%@page import="ChartDirector.*" %>
<%@page import="javax.servlet.http.*" %>
<%!
// A simple structure to represent a chart image with an image map
private static class ImageWithHotSpot
{
    String imageURL;
    String imageMap;
}

// Function to create the demo charts
ImageWithHotSpot createChart(HttpServletRequest request, int index)
{
    // The data for the pyramid chart
    double[] data = {156, 123, 211, 179};

    // The colors for the pyramid layers
    int[] colors = {0x66aaee, 0xeebb22, 0xcccccc, 0xcc88ff};

    // The elevation angle
    int angle = index * 15;

    // Create a PyramidChart object of size 200 x 200 pixels, with white (ffffff)
    // background and grey (888888) border
    PyramidChart c = new PyramidChart(200, 200, 0xffffff, 0x888888);

    // Set the pyramid center at (100, 100), and width x height to 60 x 120 pixels
    c.setPyramidSize(100, 100, 60, 120);

    // Set the elevation angle
    c.addTitle("Elevation = " + angle, "Arial Italic", 15);
    c.setViewAngle(angle);

    // Set the pyramid data
    c.setData(data);

    // Set the layer colors to the given colors
    c.setColors2(Chart.DataColor, colors);

    // Leave 1% gaps between layers
    c.setLayerGap(0.01);

    // Output the chart
    ImageWithHotSpot ret = new ImageWithHotSpot();
    ret.imageURL = c.makeSession(request, "chart" + index);
    return ret;
}
%>
<%
ImageWithHotSpot chart0 = createChart(request, 0);
ImageWithHotSpot chart1 = createChart(request, 1);
ImageWithHotSpot chart2 = createChart(request, 2);
ImageWithHotSpot chart3 = createChart(request, 3);
ImageWithHotSpot chart4 = createChart(request, 4);
ImageWithHotSpot chart5 = createChart(request, 5);
ImageWithHotSpot chart6 = createChart(request, 6);
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Pyramid Elevation
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart0.imageURL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1.imageURL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart2.imageURL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart3.imageURL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart4.imageURL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart5.imageURL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart6.imageURL)%>'>
</body>
</html>

[Java Version] javademo/pyramidelevation.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class pyramidelevation implements DemoModule
{
    //Name of demo program
    public String toString() { return "Pyramid Elevation"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 7; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the pyramid chart
        double[] data = {156, 123, 211, 179};

        // The colors for the pyramid layers
        int[] colors = {0x66aaee, 0xeebb22, 0xcccccc, 0xcc88ff};

        // The elevation angle
        int angle = index * 15;

        // Create a PyramidChart object of size 200 x 200 pixels, with white (ffffff)
        // background and grey (888888) border
        PyramidChart c = new PyramidChart(200, 200, 0xffffff, 0x888888);

        // Set the pyramid center at (100, 100), and width x height to 60 x 120
        // pixels
        c.setPyramidSize(100, 100, 60, 120);

        // Set the elevation angle
        c.addTitle("Elevation = " + angle, "Arial Italic", 15);
        c.setViewAngle(angle);

        // Set the pyramid data
        c.setData(data);

        // Set the layer colors to the given colors
        c.setColors2(Chart.DataColor, colors);

        // Leave 1% gaps between layers
        c.setLayerGap(0.01);

        // Output the chart
        viewer.setChart(c);
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new pyramidelevation();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);
        frame.getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
        frame.setSize(800, 450);

        // Create the charts and put them in the content pane
        for (int i = 0; i < demo.getNoOfCharts(); ++i)
        {
            ChartViewer viewer = new ChartViewer();
            demo.createChart(viewer, i);
            frame.getContentPane().add(viewer);
        }

        // Display the window
        frame.setVisible(true);
    }
}


Pyramid Rotation

Pyramid Rotation

This example demonstrates viewing the pyramid at different rotation angles, configured with PyramidChart.setViewAngle.

Source Code Listing

[JSP Version] jspdemo/pyramidrotation.jsp
<%@page import="ChartDirector.*" %>
<%@page import="javax.servlet.http.*" %>
<%!
// A simple structure to represent a chart image with an image map
private static class ImageWithHotSpot
{
    String imageURL;
    String imageMap;
}

// Function to create the demo charts
ImageWithHotSpot createChart(HttpServletRequest request, int index)
{
    // The data for the pyramid chart
    double[] data = {156, 123, 211, 179};

    // The semi-transparent colors for the pyramid layers
    int[] colors = {0x400000cc, 0x4066aaee, 0x40ffbb00, 0x40ee6622};

    // The rotation angle
    int angle = index * 15;

    // Create a PyramidChart object of size 200 x 200 pixels, with white (ffffff)
    // background and grey (888888) border
    PyramidChart c = new PyramidChart(200, 200, 0xffffff, 0x888888);

    // Set the pyramid center at (100, 100), and width x height to 60 x 120 pixels
    c.setPyramidSize(100, 100, 60, 120);

    // Set the elevation to 15 degrees and use the given rotation angle
    c.addTitle("Rotation = " + angle, "Arial Italic", 15);
    c.setViewAngle(15, angle);

    // Set the pyramid data
    c.setData(data);

    // Set the layer colors to the given colors
    c.setColors2(Chart.DataColor, colors);

    // Leave 1% gaps between layers
    c.setLayerGap(0.01);

    // Output the chart
    ImageWithHotSpot ret = new ImageWithHotSpot();
    ret.imageURL = c.makeSession(request, "chart" + index);
    return ret;
}
%>
<%
ImageWithHotSpot chart0 = createChart(request, 0);
ImageWithHotSpot chart1 = createChart(request, 1);
ImageWithHotSpot chart2 = createChart(request, 2);
ImageWithHotSpot chart3 = createChart(request, 3);
ImageWithHotSpot chart4 = createChart(request, 4);
ImageWithHotSpot chart5 = createChart(request, 5);
ImageWithHotSpot chart6 = createChart(request, 6);
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Pyramid Rotation
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart0.imageURL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1.imageURL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart2.imageURL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart3.imageURL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart4.imageURL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart5.imageURL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart6.imageURL)%>'>
</body>
</html>

[Java Version] javademo/pyramidrotation.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class pyramidrotation implements DemoModule
{
    //Name of demo program
    public String toString() { return "Pyramid Rotation"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 7; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the pyramid chart
        double[] data = {156, 123, 211, 179};

        // The semi-transparent colors for the pyramid layers
        int[] colors = {0x400000cc, 0x4066aaee, 0x40ffbb00, 0x40ee6622};

        // The rotation angle
        int angle = index * 15;

        // Create a PyramidChart object of size 200 x 200 pixels, with white (ffffff)
        // background and grey (888888) border
        PyramidChart c = new PyramidChart(200, 200, 0xffffff, 0x888888);

        // Set the pyramid center at (100, 100), and width x height to 60 x 120
        // pixels
        c.setPyramidSize(100, 100, 60, 120);

        // Set the elevation to 15 degrees and use the given rotation angle
        c.addTitle("Rotation = " + angle, "Arial Italic", 15);
        c.setViewAngle(15, angle);

        // Set the pyramid data
        c.setData(data);

        // Set the layer colors to the given colors
        c.setColors2(Chart.DataColor, colors);

        // Leave 1% gaps between layers
        c.setLayerGap(0.01);

        // Output the chart
        viewer.setChart(c);
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new pyramidrotation();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);
        frame.getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
        frame.setSize(800, 450);

        // Create the charts and put them in the content pane
        for (int i = 0; i < demo.getNoOfCharts(); ++i)
        {
            ChartViewer viewer = new ChartViewer();
            demo.createChart(viewer, i);
            frame.getContentPane().add(viewer);
        }

        // Display the window
        frame.setVisible(true);
    }
}


Pyramid Gap

Pyramid Gap

This example demonstrates the effects of different pyramid layer gap sizes, configured with PyramidChart.setLayerGap.

Source Code Listing

[JSP Version] jspdemo/pyramidgap.jsp
<%@page import="ChartDirector.*" %>
<%@page import="javax.servlet.http.*" %>
<%!
// A simple structure to represent a chart image with an image map
private static class ImageWithHotSpot
{
    String imageURL;
    String imageMap;
}

// Function to create the demo charts
ImageWithHotSpot createChart(HttpServletRequest request, int index)
{
    // The data for the pyramid chart
    double[] data = {156, 123, 211, 179};

    // The colors for the pyramid layers
    int[] colors = {0x66aaee, 0xeebb22, 0xcccccc, 0xcc88ff};

    // The layer gap
    double gap = index * 0.01;

    // Create a PyramidChart object of size 200 x 200 pixels, with white (ffffff)
    // background and grey (888888) border
    PyramidChart c = new PyramidChart(200, 200, 0xffffff, 0x888888);

    // Set the pyramid center at (100, 100), and width x height to 60 x 120 pixels
    c.setPyramidSize(100, 100, 60, 120);

    // Set the layer gap
    c.addTitle("Gap = " + gap, "Arial Italic", 15);
    c.setLayerGap(gap);

    // Set the elevation to 15 degrees
    c.setViewAngle(15);

    // Set the pyramid data
    c.setData(data);

    // Set the layer colors to the given colors
    c.setColors2(Chart.DataColor, colors);

    // Output the chart
    ImageWithHotSpot ret = new ImageWithHotSpot();
    ret.imageURL = c.makeSession(request, "chart" + index);
    return ret;
}
%>
<%
ImageWithHotSpot chart0 = createChart(request, 0);
ImageWithHotSpot chart1 = createChart(request, 1);
ImageWithHotSpot chart2 = createChart(request, 2);
ImageWithHotSpot chart3 = createChart(request, 3);
ImageWithHotSpot chart4 = createChart(request, 4);
ImageWithHotSpot chart5 = createChart(request, 5);
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Pyramid Gap
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart0.imageURL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1.imageURL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart2.imageURL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart3.imageURL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart4.imageURL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart5.imageURL)%>'>
</body>
</html>

[Java Version] javademo/pyramidgap.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class pyramidgap implements DemoModule
{
    //Name of demo program
    public String toString() { return "Pyramid Gap"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 6; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The data for the pyramid chart
        double[] data = {156, 123, 211, 179};

        // The colors for the pyramid layers
        int[] colors = {0x66aaee, 0xeebb22, 0xcccccc, 0xcc88ff};

        // The layer gap
        double gap = index * 0.01;

        // Create a PyramidChart object of size 200 x 200 pixels, with white (ffffff)
        // background and grey (888888) border
        PyramidChart c = new PyramidChart(200, 200, 0xffffff, 0x888888);

        // Set the pyramid center at (100, 100), and width x height to 60 x 120
        // pixels
        c.setPyramidSize(100, 100, 60, 120);

        // Set the layer gap
        c.addTitle("Gap = " + gap, "Arial Italic", 15);
        c.setLayerGap(gap);

        // Set the elevation to 15 degrees
        c.setViewAngle(15);

        // Set the pyramid data
        c.setData(data);

        // Set the layer colors to the given colors
        c.setColors2(Chart.DataColor, colors);

        // Output the chart
        viewer.setChart(c);
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new pyramidgap();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);
        frame.getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
        frame.setSize(800, 450);

        // Create the charts and put them in the content pane
        for (int i = 0; i < demo.getNoOfCharts(); ++i)
        {
            ChartViewer viewer = new ChartViewer();
            demo.createChart(viewer, i);
            frame.getContentPane().add(viewer);
        }

        // Display the window
        frame.setVisible(true);
    }
}


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 Chart.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

[JSP Version] jspdemo/semicirclemeter.jsp
<%@page import="ChartDirector.*" %>
<%
// The value to display on the meter
double 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
AngularMeter m = new AngularMeter(200, 115, Chart.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, Chart.TextColor, Chart.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
String chart1URL = m.makeSession(request, "chart1");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Semi-Circle Meter
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'>
</body>
</html>

[Java Version] javademo/semicirclemeter.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class semicirclemeter implements DemoModule
{
    //Name of demo program
    public String toString() { return "Semi-Circle Meter"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The value to display on the meter
        double 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
        AngularMeter m = new AngularMeter(200, 115, Chart.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, Chart.TextColor, Chart.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
        viewer.setChart(m);
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new semicirclemeter();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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 Chart.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

[JSP Version] jspdemo/roundmeter.jsp
<%@page import="ChartDirector.*" %>
<%
// The value to display on the meter
double 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.
AngularMeter m = new AngularMeter(200, 200, Chart.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, Chart.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, Chart.TextColor, Chart.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, Chart.Center
    ).setBackground(0x000000, 0x000000, -1);

// Add a semi-transparent blue (40333399) pointer at the specified value
m.addPointer(value, 0x40333399);

// Output the chart
String chart1URL = m.makeSession(request, "chart1");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Round Meter
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'>
</body>
</html>

[Java Version] javademo/roundmeter.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class roundmeter implements DemoModule
{
    //Name of demo program
    public String toString() { return "Round Meter"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The value to display on the meter
        double 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.
        AngularMeter m = new AngularMeter(200, 200, Chart.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, Chart.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, Chart.TextColor, Chart.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,
            Chart.Center).setBackground(0x000000, 0x000000, -1);

        // Add a semi-transparent blue (40333399) pointer at the specified value
        m.addPointer(value, 0x40333399);

        // Output the chart
        viewer.setChart(m);
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new roundmeter();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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 Chart.goldColor, Chart.silverColor and Chart.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

[JSP Version] jspdemo/wideameter.jsp
<%@page import="ChartDirector.*" %>
<%@page import="javax.servlet.http.*" %>
<%!
// Function to create the demo charts
String createChart(HttpServletRequest request, int index)
{
    // The value to display on the meter
    double value = 6.5;

    // Create an AugularMeter object of size 200 x 100 pixels with rounded corners
    AngularMeter m = new AngularMeter(200, 100);

    //Set search path to current JSP directory for loading icon images
    m.setSearchPath(getServletConfig().getServletContext(), request);
    m.setRoundedFrame();

    // Set meter background according to a parameter
    if (index == 0) {
        // Use gold background color
        m.setBackground(Chart.goldColor(), 0x000000, -2);
    } else if (index == 1) {
        // Use silver background color
        m.setBackground(Chart.silverColor(), 0x000000, -2);
    } else if (index == 2) {
        // Use metallic blue (9898E0) background color
        m.setBackground(Chart.metalColor(0x9898e0), 0x000000, -2);
    } else if (index == 3) {
        // Use a wood pattern as background color
        m.setBackground(m.patternColor2("wood.png"), 0x000000, -2);
    } else if (index == 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(Chart.Bottom, "OUTPUT POWER LEVEL\n", "Arial Bold", 10);

    // Add a semi-transparent black (80000000) pointer at the specified value
    m.addPointer(value, 0x80000000);

    // Output the chart
    return m.makeSession(request, "chart" + index);
}
%>
<%
String chart0URL = createChart(request, 0);
String chart1URL = createChart(request, 1);
String chart2URL = createChart(request, 2);
String chart3URL = createChart(request, 3);
String chart4URL = createChart(request, 4);
String chart5URL = createChart(request, 5);
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Wide Angular Meters
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart0URL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart2URL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart3URL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart4URL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart5URL)%>'>
</body>
</html>

[Java Version] javademo/wideameter.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class wideameter implements DemoModule
{
    //Name of demo program
    public String toString() { return "Wide Angular Meters"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 6; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The value to display on the meter
        double value = 6.5;

        // Create an AugularMeter object of size 200 x 100 pixels with rounded
        // corners
        AngularMeter m = new AngularMeter(200, 100);
        m.setRoundedFrame();

        // Set meter background according to a parameter
        if (index == 0) {
            // Use gold background color
            m.setBackground(Chart.goldColor(), 0x000000, -2);
        } else if (index == 1) {
            // Use silver background color
            m.setBackground(Chart.silverColor(), 0x000000, -2);
        } else if (index == 2) {
            // Use metallic blue (9898E0) background color
            m.setBackground(Chart.metalColor(0x9898e0), 0x000000, -2);
        } else if (index == 3) {
            // Use a wood pattern as background color
            m.setBackground(m.patternColor2("wood.png"), 0x000000, -2);
        } else if (index == 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(Chart.Bottom, "OUTPUT POWER LEVEL\n", "Arial Bold", 10);

        // Add a semi-transparent black (80000000) pointer at the specified value
        m.addPointer(value, 0x80000000);

        // Output the chart
        viewer.setChart(m);
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new wideameter();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);
        frame.getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
        frame.setSize(800, 450);

        // Create the charts and put them in the content pane
        for (int i = 0; i < demo.getNoOfCharts(); ++i)
        {
            ChartViewer viewer = new ChartViewer();
            demo.createChart(viewer, i);
            frame.getContentPane().add(viewer);
        }

        // Display the window
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/squareameter.jsp
<%@page import="ChartDirector.*" %>
<%@page import="javax.servlet.http.*" %>
<%!
// Function to create the demo charts
String createChart(HttpServletRequest request, int index)
{
    // The value to display on the meter
    double 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.
    AngularMeter m = new AngularMeter(110, 110, Chart.silverColor(), 0x000000, -2);

    // Set meter appearance according to a parameter
    if (index == 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, Chart.TextColor, Chart.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,
            Chart.TopRight).setBackground(0, 0, -1);
    } else if (index == 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, Chart.TextColor, Chart.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,
            Chart.BottomRight).setBackground(0, 0, -1);
    } else if (index == 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, Chart.TextColor, Chart.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,
            Chart.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, Chart.TextColor, Chart.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,
            Chart.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(request, "chart" + index);
}
%>
<%
String chart0URL = createChart(request, 0);
String chart1URL = createChart(request, 1);
String chart2URL = createChart(request, 2);
String chart3URL = createChart(request, 3);
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Square Angular Meters
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart0URL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart2URL)%>'>
<img src='<%=response.encodeURL("getchart.jsp?"+chart3URL)%>'>
</body>
</html>

[Java Version] javademo/squareameter.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class squareameter implements DemoModule
{
    //Name of demo program
    public String toString() { return "Square Angular Meters"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 4; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The value to display on the meter
        double 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.
        AngularMeter m = new AngularMeter(110, 110, Chart.silverColor(), 0x000000, -2
            );

        // Set meter appearance according to a parameter
        if (index == 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, Chart.TextColor, Chart.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,
                Chart.TopRight).setBackground(0, 0, -1);
        } else if (index == 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, Chart.TextColor, Chart.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,
                Chart.BottomRight).setBackground(0, 0, -1);
        } else if (index == 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, Chart.TextColor, Chart.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,
                Chart.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, Chart.TextColor, Chart.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,
                Chart.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
        viewer.setChart(m);
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new squareameter();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);
        frame.getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
        frame.setSize(800, 450);

        // Create the charts and put them in the content pane
        for (int i = 0; i < demo.getNoOfCharts(); ++i)
        {
            ChartViewer viewer = new ChartViewer();
            demo.createChart(viewer, i);
            frame.getContentPane().add(viewer);
        }

        // Display the window
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/multiameter.jsp
<%@page import="ChartDirector.*" %>
<%
// Create an AugularMeter object of size 200 x 200 pixels
AngularMeter m = new AngularMeter(200, 200);

// Use white on black color palette for default text and line colors
m.setColors(Chart.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, Chart.TextColor, Chart.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(Chart.ArrowPointer2);

// Add a semi-transparent yellow (80FFFF66) pointer using another arrow shape
m.addPointer(51, 0x80ffff66, 0xffff66).setShape(Chart.ArrowPointer);

// Add a semi-transparent green (8066FF66) pointer using the line shape
m.addPointer(72, 0x8066ff66, 0x66ff66).setShape(Chart.LinePointer);

// Add a semi-transparent grey (80CCCCCC) pointer using the pencil shape
m.addPointer(85, 0x80cccccc, 0xcccccc).setShape(Chart.PencilPointer);

// Output the chart
String chart1URL = m.makeSession(request, "chart1");
%>
<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 color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'>
</body>
</html>

[Java Version] javademo/multiameter.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class multiameter implements DemoModule
{
    //Name of demo program
    public String toString() { return "Multi-Pointer Angular Meter"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // Create an AugularMeter object of size 200 x 200 pixels
        AngularMeter m = new AngularMeter(200, 200);

        // Use white on black color palette for default text and line colors
        m.setColors(Chart.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, Chart.TextColor, Chart.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(Chart.ArrowPointer2);

        // Add a semi-transparent yellow (80FFFF66) pointer using another arrow shape
        m.addPointer(51, 0x80ffff66, 0xffff66).setShape(Chart.ArrowPointer);

        // Add a semi-transparent green (8066FF66) pointer using the line shape
        m.addPointer(72, 0x8066ff66, 0x66ff66).setShape(Chart.LinePointer);

        // Add a semi-transparent grey (80CCCCCC) pointer using the pencil shape
        m.addPointer(85, 0x80cccccc, 0xcccccc).setShape(Chart.PencilPointer);

        // Output the chart
        viewer.setChart(m);
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new multiameter();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/iconameter.jsp
<%@page import="ChartDirector.*" %>
<%
// The value to display on the meter
double value = 85;

// Create an AugularMeter object of size 70 x 90 pixels, using black background with
// a 2 pixel 3D depressed border.
AngularMeter m = new AngularMeter(70, 90, 0, 0, -2);

//Set search path to current JSP directory for loading icon images
m.setSearchPath(getServletConfig().getServletContext(), request);

// Use white on black color palette for default text and line colors
m.setColors(Chart.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, new String[]{"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
String chart1URL = m.makeSession(request, "chart1");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Icon Angular Meter
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'>
</body>
</html>

[Java Version] javademo/iconameter.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class iconameter implements DemoModule
{
    //Name of demo program
    public String toString() { return "Icon Angular Meter"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The value to display on the meter
        double value = 85;

        // Create an AugularMeter object of size 70 x 90 pixels, using black
        // background with a 2 pixel 3D depressed border.
        AngularMeter m = new AngularMeter(70, 90, 0, 0, -2);

        // Use white on black color palette for default text and line colors
        m.setColors(Chart.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, new String[]{"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
        viewer.setChart(m);
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new iconameter();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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 Chart.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

[JSP Version] jspdemo/hlinearmeter.jsp
<%@page import="ChartDirector.*" %>
<%
// The value to display on the meter
double value = 75.35;

// Create an LinearMeter object of size 250 x 75 pixels, using silver background with
// a 2 pixel black 3D depressed border.
LinearMeter m = new LinearMeter(250, 75, Chart.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, Chart.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, Chart.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, Chart.BottomRight
    ).setBackground(0, 0, -1);

// Output the chart
String chart1URL = m.makeSession(request, "chart1");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Horizontal Linear Meter
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'>
</body>
</html>

[Java Version] javademo/hlinearmeter.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class hlinearmeter implements DemoModule
{
    //Name of demo program
    public String toString() { return "Horizontal Linear Meter"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The value to display on the meter
        double value = 75.35;

        // Create an LinearMeter object of size 250 x 75 pixels, using silver
        // background with a 2 pixel black 3D depressed border.
        LinearMeter m = new LinearMeter(250, 75, Chart.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, Chart.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,
            Chart.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,
            Chart.BottomRight).setBackground(0, 0, -1);

        // Output the chart
        viewer.setChart(m);
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new hlinearmeter();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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 Chart.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

[JSP Version] jspdemo/vlinearmeter.jsp
<%@page import="ChartDirector.*" %>
<%
// The value to display on the meter
double value = 75.35;

// Create an LinearMeter object of size 60 x 265 pixels, using silver background with
// a 2 pixel black 3D depressed border.
LinearMeter m = new LinearMeter(60, 265, Chart.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, Chart.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,
    Chart.BottomCenter).setBackground(0, 0, -1);

// Output the chart
String chart1URL = m.makeSession(request, "chart1");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Vertical Linear Meter
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'>
</body>
</html>

[Java Version] javademo/vlinearmeter.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class vlinearmeter implements DemoModule
{
    //Name of demo program
    public String toString() { return "Vertical Linear Meter"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The value to display on the meter
        double value = 75.35;

        // Create an LinearMeter object of size 60 x 265 pixels, using silver
        // background with a 2 pixel black 3D depressed border.
        LinearMeter m = new LinearMeter(60, 265, Chart.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, Chart.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,
            Chart.BottomCenter).setBackground(0, 0, -1);

        // Output the chart
        viewer.setChart(m);
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new vlinearmeter();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/multihmeter.jsp
<%@page import="ChartDirector.*" %>
<%
// The values to display on the meter
double value0 = 30.99;
double value1 = 45.35;
double value2 = 77.64;

// Create an LinearMeter object of size 250 x 75 pixels, using silver background with
// a 2 pixel black 3D depressed border.
LinearMeter m = new LinearMeter(250, 75, Chart.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, Chart.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, Chart.BottomLeft);

// Add three text boxes to show the values in this meter
m.addText(148, 70, m.formatValue(value0, "2"), "Arial", 8, 0x6666ff,
    Chart.BottomRight).setBackground(0, 0, -1);
m.addText(193, 70, m.formatValue(value1, "2"), "Arial", 8, 0x33ff33,
    Chart.BottomRight).setBackground(0, 0, -1);
m.addText(238, 70, m.formatValue(value2, "2"), "Arial", 8, 0xff3333,
    Chart.BottomRight).setBackground(0, 0, -1);

// Output the chart
String chart1URL = m.makeSession(request, "chart1");
%>
<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 color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'>
</body>
</html>

[Java Version] javademo/multihmeter.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class multihmeter implements DemoModule
{
    //Name of demo program
    public String toString() { return "Multi-Pointer Horizontal Meter"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The values to display on the meter
        double value0 = 30.99;
        double value1 = 45.35;
        double value2 = 77.64;

        // Create an LinearMeter object of size 250 x 75 pixels, using silver
        // background with a 2 pixel black 3D depressed border.
        LinearMeter m = new LinearMeter(250, 75, Chart.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, Chart.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, Chart.BottomLeft);

        // Add three text boxes to show the values in this meter
        m.addText(148, 70, m.formatValue(value0, "2"), "Arial", 8, 0x6666ff,
            Chart.BottomRight).setBackground(0, 0, -1);
        m.addText(193, 70, m.formatValue(value1, "2"), "Arial", 8, 0x33ff33,
            Chart.BottomRight).setBackground(0, 0, -1);
        m.addText(238, 70, m.formatValue(value2, "2"), "Arial", 8, 0xff3333,
            Chart.BottomRight).setBackground(0, 0, -1);

        // Output the chart
        viewer.setChart(m);
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new multihmeter();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/multivmeter.jsp
<%@page import="ChartDirector.*" %>
<%
// The values to display on the meter
double value0 = 30.99;
double value1 = 45.35;
double value2 = 77.64;

// Create an LinearMeter object of size 60 x 245 pixels, using silver background with
// a 2 pixel black 3D depressed border.
LinearMeter m = new LinearMeter(60, 245, Chart.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, Chart.TopCenter).setBackground(
    0x9999ff);

// Output the chart
String chart1URL = m.makeSession(request, "chart1");
%>
<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 color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'>
</body>
</html>

[Java Version] javademo/multivmeter.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class multivmeter implements DemoModule
{
    //Name of demo program
    public String toString() { return "Multi-Pointer Vertical Meter"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The values to display on the meter
        double value0 = 30.99;
        double value1 = 45.35;
        double value2 = 77.64;

        // Create an LinearMeter object of size 60 x 245 pixels, using silver
        // background with a 2 pixel black 3D depressed border.
        LinearMeter m = new LinearMeter(60, 245, Chart.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, Chart.TopCenter
            ).setBackground(0x9999ff);

        // Output the chart
        viewer.setChart(m);
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new multivmeter();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

[JSP Version] jspdemo/linearzonemeter.jsp
<%@page import="ChartDirector.*" %>
<%
// The value to display on the meter
double value = 85;

// Create an LinearMeter object of size 210 x 45 pixels, using silver background with
// a 2 pixel black 3D depressed border.
LinearMeter m = new LinearMeter(210, 45, Chart.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, Chart.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(Chart.Bottom, "Battery Level", "Arial Bold", 8).setBackground(
    Chart.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(Chart.TriangularPointer);

// Output the chart
String chart1URL = m.makeSession(request, "chart1");
%>
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Linear Zone Meter
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'>
</body>
</html>

[Java Version] javademo/linearzonemeter.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import ChartDirector.*;

public class linearzonemeter implements DemoModule
{
    //Name of demo program
    public String toString() { return "Linear Zone Meter"; }

    //Number of charts produced in this demo
    public int getNoOfCharts() { return 1; }

    //Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // The value to display on the meter
        double value = 85;

        // Create an LinearMeter object of size 210 x 45 pixels, using silver
        // background with a 2 pixel black 3D depressed border.
        LinearMeter m = new LinearMeter(210, 45, Chart.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, Chart.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(Chart.Bottom, "Battery Level", "Arial Bold", 8).setBackground(
            Chart.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(Chart.TriangularPointer);

        // Output the chart
        viewer.setChart(m);
    }

    //Allow this module to run as standalone program for easy testing
    public static void main(String[] args)
    {
        //Instantiate an instance of this demo module
        DemoModule demo = new linearzonemeter();

        //Create and set up the main window
        JFrame frame = new JFrame(demo.toString());
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);} });
        frame.getContentPane().setBackground(Color.white);

        // Create the chart and put them in the content pane
        ChartViewer viewer = new ChartViewer();
        demo.createChart(viewer, 0);
        frame.getContentPane().add(viewer);

        // Display the window
        frame.pack();
        frame.setVisible(true);
    }
}


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

The DBTable Class
Overview of the ChartDirector.DBTable utility class that allows database table columns to be retrieved as arrays easily.

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 .

Producing Multiple Charts With One Database Query
Complete example demonstrating how to perform database queries and use the data to create two charts in the same web page.

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.


The DBTable Class

The DBTable Class

The ChartDirector API is designed to accept data values as array variables, which is the most flexible approach.

In Java, access to database is commonly through JDBC. Database query results are usually represented by java.sql.ResultSet objects. To use data from database to draw charts, one simply needs to read data from java.sql.ResultSet objects to array variables and pass them to ChartDirector.

To simplify things further, ChartDirector comes with a utility class DBTable. This class accepts java.sql.ResultSet objects as input, and creates arrays representing the columns of the query result. These arrays may then be used by ChartDirector to draw charts, or can be manipulated further (eg. using ChartDirector ArrayMath to compute moving averages, moving standard deviations, curve fitting, etc.)

Because of its convenience, all database examples in this documentation will use the DBTable class to read data from java.sql.ResultSet objects.


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 "jspdemo" subdirectory.

Note: These sample scripts use the JDBC to ODBC driver "sun.jdbc.odbc.JdbcOdbcDriver", with the ODBC driver being "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)}". Due to the database drivers used, these sample scripts probably only run on Windows using SUN Java VM.

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 HTML form 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 that although the database sample codes are JSP web pages, the techniques are equally applicable to standalone Java applications.

Note: This example uses the JDBC to ODBC driver "sun.jdbc.odbc.JdbcOdbcDriver", with the ODBC driver being "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)}". Due to the database driver used, this example probably only runs on Windows using SUN Java VM.

[JSP Version] jspdemo/dbdemo1.jsp
<%@page import="ChartDirector.*" %>
<%
// The currently selected year
int selectedYear = (request.getParameter("year") == null) ? 2001 :
    Integer.parseInt(request.getParameter("year"));

// SQL statement to get the monthly revenues for the selected year.
String SQL =
    "Select Software, Hardware, Services From revenue Where Year(TimeStamp) = " +
    selectedYear + " Order By TimeStamp";

//
// Connect to database and read the query result into arrays
//

// In this example, we use an MS Access database through an ODBC driver.
String dbFile = new java.io.File(application.getRealPath(request.getServletPath())
    ).getParent() + "/sample.mdb";

// Connect to database and prepare the query
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
java.sql.Connection dbConn = java.sql.DriverManager.getConnection
    ("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=" + dbFile);
java.sql.PreparedStatement stmt = dbConn.prepareStatement(SQL);

// Execute the query and read the results into arrays
DBTable table = new DBTable(stmt.executeQuery());
double[] software = table.getCol(0);
double[] hardware = table.getCol(1);
double[] services = table.getCol(2);

stmt.close();
dbConn.close();

//
// Now we have read data into arrays, we can draw the chart using ChartDirector
//

// 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.
XYChart c = new 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, Chart.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(Chart.Transparent);

// Add a stacked bar chart layer using the supplied data
BarLayer layer = c.addBarLayer2(Chart.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(Chart.Transparent, Chart.softLighting(Chart.Left));

// Set the x axis labels. In this example, the labels must be Jan - Dec.
String[] labels = {"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
String chart1URL = c.makeSession(request, "chart1");

// Include tool tip for the chart
String imageMap1 = c.getHTMLImageMap("", "",
    "title='{dataSetName} Revenue for {xLabel} = USD {value}M'");

//
// The following code generates the <option> tags for the HTML select box, with the
// <option> tag representing the currently selected year marked as selected.
//

StringBuffer selectYearOptions = new StringBuffer();
for (int i = 1990; i <= 2001; ++i)
{
    selectYearOptions.append("<option value='" + i + "'");
    if (i == selectedYear)
        selectYearOptions.append(" selected");
    selectYearOptions.append(">" + i + "</option>");
}
%>
<html>
<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.jsp?file=<%=request.getServletPath()%>'>
    View Source Code
</a>
<br />
<br />
<form>
    I want to obtain the revenue data for the year
    <select name="year">
        <%=selectYearOptions.toString()%>
    </select>
    <input type="submit" value="OK">
</form>
</div>

<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=imageMap1%></map>

</body>
</html>

The first part of the above code are standard JDBC database code. It first opens a connection to a database, then issue a query to the database.

// SQL statement to get the monthly revenues for the selected year.
String SQL =
    "Select Software, Hardware, Services From revenue Where Year(TimeStamp) = " +
    selectedYear + " Order By TimeStamp";

//
// Connect to database and read the query result into arrays
//

// In this example, we use an MS Access database through an ODBC driver.
String dbFile = new java.io.File(application.getRealPath(request.getServletPath())
    ).getParent() + "/sample.mdb";

// Connect to database and prepare the query
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
java.sql.Connection dbConn = java.sql.DriverManager.getConnection
    ("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=" + dbFile);
java.sql.PreparedStatement stmt = dbConn.prepareStatement(SQL);

The code then uses the ChartDirector utility class DBTable to read in the result of the query. The DBTable allows the query results to be accessed as arrays easily.

DBTable table = new DBTable(stmt.executeQuery());
double[] software = table.getCol(0);
double[] hardware = table.getCol(1);
double[] services = table.getCol(2);

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.

Note that although the database sample codes are JSP web pages, the techniques are equally applicable to standalone Java applications.

As similar to the last example, the user will select a year from a HTML form 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: This example uses the JDBC to ODBC driver "sun.jdbc.odbc.JdbcOdbcDriver", with the ODBC driver being "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)}". Due to the database driver used, this example probably only runs on Windows using SUN Java VM.

[JSP Version] jspdemo/dbdemo2.jsp
<%@page import="ChartDirector.*, java.util.*"%>
<%!
// A simple structure to represent a chart image with an image map
private static class ImageWithHotSpot
{
    String imageURL;
    String imageMap;
}

//
// Create the first chart based on the given data
//
private ImageWithHotSpot createChart1(HttpServletRequest request, int selectedYear,
    double[] software, double[] hardware, double[] services)
{
    // 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.
    XYChart c = new 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,
        Chart.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(Chart.Transparent);

    // Add a line chart layer using the supplied data
    LineLayer layer = c.addLineLayer2();
    layer.addDataSet(software, 0xff0000, "Software").setDataSymbol(Chart.CircleShape,
        9);
    layer.addDataSet(hardware, 0x00ff00, "Hardware").setDataSymbol(
        Chart.DiamondShape, 11);
    layer.addDataSet(services, 0xffaa00, "Services").setDataSymbol(Chart.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.
    String[] labels = {"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
    ImageWithHotSpot ret = new ImageWithHotSpot();
    ret.imageURL = c.makeSession(request, "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
//
private ImageWithHotSpot createChart2(HttpServletRequest request, int selectedYear,
    double[] software, double[] hardware, double[] services)
{
    // 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.
    XYChart c = new 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, Chart.glassEffect(Chart.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(Chart.Transparent);

    // Add a stacked area chart layer using the supplied data
    AreaLayer layer = c.addAreaLayer2(Chart.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(Chart.SameAsMainColor);

    // Set the x axis labels. In this example, the labels must be Jan - Dec.
    String[] labels = {"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
    ImageWithHotSpot ret = new ImageWithHotSpot();
    ret.imageURL = c.makeSession(request, "chart2");

    // Include tool tip for the chart
    ret.imageMap = c.getHTMLImageMap("", "",
        "title='{dataSetName} Revenue for {xLabel} = USD {value}M'");
    return ret;
}
%>
<%

// The currently selected year
int selectedYear = (request.getParameter("year") == null) ? 2001 :
    Integer.parseInt(request.getParameter("year"));

// SQL statement to get the monthly revenues for the selected year.
String SQL =
    "Select Software, Hardware, Services From revenue Where Year(TimeStamp) = " +
    selectedYear + " Order By TimeStamp";

//
// Connect to database and read the query result into arrays
//

// In this example, we use an MS Access database through an ODBC driver.
String dbFile = new java.io.File(application.getRealPath(request.getServletPath())
    ).getParent() + "/sample.mdb";

// Connect to database and prepare the query
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
java.sql.Connection dbConn = java.sql.DriverManager.getConnection
    ("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=" + dbFile);
java.sql.PreparedStatement stmt = dbConn.prepareStatement(SQL);

// Execute the query and read the results into arrays
DBTable table = new DBTable(stmt.executeQuery());
double[] software = table.getCol(0);
double[] hardware = table.getCol(1);
double[] services = table.getCol(2);

stmt.close();
dbConn.close();

//
// Now we obtained the data into arrays, we can draw the chart using ChartDirector
//

ImageWithHotSpot chart1 = createChart1(request, selectedYear, software, hardware,
    services);
ImageWithHotSpot chart2 = createChart2(request, selectedYear, software, hardware,
    services);

//
// The following code generates the <option> tags for the HTML select box, with the
// <option> tag representing the currently selected year marked as selected.
//

StringBuffer selectYearOptions = new StringBuffer();
for (int i = 1990; i <= 2001; ++i)
{
    selectYearOptions.append("<option value='" + i + "'");
    if (i == selectedYear)
        selectYearOptions.append(" selected");
    selectYearOptions.append(">" + i + "</option>");
}
%>
<html>
<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">
<a href='viewsource.jsp?file=<%=request.getServletPath()%>'>
    View Source Code
</a>
<br />
<br />
The example demonstrates creating two charts in the same page using data from a database.
<br />
<br />
<form>
    I want to obtain the revenue data for the year
    <select name="year">
        <%=selectYearOptions.toString()%>
    </select>
    <input type="submit" value="OK">
</form>
</div>

<img src='<%=response.encodeURL("getchart.jsp?"+chart1.imageURL)%>'
    usemap="#map1" border="0">
<map name="map1"><%=chart1.imageMap%></map>
<br /><br />
<img src='<%=response.encodeURL("getchart.jsp?"+chart2.imageURL)%>'
    usemap="#map2" border="0">
<map name="map2"><%=chart2.imageMap%></map>
</body>
</html>

The above code contains two methods for generating charts and putting the charts. The data for the charts are passed in as arguments.

private ImageWithHotSpot createChart1(HttpServletRequest request, int selectedYear,
    double[] software, double[] hardware, double[] services)

private ImageWithHotSpot createChart2(HttpServletRequest request, int selectedYear,
    double[] software, double[] hardware, double[] services)

When the JSP is executed, a connection to a database is created and then a query sent to the database. The query result is then read into a DBTable object. 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.

// Execute the query and read the results into arrays
DBTable table = new DBTable(stmt.executeQuery());
double[] software = table.getCol(0);
double[] hardware = table.getCol(1);
double[] services = table.getCol(2);

stmt.close();
dbConn.close();

//
// Now we obtained the data into arrays, we can draw the chart using ChartDirector
//

ImageWithHotSpot chart1 = createChart1(request, selectedYear, software, hardware,
    services);
ImageWithHotSpot chart2 = createChart2(request, 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.

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

This section will focus on clickable charts for JSP applications, such as how to use hot spots as hypertext links to "drill- down" on the data, or to trigger client-side Javascript.

For standalone Java applications, by using the ChartViewer control, all hot spots are always clickable and can be listened to using HotSpotListener and HotSpotMotionListener interfaces. They are analogous to standard mouse events so they will not be discussed further.

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.


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

[JSP Version] jspdemo/clickbar.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the bar chart
double[] data = {450, 560, 630, 800, 1100, 1350, 1600, 1950, 2300, 2700};

// The labels for the bar chart
String[] labels = {"1996", "1997", "1998", "1999", "2000", "2001", "2002", "2003",
    "2004", "2005"};

// Create a XYChart object of size 600 x 360 pixels
XYChart c = new 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(Chart.Transparent, Chart.softLighting(Chart.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
String chart1URL = c.makeSession(request, "chart1");

// Create an image map for the chart
String imageMap1 = c.getHTMLImageMap("clickline.jsp", "",
    "title='{xLabel}: US$ {value|0}M'");
%>
<html>
<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.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src="<%=response.encodeURL("getchart.jsp?"+chart1URL)%>" border="0" usemap="#map1">
<map name="map1">
<%=imageMap1%>
</map>
</body>
</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:

String imageMap = c.getHTMLImageMap("clickline.jsp", "",
    "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.jsp" 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.jsp?x=0&xLabel=1996&dataSet=0&dataSetName=&value=450">

<area shape="rect" coords="117,268,153,320" title='1997: US$ 560M'
    href="clickline.jsp?x=1&xLabel=1997&dataSet=1&dataSetName=&value=560">

<area shape="rect" coords="167,261,203,320" title='1998: US$ 630M'
    href="clickline.jsp?x=2&xLabel=1998&dataSet=2&dataSetName=&value=630">

<area shape="rect" coords="217,245,253,320" title='1999: US$ 800M'
    href="clickline.jsp?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.jsp" as the URL, with query parameters appended to describe the bars. In this way, "clickline.jsp" 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.jsp" will be invoked.

The code for "clickline.jsp" 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.jsp" is very similar to "clickbar.jsp", it will not be explained further here.

[JSP Version] jspdemo/clickline.jsp
<%@page import="ChartDirector.*" %>
<%
// Get the selected year.
String selectedYear = request.getParameter("xLabel");

//
// In real life, the data may come from a database based on selectedYear. In this
// example, we just use a random number generator.
//
int seed = 50 + (Integer.parseInt(selectedYear) - 1996) * 15;
RanTable rantable = new RanTable(seed, 1, 12);
rantable.setCol2(0, seed, -seed * 0.25, seed * 0.33, seed * 0.1, seed * 3);

double[] data = rantable.getCol(0);

//
// 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
XYChart c = new 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
ChartDirector.DataSet 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(Chart.CircleSymbol, 13);

// Set the labels on the x axis. In this example, the labels must be Jan - Dec.
String[] labels = {"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
String chart1URL = c.makeSession(request, "chart1");

// Create an image map for the chart
String imageMap1 = c.getHTMLImageMap("clickpie.jsp?year=" + selectedYear, "",
    "title='{xLabel}: US$ {value|0}M'");
%>
<html>
<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.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src="<%=response.encodeURL("getchart.jsp?"+chart1URL)%>" border="0" usemap="#map1">
<map name="map1">
<%=imageMap1%>
</map>
</body>
</html>

Clickable Pie Chart

In the previous Clickable Line Chart sample code, when a line is clicked, the "clickpie.jsp" will be invoked.

The code for "clickpie.jsp" 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.jsp" is very similar to "clickbar.jsp" and "clickline.jsp", it will not be explained further here.

[JSP Version] jspdemo/clickpie.jsp
<%@page import="ChartDirector.*" %>
<%
// Get the selected year and month
int selectedYear = Integer.parseInt(request.getParameter("year"));
int selectedMonth = Integer.parseInt(request.getParameter("x")) + 1;

//
// In real life, the data may come from a database based on selectedYear. In this
// example, we just use a random number generator.
//
int seed = (selectedYear - 1992) * (100 + 3 * selectedMonth);
RanTable rantable = new RanTable(seed, 1, 4);
rantable.setCol(0, seed * 0.003, seed * 0.017);

double[] data = rantable.getCol(0);

// The labels for the pie chart
String[] labels = {"Services", "Hardware", "Software", "Others"};

// Create a PieChart object of size 600 x 240 pixels
PieChart c = new 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.
TextBox t = c.setLabelStyle("Arial Bold Italic", 10);
t.setBackground(Chart.SameAsMainColor, Chart.Transparent, Chart.glassEffect(
    Chart.ReducedGlare));
t.setRoundedCorners();

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

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

// Create the image and save it in a temporary location
String chart1URL = c.makeSession(request, "chart1");

// Create an image map for the chart
String imageMap1 = c.getHTMLImageMap("piestub.jsp", "",
    "title='{label}:US$ {value|2}M'");
%>
<html>
<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.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<img src="<%=response.encodeURL("getchart.jsp?"+chart1URL)%>" border="0" usemap="#map1">
<map name="map1">
<%=imageMap1%>
</map>
</body>
</html>

Clickable Pie Chart Handler

In the previous Clickable Pie Chart sample code, when a sector is clicked, "piestub.jsp" will be invoked. Its code is listed below. In this example, it simply displays some data about the sector clicked.

[JSP Version] jspdemo/piestub.jsp
<html>
<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:20px">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">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 : <%=request.getParameter("sector")%></li>
    <li>Sector Name : <%=request.getParameter("label")%></li>
    <li>Sector Value : <%=request.getParameter("value")%></li>
    <li>Sector Percentage : <%=request.getParameter("percent")%>%</li>
</ul>
</div>
</body>
</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.

[JSP Version] jspdemo/jsclick.jsp
<%@page import="ChartDirector.*" %>
<%
//
// For demo purpose, we use hard coded data. In real life, the following data could
// come from a database.
//
double[] revenue = {4500, 5600, 6300, 8000, 12000, 14000, 16000, 20000, 24000, 28000}
    ;
double[] grossMargin = {62, 65, 63, 60, 55, 56, 57, 53, 52, 50};
double[] backLog = {563, 683, 788, 941, 1334, 1522, 1644, 1905, 2222, 2544};
String[] labels = {"1996", "1997", "1998", "1999", "2000", "2001", "2002", "2003",
    "2004", "2005"};

// Create a XYChart object of size 600 x 360 pixels
XYChart c = new 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.
BarLayer layer = c.addBarLayer3(revenue);

// Set cylinder bar shape
layer.setBarShape(Chart.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(Chart.Transparent);
c.yAxis().setColors(Chart.Transparent);
c.yAxis2().setColors(Chart.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
String chart1URL = c.makeSession(request, "chart1");

// Client side Javascript to show detail information "onmouseover"
String showText =
    "onmouseover='showInfo(\"{xLabel}\", {value}, {field0}, {field1});' ";

// Client side Javascript to hide detail information "onmouseout"
String hideText = "onmouseout='showInfo(null);' ";

// "title" attribute to show tool tip
String toolTip = "title='{xLabel}: US$ {value|0}M'";

// Create an image map for the chart
String imageMap1 = c.getHTMLImageMap("xystub.jsp", "", showText + hideText + toolTip)
    ;
%>
<html>
<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.jsp?file=<%=request.getServletPath()%>'>View Source Code</a>
</div>
<img src="<%=response.encodeURL("getchart.jsp?"+chart1URL)%>" border="0" usemap="#map1">
<map name="map1">
<%=imageMap1%>
</map>
<div id="detailInfo" style="margin-left:60px"></div>
</body>
</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"
String showText =
    "onmouseover='showInfo(\"{xLabel}\", {value}, {field0}, {field1});' ";

//Client side Javascript to hide detail information "onmouseout"
String hideText = "onmouseout='showInfo(null);' ";

//"title" attribute to show tool tip
String toolTip = "title='{xLabel}: USD {value|0}M'";

//Create an image map for the chart
String imageMap = c.getHTMLImageMap("xystub.jsp", "", 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.jsp" as the handler.

For demo purpose, "xystub.jsp" simply displays information on what is clicked. It's source code is as follows.

[JSP Version] jspdemo/xystub.jsp
<html>
<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:20px">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">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 : <%=request.getParameter("dataSetName")%></li>
    <li>X Position : <%=request.getParameter("x")%></li>
    <li>X Label : <%=request.getParameter("xLabel")%></li>
    <li>Data Value : <%=request.getParameter("value")%></li>
</ul>
</div>
</body>
</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.

[JSP Version] jspdemo/customclick.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the line chart
double[] data0 = {50, 55, 47, 36, 42, 49, 63, 62, 73, 59, 56, 50, 64, 60, 67, 67, 58,
    59, 73, 77, 84, 82, 80, 84};
double[] data1 = {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
String[] labels = {"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
XYChart c = new 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 legendBox = c.addLegend(55, 58, false, "Arial Bold", 9);
legendBox.setBackground(Chart.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.
ChartDirector.TextBox title = c.addTitle("Monthly Revenue for Year 2000/2001",
    "Times New Roman Bold Italic", 15, 0xffffff);
title.setBackground(0x0000cc, 0x000000, Chart.glassEffect(Chart.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 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
ChartDirector.TextBox copyRight = c.addText(575, 295,
    "(c) Copyright Space Travel Ltd", "Arial Bold");
copyRight.setAlignment(Chart.BottomRight);

// Add a line layer to the chart
LineLayer 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
String chart1URL = c.makeSession(request, "chart1");

// Create an image map for the chart
String chartImageMap = c.getHTMLImageMap("xystub.jsp", "",
    "title='{dataSetName} @ {xLabel} = USD {value|0} millions'");

// Create an image map for the legend box
String 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.)
String titleCoor = title.getImageCoor();
String markCoor = mark.getImageCoor();
String copyRightCoor = copyRight.getImageCoor();
%>
<html>
<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.jsp?file=<%=request.getServletPath()%>'>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="<%=response.encodeURL("getchart.jsp?"+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>
</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.jsp" as the handler:

String chartImageMap = c.getHTMLImageMap("xystub.jsp", "",
    "title='{dataSetName} @ {xLabel} = USD {value|0} millions'");

For demo purpose, "xystub.jsp" simply displays information on what is clicked. It's source code is as follows.

[JSP Version] jspdemo/xystub.jsp
<html>
<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:20px">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">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 : <%=request.getParameter("dataSetName")%></li>
    <li>X Position : <%=request.getParameter("x")%></li>
    <li>X Label : <%=request.getParameter("xLabel")%></li>
    <li>Data Value : <%=request.getParameter("value")%></li>
</ul>
</div>
</body>
</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.

String 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:

String titleCoor = title.getImageCoor();
String markCoor = mark.getImageCoor();
String 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.

[JSP Version] jspdemo/dbdemo3.jsp
<%@page import="ChartDirector.*" %>
<%
// SQL statement to get the revenue for the 12 years from 1990 to 2001
String SQL =
    "Select Sum(Software + Hardware + Services), Year(TimeStamp) From revenue " +
    "Where Year(TimeStamp) >= 1990 And Year(TimeStamp) <= 2001 Group By " +
    "Year(TimeStamp) Order By Year(TimeStamp)";

//
// Connect to database and read the query result into arrays
//

// In this example, we use an MS Access database through an ODBC driver.
String dbFile = new java.io.File(application.getRealPath(request.getServletPath())
    ).getParent() + "/sample.mdb";

// Connect to database and prepare the query
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
java.sql.Connection dbConn = java.sql.DriverManager.getConnection
    ("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=" + dbFile);
java.sql.PreparedStatement stmt = dbConn.prepareStatement(SQL);

// Execute the query and read the results into arrays
DBTable table = new DBTable(stmt.executeQuery());
double[] revenue = table.getCol(0);
double[] timestamp = table.getCol(1);

stmt.close();
dbConn.close();

//
// Now we have read data into arrays, we can draw the chart using ChartDirector
//

// Create a XYChart object of size 600 x 360 pixels
XYChart c = new 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
BarLayer layer = c.addBarLayer3(revenue);

// Use glass lighting effect with light direction from the left
layer.setBorderColor(Chart.Transparent, Chart.glassEffect(Chart.NormalGlare,
    Chart.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(Chart.Transparent);
c.yAxis().setColors(Chart.Transparent);
c.yAxis2().setColors(Chart.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
String chart1URL = c.makeSession(request, "chart1");

// Create an image map for the chart
String imageMap1 = c.getHTMLImageMap("dbdemo3a.jsp", "",
    "title='{xLabel}: US$ {value|0}M'");
%>
<html>
<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.jsp?file=<%=request.getServletPath()%>'>
    View source code
</a>
</div>

<img src="<%=response.encodeURL("getchart.jsp?"+chart1URL)%>" border="0" usemap="#map1">
<map name="map1">
<%=imageMap1%>
</map>

</body>
</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.jsp" as the handler.

When the user clicks on the bar chart, "dbdemo3a.jsp" 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.jsp" can determine which year the user has clicked. It can then query the database for the data in that year, and produces the bar chart for that year.

In this example, "dbdemo3a.jsp" will produce another clickable chart using "xystub.jsp" as the handler.

[JSP Version] jspdemo/dbdemo3a.jsp
<%@page import="ChartDirector.*" %>
<%
//
// Displays the monthly revenue for the selected year. The selected year should be
// passed in as a query parameter called "xLabel"
//
int selectedYear = (request.getParameter("xLabel") == null) ? 2001 :
    Integer.parseInt(request.getParameter("xLabel"));

// SQL statement to get the monthly revenues for the selected year.
String SQL =
    "Select Software, Hardware, Services From revenue Where Year(TimeStamp) = " +
    selectedYear + " Order By TimeStamp";

//
// Connect to database and read the query result into arrays
//

// In this example, we use an MS Access database through an ODBC driver.
String dbFile = new java.io.File(application.getRealPath(request.getServletPath())
    ).getParent() + "/sample.mdb";

// Connect to database and prepare the query
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
java.sql.Connection dbConn = java.sql.DriverManager.getConnection
    ("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=" + dbFile);
java.sql.PreparedStatement stmt = dbConn.prepareStatement(SQL);

// Execute the query and read the results into arrays
DBTable table = new DBTable(stmt.executeQuery());
double[] software = table.getCol(0);
double[] hardware = table.getCol(1);
double[] services = table.getCol(2);

stmt.close();
dbConn.close();

//
// Now we have read data into arrays, we can draw the chart using ChartDirector
//

// Create a XYChart object of size 600 x 360 pixels
XYChart c = new 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(Chart.Transparent);

// Add a line chart layer using the supplied data
LineLayer layer = c.addLineLayer2();
layer.addDataSet(software, 0xffaa00, "Software").setDataSymbol(Chart.CircleShape, 9);
layer.addDataSet(hardware, 0x00ff00, "Hardware").setDataSymbol(Chart.DiamondShape, 11
    );
layer.addDataSet(services, 0xff0000, "Services").setDataSymbol(Chart.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.
String[] labels = {"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(Chart.Transparent);
c.yAxis().setColors(Chart.Transparent);
c.yAxis2().setColors(Chart.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
String chart1URL = c.makeSession(request, "chart1");

// Create an image map for the chart
String imageMap1 = c.getHTMLImageMap("xystub.jsp", "",
    "title='{dataSetName} @ {xLabel} = USD {value|0}M'");
%>
<html>
<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.jsp?file=<%=request.getServletPath()%>'>
    View source code
</a>
</div>

<img src="<%=response.encodeURL("getchart.jsp?"+chart1URL)%>" border="0" usemap="#map1">
<map name="map1">
<%=imageMap1%>
</map>

</body>
</html>

For demo purpose, "xystub.jsp" simply displays information on what is clicked. It's source code is as follows.

[JSP Version] jspdemo/xystub.jsp
<html>
<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:20px">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">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 : <%=request.getParameter("dataSetName")%></li>
    <li>X Position : <%=request.getParameter("x")%></li>
    <li>X Label : <%=request.getParameter("xLabel")%></li>
    <li>Data Value : <%=request.getParameter("value")%></li>
</ul>
</div>
</body>
</html>


Using Multiple Click Handlers

Using Multiple Click Handlers

In JSP, 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.jsp" as the handler, no matter which sector is clicked, "piestub.jsp" 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).


Programmable Track Cursor

Programmable Track Cursor

This section describes ChartDirector's Programmable Track Cursor features.

For Windows Applications

Programmable Track Cursor (Windows)
Description of ChartDirector's Programmable Track Cursor features for Windows applications.

Track Line with Legend (Windows)
Demonstrates a track cursor programmed as a vertical sweep line that snaps to the x data value nearest to the mouse cursor, with dots showing the data points at the x position and dynamically updated legend entries showing their values.

Track Line with Data Labels (Windows)
Demonstrates a track cursor programmed as a vertical sweep line that snaps to the x data value nearest to the mouse cursor, with a tracking label on the x-axis showing the x value. There are also dots showing the data points at the x position and labels beside the dots showing their values.

Track Line with Axis Labels (Windows)
Demonstrates a track cursor with dots showing the data points at the nearest x data value from the mouse cursor, with lines connecting the dots to the x-axis and y-axis and axis labels showing their values.

Track Box with Legend (Windows)
Demonstrates a track cursor implemented as a rectangle enclosing the x data slot that contains the mouse cursor, with a floating legend box following the mouse cursor and showing the data values in the slot.

Finance Chart Track Line (Windows)
Demonstrates a track cursor for a finance chart, implemented as a vertical sweep line that snaps to the trading session nearest to the mouse cursor, with dynamically updated legend entries that show the price, volume and other technical indicators at that trading session.

Crosshair with Axis Labels (Windows)
Demonstrates a track cursor programmed as a crosshair cursor with axis labels.

For Web Applications

Programmable Track Cursor (Web)
Description of ChartDirector's Programmable Track Cursor features for web applications.

Track Line with Legend (Web)
Demonstrates a track cursor programmed as a vertical sweep line that snaps to the x data value nearest to the mouse cursor, with dots showing the data points at the x position and dynamically updated legend entries showing their values.

Track Line with Data Labels (Web)
Demonstrates a track cursor programmed as a vertical sweep line that snaps to the x data value nearest to the mouse cursor, with a tracking label on the x-axis showing the x value. There are also dots showing the data points at the x position and labels beside the dots showing their values.

Track Line with Axis Labels (Web)
Demonstrates a track cursor with dots showing the data points at the nearest x data value from the mouse cursor, with lines connecting the dots to the x-axis and y-axis and axis labels showing their values.

Track Box with Legend (Web)
Demonstrates a track cursor implemented as a rectangle enclosing the x data slot that contains the mouse cursor, with a floating legend box following the mouse cursor and showing the data values in the slot.

Finance Chart Track Line (Web)
Demonstrates a track cursor for a finance chart, implemented as a vertical sweep line that snaps to the trading session nearest to the mouse cursor, with dynamically updated legend entries that show the price, volume and other technical indicators at that trading session.

Crosshair with Axis Labels (Web)
Demonstrates a track cursor programmed as a crosshair cursor with axis labels.


Programmable Track Cursor (Windows)

Programmable Track Cursor (Windows)

NOTE: This section describes Programmable Track Cursor for Windows applications only. For web applications, please refer to Programmable Track Cursor (Web).

Introduction

For desktop applications, ChartDirector Programmable Track Cursor is implemented by drawing the track cursor on a "dynamic layer" of the chart. For example, drawing a horizontal line and a vertical line will create a crosshair cursor. The drawing is typically performed in a TrackCursorListener.mouseMovedPlotArea event handler so that the track cursor follows the mouse cursor. It is also possible to draw the track cursor at other times. For example, one may program the track cursor so that it is movable by arrow keys. In a realtime chart, the track cursor can be programmed to sweep through the chart as new data points are added.

MouseMovePlotArea Event

By far the most common usage of track cursor is when the mouse is moving over the plot area of an XYChart. The TrackCursorListener.mouseMovedPlotArea event , which occurs when the mouse moves over the plot area, is specially designed to facilitate track cursor implementation.

A special feature of MouseMovePlotArea is that it occurs even if the mouse is slightly outside the plot area, in which case ChartViewer.getPlotAreaMouseX and ChartViewer.getPlotAreaMouseY will report as if the mouse is still on the edge of the plot area. This feature allows the user to easily position the track cursor on the edge of the plot area, at which the latest data points are often located. The margin around the plot area that would still trigger MouseMovePlotArea is configurable using ChartViewer.setPlotAreaMouseMargin.

Dynamic Layer

The "dynamic layer" can be imagined as a special layer on top of the chart for drawing updatable contents. The BaseChart.initDynamicLayer method creates the dynamic layer, or clears the dynamic layer if it has already been created. This method returns a DrawArea object for drawing lines, shapes and text on the dynamic layer.

In typical usage, the track cursor drawing code would use initDynamicLayer to get the DrawArea object for the dynamic layer, and use the DrawArea object to draw the track cursor. After the drawing is completed, ChartViewer.updateDisplay should be used to commit the drawing to the display. If the track cursor drawing code is called from the TrackCursorListener.mouseMovedPlotArea event handler, the crosshair will appear to follow the mouse.

In some track cursor style, the track cursor should be removed when the mouse leaves the plot area. One way to perform this is to use BaseChart.removeDynamicLayer in the TrackCursorListener.mouseExitedPlotArea event handler to remove the dynamic layer. A more convenient method is to use ChartViewer.removeDynamicLayer to automatically remove the dynamic layer when the mouse leaves the plot area, which avoids the need to set up an extra event handler.

Snapping to the Nearest X Data Position

Very often, the track cursor is not drawn exactly at the mouse cursor position, but is drawn at the data point position nearest to the mouse cursor in the x direction. ChartDirector includes a method XYChart.getNearestXValue, which will search all data in the chart to get the x data value nearest to a given point. This value can then be used to obtain the x pixel coordinate (using XYChart.getXCoor) for drawing the track cursor. It can also be used to look up the data points (using Layer.getXIndexOf) so as to draw dots that track the data points, generate dynamic data labels, axis labels or legend entries.

Sample Track Cursors

ChartDirector includes a number of sample drawing routines in its sample code as follows:

Sample Code | Description
Track Line with Legend (Windows) | Demonstrates a track cursor that consists of a vertical line snapped to the nearest x data position. There are dots to highlight the nearest data points, and a dynamically updated legend showing their values.
Track Line with Data Labels (Windows) | Demonstrates a track cursor that consists of a vertical line snapped to the nearest x data position with a floating x-axis label. There are also dots to highlight the nearest data points, with labels beside them displaying their values.
Track Line with Axis Labels (Windows) | Demonstrates a track cursor that uses horizontal and vertical lines to connect the nearest data points to the x-axis and y-axis, with floating axis labels showing their values.
Track Box with Legend (Windows) | Demonstrates a track cursor that consists of a rectangle enclosing the slot corresponding to the nearest x-axis label. A floating legend box that moves with the mouse cursor is used to display the data values in that slot.
Crosshair with Axis Labels (Windows) | Demonstrates a track cursor that consists of a vertical line and a horizontal line at the mouse cursor position, thereby forming a crosshair. Floating axis labels are used to display the cursor position.
Finance Chart Track Line (Windows) | This is similar to Track Line with Legend (Windows), but is modified to apply to the FinanceChart object.
Zooming and Scrolling with Track Line (1) (Windows) | Demonstrates how to apply track cursors to a Zoomable and Scrollable chart. The track cursor drawing code is the same as that in Track Line with Legend (Windows).
Realtime Chart with Track Line (Windows) | Demonstrates how to apply track cursors to a Realtime chart. The track cursor drawing code is the same as that in Track Line with Legend (Windows).

Note that the above are only examples demonstrating the ChartDirector features for drawing track cursors. You may reuse them, or modify them for your own needs. You may also develop your own track cursor drawing code to implement the track cursor behaviour you want.


Track Line with Legend (Windows)

Track Line with Legend (Windows)

NOTE: This section describes Track Line with Legend for Windows applications only. For web applications, please refer to Track Line with Legend (Web).

This sample program demonstrates a track cursor programmed with the following features:

  • A vertical line that follows the mouse cursor on the plot area and snaps to the nearest x data value.

  • Small dots that shows the data points at the nearest x data value.

  • Dynamically updated legend entries that shows the value of the data points at the nearest x data value.

The code first draws the chart, and sets the track cursor to the right side of the plot area. This ensures the chart initially has a legend that reflects the latest data values. In the TrackCursorListener.mouseMovedPlotArea event handler, the track cursor is updated to reflect the mouse position.

The trackLineLegend method is the routine that draws the track cursor. Its key elements are:

  • To draw dynamic contents on the chart, the code obtains the DrawArea object for drawing on the dynamic layer of the chart using BaseChart.initDynamicLayer.

  • The nearest x data value is obtained using XYChart.getNearestXValue.

  • A vertical line is drawn at the nearest x data value using DrawArea.vline.

  • The code then iterates through all data sets in all layers to find all the data points at the nearest x data value. For each of these points, it formats a legend entry for the point, which consists of the data set icon (obtained using DataSet.getLegendIcon), data set name (obtained using DataSet.getDataName), and data value (obtained using DataSet.getValue). The code also gets the point's y position using DataSet.getPosition, and draws a circular dot using DrawArea.circle.

  • Finally, the code combines all the legend entries and draws them at the top of the plot area using DrawArea.text.

Source Code Listing

[Java Version] javademo/tracklegend.java
import ChartDirector.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;

public class tracklegend extends JFrame implements DemoModule
{
    //
    // The main method to allow this demo to run as a standalone program.
    //
    public static void main(String args[])
    {
        tracklegend demo = new tracklegend();
        demo.setDefaultCloseOperation(EXIT_ON_CLOSE);
        demo.setupFrame();
        demo.setVisible(true);
    }

    //
    // Set up the JFrame
    //
    private void setupFrame()
    {
           // If the JFrame has a title, it has already been set up.
        if ((null != getTitle()) && !getTitle().equals(""))
            return;

        // Set JFrame title to name of this demo program
        setTitle(toString());
        setResizable(false);

        // Create the ChartViewer and add it to the JFrame
        ChartViewer viewer = new ChartViewer();
        getContentPane().add(viewer);

        // Add a movedMovedPlotArea event listener to draw the track cursor
        viewer.addTrackCursorListener(new TrackCursorAdapter() {
            public void mouseMovedPlotArea(MouseEvent e) {
                chartViewer1_MouseMovedPlotArea(e);
            }
        });

        // Draw the chart
        drawChart(viewer);

        // Layout the JFrame
        pack();
    }

    //
    // Main code for creating charts
    //
    public void drawChart(ChartViewer viewer)
    {
        // Data for the chart as 3 random data series
        RanSeries r = new RanSeries(127);
        double[] data0 = r.getSeries(100, 100, -15, 15);
        double[] data1 = r.getSeries(100, 150, -15, 15);
        double[] data2 = r.getSeries(100, 200, -15, 15);
        Date[] timeStamps = r.getDateSeries(100, new GregorianCalendar(2011, 0, 1).getTime(), 86400);

        // Create a XYChart object of size 640 x 400 pixels
        XYChart c = new XYChart(640, 400);

        // Add a title to the chart using 18 pts Times New Roman Bold Italic font
        c.addTitle("    Product Line Global Revenue", "Times New Roman Bold Italic", 18);

        // Set the plotarea at (50, 55) with width 70 pixels less than chart width, and height 90 pixels less
        // than chart height. Use a vertical gradient from light blue (f0f6ff) to sky blue (a0c0ff) as
        // background. Set border to transparent and grid lines to white (ffffff).
        c.setPlotArea(50, 55, c.getWidth() - 70, c.getHeight() - 90, c.linearGradientColor(0, 55, 0,
            c.getHeight() - 35, 0xf0f6ff, 0xa0c0ff), -1, Chart.Transparent, 0xffffff, 0xffffff);

        // Set legend icon style to use line style icon, sized for 8pt font
        c.getLegend().setLineStyleKey();
        c.getLegend().setFontSize(8);

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

        // Set the axis stem to transparent
        c.xAxis().setColors(Chart.Transparent);
        c.yAxis().setColors(Chart.Transparent);

        // Configure x-axis label format
        c.xAxis().setMultiFormat(Chart.StartOfYearFilter(), "{value|mm/yyyy} ", Chart.StartOfMonthFilter(),
            "{value|mm}");

        // Add axis title using 10pts Arial Bold Italic font
        c.yAxis().setTitle("USD millions", "Arial Bold Italic", 10);

        // Add a line layer to the chart using a line width of 2 pixels.
        LineLayer layer = c.addLineLayer2();
        layer.setLineWidth(2);

        // Add 3 data series to the line layer
        layer.setXData(timeStamps);
        layer.addDataSet(data0, 0xff3333, "Alpha");
        layer.addDataSet(data1, 0x008800, "Beta");
        layer.addDataSet(data2, 0x3333cc, "Gamma");

        // Include track line with legend for the latest data values
        trackLineLegend(c, c.getPlotArea().getRightX());

        // Assign the chart to the ChartViewer
        viewer.setChart(c);
    }

    //
    // Draw track cursor when mouse is moving over plotarea
    //
    private void chartViewer1_MouseMovedPlotArea(MouseEvent e)
    {
        ChartViewer viewer = (ChartViewer)e.getSource();
        trackLineLegend((XYChart)viewer.getChart(), viewer.getPlotAreaMouseX());
        viewer.updateDisplay();
    }

    //
    // Draw the track line with legend
    //
    private void trackLineLegend(XYChart c, int mouseX)
    {
        // Clear the current dynamic layer and get the DrawArea object to draw on it.
        DrawArea d = c.initDynamicLayer();

        // The plot area object
        PlotArea plotArea = c.getPlotArea();

        // Get the data x-value that is nearest to the mouse, and find its pixel coordinate.
        double xValue = c.getNearestXValue(mouseX);
        int xCoor = c.getXCoor(xValue);

        // Draw a vertical track line at the x-position
        d.vline(plotArea.getTopY(), plotArea.getBottomY(), xCoor, d.dashLineColor(0x000000, 0x0101));

        // Container to hold the legend entries
        ArrayList legendEntries = new ArrayList();

        // Iterate through all layers to build the legend array
        for (int i = 0; i < c.getLayerCount(); ++i) {
            Layer layer = c.getLayerByZ(i);

            // The data array index of the x-value
            int xIndex = layer.getXIndexOf(xValue);

            // Iterate through all the data sets in the layer
            for (int j = 0; j < layer.getDataSetCount(); ++j) {
                ChartDirector.DataSet dataSet = layer.getDataSetByZ(j);

                // We are only interested in visible data sets with names
                String dataName = dataSet.getDataName();
                int color = dataSet.getDataColor();
                if ((!(dataName == null || dataName.length() == 0)) && (color != Chart.Transparent)) {
                    // Build the legend entry, consist of the legend icon, name and data value.
                    double dataValue = dataSet.getValue(xIndex);
                    legendEntries.add("<*block*>" + dataSet.getLegendIcon() + " " + dataName + ": " + ((
                        dataValue == Chart.NoValue) ? "N/A" : c.formatValue(dataValue, "{value|P4}")) +
                        "<*/*>");

                    // Draw a track dot for data points within the plot area
                    int yCoor = c.getYCoor(dataSet.getPosition(xIndex), dataSet.getUseYAxis());
                    if ((yCoor >= plotArea.getTopY()) && (yCoor <= plotArea.getBottomY())) {
                        d.circle(xCoor, yCoor, 4, 4, color, color);
                    }
                }
            }
        }

        // Create the legend by joining the legend entries
        Collections.reverse(legendEntries);
        String legendText = "<*block,maxWidth=" + plotArea.getWidth() + "*><*block*><*font=Arial Bold*>[" +
            c.xAxis().getFormattedLabel(xValue, "mmm dd, yyyy") + "]<*/*>        " + Chart.stringJoin(
            legendEntries, "        ") + "<*/*>";

        // Display the legend on the top of the plot area
        TTFText t = d.text(legendText, "Arial", 8);
        t.draw(plotArea.getLeftX() + 5, plotArea.getTopY() - 3, 0x000000, Chart.BottomLeft);
    }

    //
    // Implementation of the DemoModule interface to allow this demo to run inside the
    // ChartDirectorDemo browser
    //

    // Name of demo program
    public String toString()
    {
        return "Track Line with Legend";
    }

    // Number of charts produced in this demo
    public int getNoOfCharts()
    {
        // This demo open its own frame instead of using the right pane of the ChartDirectorDemo
        // for display. We just set up the frame, then returns 0.
        setupFrame();
        setVisible(true);
        return 0;
    }

    // Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // do nothing, as the ChartDirectorDemo browser right pane is not used
    }
}


Track Line with Data Labels (Windows)

Track Line with Data Labels (Windows)

NOTE: This section describes Track Line with Data Labels for Windows applications only. For web applications, please refer to Track Line with Data Labels (Web).

This sample program demonstrates a track cursor programmed with the following features:

  • A vertical line that follows the mouse cursor on the plot area and snaps to the nearest x data value, with a label on the x-axis displaying that value.

  • Small dots that shows the data points at the nearest x data value.

  • Labels beside the small dots displaying the values of the data points.

The code first draws the chart. Then in the TrackCursorListener.mouseMovedPlotArea event handler, the track cursor is drawn to reflect the mouse position. The track cursor is configured to automatically hide itself when the mouse leaves the plot area.

The trackLineLabel method is the routine that draws the track cursor. Its key elements are:

  • To draw dynamic contents on the chart, the code obtains the DrawArea object for drawing on the dynamic layer of the chart using BaseChart.initDynamicLayer.

  • The nearest x data value is obtained using XYChart.getNearestXValue.

  • A vertical line is drawn at the nearest x data value using DrawArea.vline.

  • The x-axis label at the nearest x value is drawn using DrawArea.text.

  • The code then iterates through all data sets in all layers to find all the data points at the nearest x data value. For each of these points, it gets the point's y position using DataSet.getPosition, and draws a circular dot using DrawArea.circle. It also formats the point's data value (obtained using DataSet.getValue) and displays it next to the dot using DrawArea.text.

Source Code Listing

[Java Version] javademo/tracklabel.java
import ChartDirector.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;

public class tracklabel extends JFrame implements DemoModule
{
    //
    // The main method to allow this demo to run as a standalone program.
    //
    public static void main(String args[])
    {
        tracklabel demo = new tracklabel();
        demo.setDefaultCloseOperation(EXIT_ON_CLOSE);
        demo.setupFrame();
        demo.setVisible(true);
    }

    //
    // Set up the JFrame
    //
    private void setupFrame()
    {
           // If the JFrame has a title, it has already been set up.
        if ((null != getTitle()) && !getTitle().equals(""))
            return;

        // Set JFrame title to name of this demo program
        setTitle(toString());
        setResizable(false);

        // Create the ChartViewer and add it to the JFrame
        ChartViewer viewer = new ChartViewer();
        getContentPane().add(viewer);

        // Add a movedMovedPlotArea event listener to draw the track cursor
        viewer.addTrackCursorListener(new TrackCursorAdapter() {
            public void mouseMovedPlotArea(MouseEvent e) {
                chartViewer1_MouseMovedPlotArea(e);
            }
        });

        // Draw the chart
        drawChart(viewer);

        // Layout the JFrame
        pack();
    }

    //
    // Main code for creating charts
    //
    public void drawChart(ChartViewer viewer)
    {
        // Data for the chart as 3 random data series
        RanSeries r = new RanSeries(127);
        double[] data0 = r.getSeries(100, 100, -15, 15);
        double[] data1 = r.getSeries(100, 150, -15, 15);
        double[] data2 = r.getSeries(100, 200, -15, 15);
        Date[] timeStamps = r.getDateSeries(100, new GregorianCalendar(2011, 0, 1).getTime(), 86400);

        // Create a XYChart object of size 640 x 400 pixels
        XYChart c = new XYChart(640, 400);

        // Add a title to the chart using 18 pts Times New Roman Bold Italic font
        c.addTitle("    Product Line Global Revenue", "Times New Roman Bold Italic", 18);

        // Set the plotarea at (50, 55) with width 70 pixels less than chart width, and height 90 pixels less
        // than chart height. Use a vertical gradient from light blue (f0f6ff) to sky blue (a0c0ff) as
        // background. Set border to transparent and grid lines to white (ffffff).
        c.setPlotArea(50, 55, c.getWidth() - 70, c.getHeight() - 90, c.linearGradientColor(0, 55, 0,
            c.getHeight() - 35, 0xf0f6ff, 0xa0c0ff), -1, Chart.Transparent, 0xffffff, 0xffffff);

        // Add a legend box at (50, 25) using horizontal layout. Use 10pts Arial Bold as font. Set the
        // background and border color to Transparent.
        c.addLegend(50, 25, false, "Arial Bold", 10).setBackground(Chart.Transparent);

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

        // Set the axis stem to transparent
        c.xAxis().setColors(Chart.Transparent);
        c.yAxis().setColors(Chart.Transparent);

        // Configure x-axis label format
        c.xAxis().setMultiFormat(Chart.StartOfYearFilter(), "{value|mm/yyyy} ", Chart.StartOfMonthFilter(),
            "{value|mm}");

        // Add axis title using 10pts Arial Bold Italic font
        c.yAxis().setTitle("USD millions", "Arial Bold Italic", 10);

        // Add a line layer to the chart using a line width of 2 pixels.
        LineLayer layer = c.addLineLayer2();
        layer.setLineWidth(2);

        // Add 3 data series to the line layer
        layer.setXData(timeStamps);
        layer.addDataSet(data0, 0xff3333, "Alpha");
        layer.addDataSet(data1, 0x008800, "Beta");
        layer.addDataSet(data2, 0x3333cc, "Gamma");

        // Assign the chart to the ChartViewer
        viewer.setChart(c);
    }

    //
    // Draw track cursor when mouse is moving over plotarea
    //
    private void chartViewer1_MouseMovedPlotArea(MouseEvent e)
    {
        ChartViewer viewer = (ChartViewer)e.getSource();
        trackLineLabel((XYChart)viewer.getChart(), viewer.getPlotAreaMouseX());
        viewer.updateDisplay();

        // Hide the track cursor when the mouse leaves the plot area
        viewer.removeDynamicLayer("MouseExitedPlotArea");
    }

    //
    // Draw track line with data labels
    //
    private void trackLineLabel(XYChart c, int mouseX)
    {
        // Clear the current dynamic layer and get the DrawArea object to draw on it.
        DrawArea d = c.initDynamicLayer();

        // The plot area object
        PlotArea plotArea = c.getPlotArea();

        // Get the data x-value that is nearest to the mouse, and find its pixel coordinate.
        double xValue = c.getNearestXValue(mouseX);
        int xCoor = c.getXCoor(xValue);

        // Draw a vertical track line at the x-position
        d.vline(plotArea.getTopY(), plotArea.getBottomY(), xCoor, d.dashLineColor(0x000000, 0x0101));

        // Draw a label on the x-axis to show the track line position.
        String xlabel = "<*font,bgColor=000000*> " + c.xAxis().getFormattedLabel(xValue, "mmm dd, yyyy") +
            " <*/font*>";
        TTFText t = d.text(xlabel, "Arial Bold", 8);

        // Restrict the x-pixel position of the label to make sure it stays inside the chart image.
        int xLabelPos = Math.max(0, Math.min(xCoor - t.getWidth() / 2, c.getWidth() - t.getWidth()));
        t.draw(xLabelPos, plotArea.getBottomY() + 6, 0xffffff);

        // Iterate through all layers to draw the data labels
        for (int i = 0; i < c.getLayerCount(); ++i) {
            Layer layer = c.getLayerByZ(i);

            // The data array index of the x-value
            int xIndex = layer.getXIndexOf(xValue);

            // Iterate through all the data sets in the layer
            for (int j = 0; j < layer.getDataSetCount(); ++j) {
                ChartDirector.DataSet dataSet = layer.getDataSetByZ(j);

                // Get the color and position of the data label
                int color = dataSet.getDataColor();
                int yCoor = c.getYCoor(dataSet.getPosition(xIndex), dataSet.getUseYAxis());

                // Draw a track dot with a label next to it for visible data points in the plot area
                if ((yCoor >= plotArea.getTopY()) && (yCoor <= plotArea.getBottomY()) && (color !=
                    Chart.Transparent)) {

                    d.circle(xCoor, yCoor, 4, 4, color, color);

                    String label = "<*font,bgColor=" + Integer.toHexString(color) + "*> " + c.formatValue(
                        dataSet.getValue(xIndex), "{value|P4}") + " <*/font*>";
                    t = d.text(label, "Arial Bold", 8);

                    // Draw the label on the right side of the dot if the mouse is on the left side the chart,
                    // and vice versa. This ensures the label will not go outside the chart image.
                    if (xCoor <= (plotArea.getLeftX() + plotArea.getRightX()) / 2) {
                        t.draw(xCoor + 5, yCoor, 0xffffff, Chart.Left);
                    } else {
                        t.draw(xCoor - 5, yCoor, 0xffffff, Chart.Right);
                    }
                }
            }
        }
    }

    //
    // Implementation of the DemoModule interface to allow this demo to run inside the
    // ChartDirectorDemo browser
    //

    // Name of demo program
    public String toString()
    {
        return "Track Line with Data Labels";
    }

    // Number of charts produced in this demo
    public int getNoOfCharts()
    {
        // This demo open its own frame instead of using the right pane of the ChartDirectorDemo
        // for display. We just set up the frame, then returns 0.
        setupFrame();
        setVisible(true);
        return 0;
    }

    // Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // do nothing, as the ChartDirectorDemo browser right pane is not used
    }
}


Track Line with Axis Labels (Windows)

Track Line with Axis Labels (Windows)

NOTE: This section describes Track Line with Axis Labels for Windows applications only. For web applications, please refer to Track Line with Axis Labels (Web).

This sample program demonstrates a track cursor programmed with the following features:

  • Small dots that shows the data points at the nearest x data value from the mouse cursor.

  • A vertical line that connects the data points to the x-axis, with an x-axis label displaying the x value.

  • Horizontal lines that connect the data points to the y-axes, with y-axis labels displaying their values.

The code first draws the chart. Then in the TrackCursorListener.mouseMovedPlotArea event handler, the track cursor is drawn to reflect the mouse position. The track cursor is configured to automatically hide itself when the mouse leaves the plot area.

The trackLineAxis method is the routine that draws the track cursor. Its key elements are:

  • To draw dynamic contents on the chart, the code obtains the DrawArea object for drawing on the dynamic layer of the chart using BaseChart.initDynamicLayer.

  • The nearest x data value is obtained using XYChart.getNearestXValue.

  • The code iterates through all data sets in all layers to find the highest data point at the nearest x data value. It then draws a vertical line from that point to the x-axis using DrawArea.vline, and the corresponding x-axis label using DrawArea.text.

  • The code iterates through all data sets in all layers once more to find all the data points at the nearest x data value. For each of these points, it draws a horizontal line to connect the point to the y-axis using DrawArea.hline, draws the axis label using DrawArea.text, and draws a circular dot at the point using DrawArea.circle.

Source Code Listing

[Java Version] javademo/trackaxis.java
import ChartDirector.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;

public class trackaxis extends JFrame implements DemoModule
{
    //
    // The main method to allow this demo to run as a standalone program.
    //
    public static void main(String args[])
    {
        trackaxis demo = new trackaxis();
        demo.setDefaultCloseOperation(EXIT_ON_CLOSE);
        demo.setupFrame();
        demo.setVisible(true);
    }

    //
    // Set up the JFrame
    //
    private void setupFrame()
    {
           // If the JFrame has a title, it has already been set up.
        if ((null != getTitle()) && !getTitle().equals(""))
            return;

        // Set JFrame title to name of this demo program
        setTitle(toString());
        setResizable(false);

        // Create the ChartViewer and add it to the JFrame
        ChartViewer viewer = new ChartViewer();
        getContentPane().add(viewer);

        // Add a movedMovedPlotArea event listener to draw the track cursor
        viewer.addTrackCursorListener(new TrackCursorAdapter() {
            public void mouseMovedPlotArea(MouseEvent e) {
                chartViewer1_MouseMovedPlotArea(e);
            }
        });

        // Draw the chart
        drawChart(viewer);

        // Layout the JFrame
        pack();
    }

    //
    // Main code for creating charts
    //
    public void drawChart(ChartViewer viewer)
    {
        // Data for the chart as 2 random data series
        RanSeries r = new RanSeries(127);
        double[] data0 = r.getSeries(180, 10, -1.5, 1.5);
        double[] data1 = r.getSeries(180, 150, -15, 15);
        Date[] timeStamps = r.getDateSeries(180, new GregorianCalendar(2011, 0, 1).getTime(), 86400);

        // Create a XYChart object of size 670 x 400 pixels
        XYChart c = new XYChart(670, 400);

        // Add a title to the chart using 18 pts Times New Roman Bold Italic font
        c.addTitle("Plasma Stabilizer Energy Usage", "Times New Roman Bold Italic", 18);

        // Set the plotarea at (50, 55) with width 100 pixels less than chart width, and height 90 pixels less
        // than chart height. Use a vertical gradient from light blue (f0f6ff) to sky blue (a0c0ff) as
        // background. Set border to transparent and grid lines to white (ffffff).
        c.setPlotArea(50, 55, c.getWidth() - 100, c.getHeight() - 90, c.linearGradientColor(0, 55, 0,
            c.getHeight() - 35, 0xf0f6ff, 0xa0c0ff), -1, Chart.Transparent, 0xffffff, 0xffffff);

        // Add a legend box at (50, 25) using horizontal layout. Use 10pts Arial Bold as font. Set the
        // background and border color to Transparent.
        c.addLegend(50, 25, false, "Arial Bold", 10).setBackground(Chart.Transparent);

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

        // Set the axis stem to transparent
        c.xAxis().setColors(Chart.Transparent);
        c.yAxis().setColors(Chart.Transparent);
        c.yAxis2().setColors(Chart.Transparent);

        // Configure x-axis label format
        c.xAxis().setMultiFormat(Chart.StartOfYearFilter(), "{value|mm/yyyy} ", Chart.StartOfMonthFilter(),
            "{value|mm}");

        // Add axis title using 10pts Arial Bold Italic font
        c.yAxis().setTitle("Power Usage (Watt)", "Arial Bold Italic", 10);
        c.yAxis2().setTitle("Effective Load (kg)", "Arial Bold Italic", 10);

        // Add a line layer to the chart using a line width of 2 pixels.
        LineLayer layer = c.addLineLayer2();
        layer.setLineWidth(2);

        // Add 2 data series to the line layer
        layer.setXData(timeStamps);
        layer.addDataSet(data0, 0xcc0000, "Power Usage");
        layer.addDataSet(data1, 0x008800, "Effective Load").setUseYAxis2();

        // Assign the chart to the ChartViewer
        viewer.setChart(c);
    }

    //
    // Draw track cursor when mouse is moving over plotarea
    //
    private void chartViewer1_MouseMovedPlotArea(MouseEvent e)
    {
        ChartViewer viewer = (ChartViewer)e.getSource();
        trackLineAxis((XYChart)viewer.getChart(), viewer.getPlotAreaMouseX());
        viewer.updateDisplay();

        // Hide the track cursor when the mouse leaves the plot area
        viewer.removeDynamicLayer("MouseExitedPlotArea");
    }

    //
    // Draw track line with axis labels
    //
    private void trackLineAxis(XYChart c, int mouseX)
    {
        // Clear the current dynamic layer and get the DrawArea object to draw on it.
        DrawArea d = c.initDynamicLayer();

        // The plot area object
        PlotArea plotArea = c.getPlotArea();

        // Get the data x-value that is nearest to the mouse, and find its pixel coordinate.
        double xValue = c.getNearestXValue(mouseX);
        int xCoor = c.getXCoor(xValue);

        // The vertical track line is drawn up to the highest data point (the point with smallest
        // y-coordinate). We need to iterate all datasets in all layers to determine where it is.
        int minY = plotArea.getBottomY();

        // Iterate through all layers to find the highest data point
        for (int i = 0; i < c.getLayerCount(); ++i) {
            Layer layer = c.getLayerByZ(i);

            // The data array index of the x-value
            int xIndex = layer.getXIndexOf(xValue);

            // Iterate through all the data sets in the layer
            for (int j = 0; j < layer.getDataSetCount(); ++j) {
                ChartDirector.DataSet dataSet = layer.getDataSetByZ(j);

                double dataPoint = dataSet.getPosition(xIndex);
                if ((dataPoint != Chart.NoValue) && (dataSet.getDataColor() != Chart.Transparent)) {
                    minY = Math.min(minY, c.getYCoor(dataPoint, dataSet.getUseYAxis()));
                }
            }
        }

        // Draw a vertical track line at the x-position up to the highest data point.
        d.vline(Math.max(minY, plotArea.getTopY()), plotArea.getBottomY() + 6, xCoor, d.dashLineColor(
            0x000000, 0x0101));

        // Draw a label on the x-axis to show the track line position
        d.text("<*font,bgColor=000000*> " + c.xAxis().getFormattedLabel(xValue, "mmm dd, yyyy") +
            " <*/font*>", "Arial Bold", 8).draw(xCoor, plotArea.getBottomY() + 6, 0xffffff, Chart.Top);

        // Iterate through all layers to build the legend array
        for (int i = 0; i < c.getLayerCount(); ++i) {
            Layer layer = c.getLayerByZ(i);

            // The data array index of the x-value
            int xIndex = layer.getXIndexOf(xValue);

            // Iterate through all the data sets in the layer
            for (int j = 0; j < layer.getDataSetCount(); ++j) {
                ChartDirector.DataSet dataSet = layer.getDataSetByZ(j);

                // The positional value, axis binding, pixel coordinate and color of the data point.
                double dataPoint = dataSet.getPosition(xIndex);
                Axis yAxis = dataSet.getUseYAxis();
                int yCoor = c.getYCoor(dataPoint, yAxis);
                int color = dataSet.getDataColor();

                // Draw the axis label only for visible data points of named data sets
                if ((dataPoint != Chart.NoValue) && (color != Chart.Transparent) && (yCoor >=
                    plotArea.getTopY()) && (yCoor <= plotArea.getBottomY())) {
                    // The axis label consists of 3 parts - a track dot for the data point, an axis label, and
                    // a line joining the track dot to the axis label.

                    // Draw the line first. The end point of the line at the axis label side depends on
                    // whether the label is at the left or right side of the axis (that is, on whether the
                    // axis is on the left or right side of the plot area).
                    int xPos = yAxis.getX() + ((yAxis.getAlignment() == Chart.Left) ? -4 : 4);
                    d.hline(xCoor, xPos, yCoor, d.dashLineColor(color, 0x0101));

                    // Draw the track dot
                    d.circle(xCoor, yCoor, 4, 4, color, color);

                    // Draw the axis label. If the axis is on the left side of the plot area, the labels
                    // should right aligned to the axis, and vice versa.
                    d.text("<*font,bgColor=" + Integer.toHexString(color) + "*> " + c.formatValue(dataPoint,
                        "{value|P4}") + " <*/font*>", "Arial Bold", 8).draw(xPos, yCoor, 0xffffff, ((
                        yAxis.getAlignment() == Chart.Left) ? Chart.Right : Chart.Left));
                }
            }
        }
    }

    //
    // Implementation of the DemoModule interface to allow this demo to run inside the
    // ChartDirectorDemo browser
    //

    // Name of demo program
    public String toString()
    {
        return "Track Line with Axis Labels";
    }

    // Number of charts produced in this demo
    public int getNoOfCharts()
    {
        // This demo open its own frame instead of using the right pane of the ChartDirectorDemo
        // for display. We just set up the frame, then returns 0.
        setupFrame();
        setVisible(true);
        return 0;
    }

    // Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // do nothing, as the ChartDirectorDemo browser right pane is not used
    }
}


Track Box with Legend (Windows)

Track Box with Legend (Windows)

NOTE: This section describes Track Box with Legend for Windows applications only. For web applications, please refer to Track Box with Legend (Web).

This sample program demonstrates a track cursor programmed with the following features:

  • A box that horizontally centers around the x data value nearest to the mouse cursor.

  • A floating legend box that moves with the mouse cursor, displaying the data values at the x data value nearest to the mouse cursor.

The code first draws the chart. Then in the TrackCursorListener.mouseMovedPlotArea event handler, the track cursor is drawn to reflect the mouse position. The track cursor is configured to automatically hide itself when the mouse leaves the plot area.

The trackBoxLegend method is the routine that draws the track cursor. Its key elements are:

  • To draw dynamic contents on the chart, the code obtains the DrawArea object for drawing on the dynamic layer of the chart using BaseChart.initDynamicLayer.

  • The nearest x data value is obtained using XYChart.getNearestXValue.

  • The code draws a rectangle that horizontally spans from (x - 0.5) to (x + 0.5) with DrawArea.rect. The +/- 0.5 offset is the suitable value to use for a label based x-axis (that is, for axis set up with Axis.setLabels or Axis.setLabels2). For this type of axis, the label distance is assumed to be 1 x-axis unit irrespective of what are the labels, so an offset of 0.5 refers to the middle position between two labels.

  • The code then iterates through all data sets in all layers to find all the data points at the nearest x data value. For each of these points, it formats a legend entry for the point, which consists of the data set icon (obtained using DataSet.getLegendIcon), data set name (obtained using DataSet.getDataName), and the data value (obtained using DataSet.getValue).

  • Finally, the code combines all the legend entries into a legend box and draws it near the mouse cursor using DrawArea.text.

Source Code Listing

[Java Version] javademo/trackbox.java
import ChartDirector.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;

public class trackbox extends JFrame implements DemoModule
{
    //
    // The main method to allow this demo to run as a standalone program.
    //
    public static void main(String args[])
    {
        trackbox demo = new trackbox();
        demo.setDefaultCloseOperation(EXIT_ON_CLOSE);
        demo.setupFrame();
        demo.setVisible(true);
    }

    //
    // Set up the JFrame
    //
    private void setupFrame()
    {
           // If the JFrame has a title, it has already been set up.
        if ((null != getTitle()) && !getTitle().equals(""))
            return;

        // Set JFrame title to name of this demo program
        setTitle(toString());
        setResizable(false);

        // Create the ChartViewer and add it to the JFrame
        ChartViewer viewer = new ChartViewer();
        getContentPane().add(viewer);

        // Add a movedMovedPlotArea event listener to draw the track cursor
        viewer.addTrackCursorListener(new TrackCursorAdapter() {
            public void mouseMovedPlotArea(MouseEvent e) {
                chartViewer1_MouseMovedPlotArea(e);
            }
        });

        // Draw the chart
        drawChart(viewer);

        // Layout the JFrame
        pack();
    }

    //
    // Main code for creating charts
    //
    public void drawChart(ChartViewer viewer)
    {
        // The data for the bar chart
        double[] data0 = {100, 125, 245, 147, 67};
        double[] data1 = {85, 156, 179, 211, 123};
        double[] data2 = {97, 87, 56, 267, 157};
        String[] labels = {"Mon", "Tue", "Wed", "Thur", "Fri"};

        // Create a XYChart object of size 540 x 375 pixels
        XYChart c = new 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(Chart.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
        BarLayer layer = c.addBarLayer2(Chart.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(Chart.Transparent, Chart.glassEffect(Chart.NormalGlare, Chart.Left));

        // Configure the bars within a group to touch each others (no gap)
        layer.setBarGap(0.2, Chart.TouchBar);

        // Assign the chart to the ChartViewer
        viewer.setChart(c);
    }

    //
    // Draw track cursor when mouse is moving over plotarea
    //
    private void chartViewer1_MouseMovedPlotArea(MouseEvent e)
    {
        ChartViewer viewer = (ChartViewer)e.getSource();
        trackBoxLegend((XYChart)viewer.getChart(), viewer.getPlotAreaMouseX(), viewer.getPlotAreaMouseY());
        viewer.updateDisplay();

        // Hide the track cursor when the mouse leaves the plot area
        viewer.removeDynamicLayer("MouseExitedPlotArea");
    }

    //
    // Draw the track box with legend
    //
    private void trackBoxLegend(XYChart c, int mouseX, int mouseY)
    {
        // Clear the current dynamic layer and get the DrawArea object to draw on it.
        DrawArea d = c.initDynamicLayer();

        // The plot area object
        PlotArea plotArea = c.getPlotArea();

        // Get the data x-value that is nearest to the mouse
        double xValue = c.getNearestXValue(mouseX);

        // Compute the position of the box. This example assumes a label based x-axis, in which the labeling
        // spacing is one x-axis unit. So the left and right sides of the box is 0.5 unit from the central
        // x-value.
        int boxLeft = c.getXCoor(xValue - 0.5);
        int boxRight = c.getXCoor(xValue + 0.5);
        int boxTop = plotArea.getTopY();
        int boxBottom = plotArea.getBottomY();

        // Draw the track box
        d.rect(boxLeft, boxTop, boxRight, boxBottom, 0x000000, Chart.Transparent);

        // Container to hold the legend entries
        ArrayList legendEntries = new ArrayList();

        // Iterate through all layers to build the legend array
        for (int i = 0; i < c.getLayerCount(); ++i) {
            Layer layer = c.getLayerByZ(i);

            // The data array index of the x-value
            int xIndex = layer.getXIndexOf(xValue);

            // Iterate through all the data sets in the layer
            for (int j = 0; j < layer.getDataSetCount(); ++j) {
                ChartDirector.DataSet dataSet = layer.getDataSetByZ(j);

                // Build the legend entry, consist of the legend icon, the name and the data value.
                double dataValue = dataSet.getValue(xIndex);
                if ((dataValue != Chart.NoValue) && (dataSet.getDataColor() != Chart.Transparent)) {
                    legendEntries.add(dataSet.getLegendIcon() + " " + dataSet.getDataName() + ": " +
                        c.formatValue(dataValue, "{value|P4}"));
                }
            }
        }

        // Create the legend by joining the legend entries
        if (legendEntries.size() > 0) {
            Collections.reverse(legendEntries);
            String legend = "<*block,bgColor=FFFFCC,edgeColor=000000,margin=5*><*font,underline=1*>" +
                c.xAxis().getFormattedLabel(xValue) + "<*/font*><*br*>" + Chart.stringJoin(legendEntries,
                "<*br*>") + "<*/*>";

            // Display the legend at the bottom-right side of the mouse cursor, and make sure the legend will
            // not go outside the chart image.
            TTFText t = d.text(legend, "Arial Bold", 8);
            t.draw(Math.min(mouseX + 12, c.getWidth() - t.getWidth()), Math.min(mouseY + 18, c.getHeight() -
                t.getHeight()), 0x000000, Chart.TopLeft);
        }
    }

    //
    // Implementation of the DemoModule interface to allow this demo to run inside the
    // ChartDirectorDemo browser
    //

    // Name of demo program
    public String toString()
    {
        return "Track Box with Legend";
    }

    // Number of charts produced in this demo
    public int getNoOfCharts()
    {
        // This demo open its own frame instead of using the right pane of the ChartDirectorDemo
        // for display. We just set up the frame, then returns 0.
        setupFrame();
        setVisible(true);
        return 0;
    }

    // Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // do nothing, as the ChartDirectorDemo browser right pane is not used
    }
}


Finance Chart Track Line (Windows)

Finance Chart Track Line (Windows)

NOTE: This section describes Finance Chart Track Line for Windows applications only. For web applications, please refer to Finance Chart Track Line (Web).

This sample program demonstrates a track cursor for a finance chart programmed with the following features:

  • A vertical line that follows the mouse cursor on the plot area and snaps to the nearest trading session.

  • Dynamically updated legend entries that show the price, volume and other technical indicators at the nearest trading session.

The code first draws the finance chart with the legend box set to transparent (so that the default legend box is not displayed). It then sets the track cursor to the right side of the plot area. This ensures the chart initially has a dynamic legend for the latest trading session. In the TrackCursorListener.mouseMovedPlotArea event handler, the track cursor is updated to reflect the mouse position.

The trackFinance method is the routine that draws the track cursor. Its key elements are:

  • To draw dynamic contents on the chart, the code obtains the DrawArea object for drawing on the dynamic layer of the chart using BaseChart.initDynamicLayer.

  • The nearest trading session is obtained from the first XYChart in the FinanceChart using XYChart.getNearestXValue.

  • The code iterates through all the XYChart objects in the FinanceChart. For each XYChart, the code iterates through all the layers to create dynamic legend entries. The FinanceChart creates default static legend entries for all indicators showing their latest values (even though the default static legend box is set to transparent in the chart). The code creates the dynamic legend entries by replacing the values in the static legend entries.

  • If a layer contains 4 data sets, the code assumes it is either a CandleStickLayer or HLOCLayer. It formats a legend entry consisting of the open, high, low, close values, as well as an up/down icon and the percentage change.

  • If a layer contains 2 data sets, the code assumes the layer is for a "band" or "channel" (such as Bollinger Band or Donchian Channel). The code formats a legend entry by replacing the values in the default legend entry (obtained using DataSet.getDataName).

  • If a layer contains 3 data sets, the code assumes the layer is for volume bars, with the 3 data sets representing volume bars of different colors for up, down and flat days. The code computes the volume by adding the values from the three data sets, and formats a legend entry by replacing the value in the default legend entry (obtained using DataSet.getDataName) with the computed value.

  • In all other cases, the code iterates the data sets. For each of them, it formats a legend by replacing the value in the default legend entry (obtained using DataSet.getDataName) with the value for the nearest trading session (obtained using DataSet.getValue).

  • Finally, the code combines all the legend entries into a legend box and draws it on top of the plot area using DrawArea.text. It also draws a vertical line at the nearest trading session using DrawArea.vline.

Source Code Listing

[Java Version] javademo/trackfinance.java
import ChartDirector.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;

public class trackfinance extends JFrame implements DemoModule
{
    //
    // The main method to allow this demo to run as a standalone program.
    //
    public static void main(String args[])
    {
        trackfinance demo = new trackfinance();
        demo.setDefaultCloseOperation(EXIT_ON_CLOSE);
        demo.setupFrame();
        demo.setVisible(true);
    }

    //
    // Set up the JFrame
    //
    private void setupFrame()
    {
           // If the JFrame has a title, it has already been set up.
        if ((null != getTitle()) && !getTitle().equals(""))
            return;

        // Set JFrame title to name of this demo program
        setTitle(toString());
        setResizable(false);

        // Create the ChartViewer and add it to the JFrame
        ChartViewer viewer = new ChartViewer();
        getContentPane().add(viewer);

        // Add a movedMovedPlotArea event listener to draw the track cursor
        viewer.addTrackCursorListener(new TrackCursorAdapter() {
            public void mouseMovedPlotArea(MouseEvent e) {
                chartViewer1_MouseMovedPlotArea(e);
            }
        });

        // Draw the chart
        drawChart(viewer);

        // Layout the JFrame
        pack();
    }

    //
    // Main code for creating charts
    //
    public void drawChart(ChartViewer viewer)
    {
        // Create a finance chart demo containing 100 days of data
        int noOfDays = 100;

        // To compute moving averages starting from the first day, we need to get extra data points before the
        // first day
        int 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 rantable = new RanTable(9, 6, noOfDays + extraDays);

        // Set the 1st col to be the timeStamp, starting from Sep 4, 2011, with each row representing one day,
        // and counting week days only (jump over Sat and Sun)
        rantable.setDateCol(0, new GregorianCalendar(2011, 8, 4).getTime(), 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
        double[] timeStamps = rantable.getCol(0);
        double[] highData = rantable.getCol(1);
        double[] lowData = rantable.getCol(2);
        double[] openData = rantable.getCol(3);
        double[] closeData = rantable.getCol(4);
        double[] volData = rantable.getCol(5);

        // Create a FinanceChart object of width 720 pixels
        FinanceChart c = new FinanceChart(720);

        // Add a title to the chart
        c.addTitle("Finance Chart Demonstration");

        // Disable default legend box, as we are using dynamic legend
        c.setLegendStyle("normal", 8, Chart.Transparent, Chart.Transparent);

        // Set the data into the finance chart object
        c.setData(timeStamps, highData, lowData, openData, closeData, volData, extraDays);

        // Add the main chart with 240 pixels in height
        c.addMainChart(240);

        // 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 candlestick symbols to the main chart, using green/red for up/down days
        c.addCandleStick(0x00ff00, 0xff0000);

        // 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 75 pixels volume bars sub-chart to the bottom of the main chart, using green/red/grey for
        // up/down/flat days
        c.addVolBars(75, 0x99ff99, 0xff9999, 0x808080);

        // Append a 14-days RSI indicator chart (75 pixels high) 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(75, 14, 0x800080, 20, 0xff0000, 0x0000ff);

        // Append a MACD(26, 12) indicator chart (75 pixels high) after the main chart, using 9 days for
        // computing divergence.
        c.addMACD(75, 26, 12, 9, 0x0000ff, 0xff00ff, 0x008000);

        // Include track line with legend for the latest data values
        trackFinance(c, ((XYChart)c.getChart(0)).getPlotArea().getRightX());

        // Assign the chart to the ChartViewer
        viewer.setChart(c);
    }

    //
    // Draw track cursor when mouse is moving over plotarea
    //
    private void chartViewer1_MouseMovedPlotArea(MouseEvent e)
    {
        ChartViewer viewer = (ChartViewer)e.getSource();
        trackFinance((MultiChart)viewer.getChart(), viewer.getPlotAreaMouseX());
        viewer.updateDisplay();
    }

    //
    // Draw finance chart track line with legend
    //
    private void trackFinance(MultiChart m, int mouseX)
    {
        // Clear the current dynamic layer and get the DrawArea object to draw on it.
        DrawArea d = m.initDynamicLayer();

        // It is possible for a FinanceChart to be empty, so we need to check for it.
        if (m.getChartCount() == 0) {
            return ;
        }

        // Get the data x-value that is nearest to the mouse
        int xValue = (int)(((XYChart)m.getChart(0)).getNearestXValue(mouseX));

        // Iterate the XY charts (main price chart and indicator charts) in the FinanceChart
        XYChart c = null;
        for (int i = 0; i < m.getChartCount(); ++i) {
            c = (XYChart)m.getChart(i);

            // Variables to hold the legend entries
            String ohlcLegend = "";
            ArrayList legendEntries = new ArrayList();

            // Iterate through all layers to find the highest data point
            for (int j = 0; j < c.getLayerCount(); ++j) {
                Layer layer = c.getLayerByZ(j);
                int xIndex = layer.getXIndexOf(xValue);
                int dataSetCount = layer.getDataSetCount();

                // In a FinanceChart, only layers showing OHLC data can have 4 data sets
                if (dataSetCount == 4) {
                    double highValue = layer.getDataSet(0).getValue(xIndex);
                    double lowValue = layer.getDataSet(1).getValue(xIndex);
                    double openValue = layer.getDataSet(2).getValue(xIndex);
                    double closeValue = layer.getDataSet(3).getValue(xIndex);

                    if (closeValue != Chart.NoValue) {
                        // Build the OHLC legend
                        ohlcLegend = "Open: " + c.formatValue(openValue, "{value|P4}") + ", High: " +
                            c.formatValue(highValue, "{value|P4}") + ", Low: " + c.formatValue(lowValue,
                            "{value|P4}") + ", Close: " + c.formatValue(closeValue, "{value|P4}");

                        // We also draw an upward or downward triangle for up and down days and the % change
                        double lastCloseValue = layer.getDataSet(3).getValue(xIndex - 1);
                        if (lastCloseValue != Chart.NoValue) {
                            double change = closeValue - lastCloseValue;
                            double percent = change * 100 / closeValue;
                            String symbol = ((change >= 0) ?
                                "<*font,color=008800*><*img=@triangle,width=8,color=008800*>" :
                                "<*font,color=CC0000*><*img=@invertedtriangle,width=8,color=CC0000*>");

                            ohlcLegend = ohlcLegend + "  " + symbol + " " + c.formatValue(change, "{value|P4}"
                                ) + " (" + c.formatValue(percent, "{value|2}") + "%)<*/font*>";
                        }

                        // Use a <*block*> to make sure the line does not wrap within the legend entry
                        ohlcLegend = "<*block*>" + ohlcLegend + "      <*/*>";
                    }
                } else {
                    // Iterate through all the data sets in the layer
                    for (int k = 0; k < layer.getDataSetCount(); ++k) {
                        ChartDirector.DataSet dataSet = layer.getDataSetByZ(k);

                        String name = dataSet.getDataName();
                        double value = dataSet.getValue(xIndex);
                        if ((!(name == null || name.length() == 0)) && (value != Chart.NoValue)) {

                            // In a FinanceChart, the data set name consists of the indicator name and its
                            // latest value. It is like "Vol: 123M" or "RSI (14): 55.34". As we are generating
                            // the values dynamically, we need to extract the indictor name out, and also the
                            // volume unit (if any).

                            // The unit character, if any, is the last character and must not be a digit.
                            String unitChar = name.substring(name.length() - 1);
                            if (unitChar.compareTo("0") >= 0 && unitChar.compareTo("9") <= 0) {
                                unitChar = "";
                            }

                            // The indicator name is the part of the name up to the colon character.
                            int delimiterPosition = name.indexOf(":");
                            if (delimiterPosition != -1) {
                                name = name.substring(0, delimiterPosition);
                            }

                            // In a FinanceChart, if there are two data sets, it must be representing a range.
                            if (dataSetCount == 2) {
                                // We show both values in the range in a single legend entry
                                value = layer.getDataSet(0).getValue(xIndex);
                                double value2 = layer.getDataSet(1).getValue(xIndex);
                                name = name + ": " + c.formatValue(Math.min(value, value2), "{value|P3}") +
                                    " - " + c.formatValue(Math.max(value, value2), "{value|P3}");
                            } else {
                                // In a FinanceChart, only the layer for volume bars has 3 data sets for
                                // up/down/flat days
                                if (dataSetCount == 3) {
                                    // The actual volume is the sum of the 3 data sets.
                                    value = layer.getDataSet(0).getValue(xIndex) + layer.getDataSet(1
                                        ).getValue(xIndex) + layer.getDataSet(2).getValue(xIndex);
                                }

                                // Create the legend entry
                                name = name + " : " + c.formatValue(value, "{value|P3}") + unitChar;
                            }

                            // Build the legend entry, consist of a colored square box and the name (with the
                            // data value in it).
                            legendEntries.add("<*block*><*img=@square,width=8,edgeColor=000000,color=" +
                                Integer.toHexString(dataSet.getDataColor()) + "*> " + name + "<*/*>");
                        }
                    }
                }
            }

            // Get the plot area position relative to the entire FinanceChart
            PlotArea plotArea = c.getPlotArea();
            int plotAreaLeftX = plotArea.getLeftX() + c.getAbsOffsetX();
            int plotAreaTopY = plotArea.getTopY() + c.getAbsOffsetY();

            // The legend is formed by concatenating the legend entries.
            Collections.reverse(legendEntries);
            String legendText = Chart.stringJoin(legendEntries, "      ");

            // Add the date and the ohlcLegend (if any) at the beginning of the legend
            legendText = "<*block,valign=top,maxWidth=" + (plotArea.getWidth() - 5) + "*><*font=Arial Bold*>["
                 + c.xAxis().getFormattedLabel(xValue, "mmm dd, yyyy") + "]<*/font*>      " + ohlcLegend +
                legendText;

            // Draw a vertical track line at the x-position
            d.vline(plotAreaTopY, plotAreaTopY + plotArea.getHeight(), c.getXCoor(xValue) + c.getAbsOffsetX(),
                d.dashLineColor(0x000000, 0x0101));

            // Display the legend on the top of the plot area
            TTFText t = d.text(legendText, "Arial", 8);
            t.draw(plotAreaLeftX + 5, plotAreaTopY + 3, 0x000000, Chart.TopLeft);
        }
    }

    //
    // Implementation of the DemoModule interface to allow this demo to run inside the
    // ChartDirectorDemo browser
    //

    // Name of demo program
    public String toString()
    {
        return "Finance Chart Track Line";
    }

    // Number of charts produced in this demo
    public int getNoOfCharts()
    {
        // This demo open its own frame instead of using the right pane of the ChartDirectorDemo
        // for display. We just set up the frame, then returns 0.
        setupFrame();
        setVisible(true);
        return 0;
    }

    // Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // do nothing, as the ChartDirectorDemo browser right pane is not used
    }
}


Crosshair with Axis Labels (Windows)

Crosshair with Axis Labels (Windows)

NOTE: This section describes Crosshair with Axis Labels for Windows applications only. For web applications, please refer to Crosshair with Axis Labels (Web).

This sample program demonstrates a track cursor programmed as a crosshair cursor with axis labels.

The code first draws the chart. Then in the TrackCursorListener.mouseMovedPlotArea event handler, the track cursor is drawn to reflect the mouse position. The track cursor is configured to automatically hide itself when the mouse leaves the plot area.

The crossHair method is the routine that draws the track cursor. Its key elements are:

  • To draw dynamic contents on the chart, the code obtains the DrawArea object for drawing on the dynamic layer of the chart using BaseChart.initDynamicLayer.

  • The code draws a vertical line (using DrawArea.vline) and a horizontal line (using DrawArea.hline) at the mouse cursor position. This creates the crosshair.

  • The code also draws x and y axis labels using DrawArea.text.

Source Code Listing

[Java Version] javademo/crosshair.java
import ChartDirector.*;
import javax.swing.*;
import java.awt.event.*;

public class crosshair extends JFrame implements DemoModule
{
    //
    // The main method to allow this demo to run as a standalone program.
    //
    public static void main(String args[])
    {
        crosshair demo = new crosshair();
        demo.setDefaultCloseOperation(EXIT_ON_CLOSE);
        demo.setupFrame();
        demo.setVisible(true);
    }

    //
    // Set up the JFrame
    //
    private void setupFrame()
    {
           // If the JFrame has a title, it has already been set up.
        if ((null != getTitle()) && !getTitle().equals(""))
            return;

        // Set JFrame title to name of this demo program
        setTitle(toString());
        setResizable(false);

        // Create the ChartViewer and add it to the JFrame
        ChartViewer viewer = new ChartViewer();
        getContentPane().add(viewer);

        // Add a movedMovedPlotArea event listener to draw the track cursor
        viewer.addTrackCursorListener(new TrackCursorAdapter() {
            public void mouseMovedPlotArea(MouseEvent e) {
                chartViewer1_MouseMovedPlotArea(e);
            }
        });

        // Draw the chart
        drawChart(viewer);

        // Layout the JFrame
        pack();
    }

    //
    // Main code for creating charts
    //
    public void drawChart(ChartViewer viewer)
    {
        // The XY data of the first data series
        double[] dataX = {50, 55, 37, 24, 42, 49, 63, 72, 83, 59};
        double[] dataY = {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 520 x 490 pixels
        XYChart c = new XYChart(520, 490);

        // Set the plotarea at (60, 40) and of size 450 x 400 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(60, 40, 450, 400, 0xffffff, -1, 0xc0c0c0, 0xc0c0c0, -1);

        // Add a title to the chart using 18 point Times Bold Itatic font.
        c.addTitle("      Chemical X Thermal Conductivity", "Times New Roman Bold Italic", 18);

        // Add titles to the axes using 12 pts Arial Bold Italic font
        c.yAxis().setTitle("Thermal Conductivity (W/K)", "Arial Bold Italic", 12);
        c.xAxis().setTitle("Concentration (g/liter)", "Arial Bold Italic", 12);

        // Set the axes line width to 3 pixels
        c.yAxis().setWidth(3);
        c.xAxis().setWidth(3);

        // Add a scatter layer using (dataX, dataY)
        ScatterLayer scatterLayer = c.addScatterLayer(dataX, dataY, "", Chart.GlassSphereShape, 13, 0xcc0000);

        // Tooltip for the scatter layer
        scatterLayer.setHTMLImageMap("", "", "title='Concentration: {x} g/liter, Conductivity: {value} W/K'");

        // Add a trend line layer for (dataX, dataY)
        TrendLayer trendLayer = c.addTrendLayer2(dataX, dataY, 0xcc0000);

        // 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 the trend layer
        trendLayer.setHTMLImageMap("", "", "title='Trend Line: y = {slope|P4} x + {intercept|P4}'");

        // Add a legend box at (60, 35) (top of the chart) with horizontal layout. Use 10 pts Arial Bold
        // Italic font. Set the background and border color to Transparent and use line style legend icons.
        LegendBox legendBox = c.addLegend(60, 35, false, "Arial Bold Italic", 9);
        legendBox.setBackground(Chart.Transparent);
        legendBox.setLineStyleKey(true);

        // Add entries to the legend box
        legendBox.addKey("95% Line Confidence", 0x806666ff);
        legendBox.addKey("95% Point Confidence", 0x8066ff66);
        legendBox.addKey(java.text.MessageFormat.format(
            "Trend Line: y = {0,number,#.####} x + {1,number,#.####}", new Object[]{new Double(
            trendLayer.getSlope()), new Double(trendLayer.getIntercept())}), 0xcc0000, 3);

        // Assign the chart to the ChartViewer
        viewer.setChart(c);

        // Include tool tip for the chart
        viewer.setImageMap(c.getHTMLImageMap(""));
    }

    //
    // Draw track cursor when mouse is moving over plotarea
    //
    private void chartViewer1_MouseMovedPlotArea(MouseEvent e)
    {
        ChartViewer viewer = (ChartViewer)e.getSource();
        crossHair((XYChart)viewer.getChart(), viewer.getPlotAreaMouseX(), viewer.getPlotAreaMouseY());
        viewer.updateDisplay();

        // Hide the track cursor when the mouse leaves the plot area
        viewer.removeDynamicLayer("MouseExitedPlotArea");
    }

    //
    // Draw cross hair cursor with axis labels
    //
    private void crossHair(XYChart c, int mouseX, int mouseY)
    {
        // Clear the current dynamic layer and get the DrawArea object to draw on it.
        DrawArea d = c.initDynamicLayer();

        // The plot area object
        PlotArea plotArea = c.getPlotArea();

        // Draw a vertical line and a horizontal line as the cross hair
        d.vline(plotArea.getTopY(), plotArea.getBottomY(), mouseX, d.dashLineColor(0x000000, 0x0101));
        d.hline(plotArea.getLeftX(), plotArea.getRightX(), mouseY, d.dashLineColor(0x000000, 0x0101));

        // Draw y-axis label
        String label = "<*block,bgColor=FFFFDD,margin=3,edgeColor=000000*>" + c.formatValue(c.getYValue(
            mouseY, c.yAxis()), "{value|P4}") + "<*/*>";
        TTFText t = d.text(label, "Arial Bold", 8);
        t.draw(plotArea.getLeftX() - 5, mouseY, 0x000000, Chart.Right);

        // Draw x-axis label
        label = "<*block,bgColor=FFFFDD,margin=3,edgeColor=000000*>" + c.formatValue(c.getXValue(mouseX),
            "{value|P4}") + "<*/*>";
        t = d.text(label, "Arial Bold", 8);
        t.draw(mouseX, plotArea.getBottomY() + 5, 0x000000, Chart.Top);
    }

    //
    // Implementation of the DemoModule interface to allow this demo to run inside the
    // ChartDirectorDemo browser
    //

    // Name of demo program
    public String toString()
    {
        return "Crosshair with Axis Labels";
    }

    // Number of charts produced in this demo
    public int getNoOfCharts()
    {
        // This demo open its own frame instead of using the right pane of the ChartDirectorDemo
        // for display. We just set up the frame, then returns 0.
        setupFrame();
        setVisible(true);
        return 0;
    }

    // Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // do nothing, as the ChartDirectorDemo browser right pane is not used
    }
}


Programmable Track Cursor (Web)

Programmable Track Cursor (Web)

NOTE: This section describes Programmable Track Cursor for web applications only. For Windows applications, please refer to Programmable Track Cursor (Windows).

Introduction

For web applications, ChartDirector Programmable Track Cursor is implemented by drawing the track cursor on the browser side with Javascript. For example, drawing a horizontal line and a vertical line will create a crosshair cursor. The drawing is typically performed in a JsChartViewer.MouseMovePlotArea event handler so that the track cursor follows the mouse cursor. It is also possible to draw the track cursor at other times. For example, one may program the track cursor so that it is movable by arrow keys. In a realtime chart, the track cursor can be programmed to sweep through the chart as new data points are added.

Javascript Chart Model

To draw track cursors on the browser side, certain chart configuration (such as the position and size of the plot area, the axis scale of all axes, the data values, etc) needs to be accessible on the browser side. In ChartDirector, this is achieved by using the Javascript Chart Model.

To set up the Javascript Chart Mode, BaseChart.getJsChartModel can be used on the server side to generate a data structure containing the chart configuration. The data structure can then be passed to the WebChartViewer using WebChartViewer.setChartModel, which will send it to the browser. On the browser side, the Javascript Chart Viewer will use the data structure to construct Javascript objects representing the chart. These objects can be accessed using JsChartViewer.getChart.

MouseMovePlotArea Event

By far the most common usage of track cursor is when the mouse is moving over the plot area of an XYChart. The JsChartViewer.MouseMovePlotArea event , which occurs when the mouse moves over the plot area, is specially designed to facilitate track cursor implementation.

A special feature of MouseMovePlotArea is that it occurs even if the mouse is slightly outside the plot area, in which case JsChartViewer.getPlotAreaMouseX and JsChartViewer.getPlotAreaMouseY will report as if the mouse is still on the edge of the plot area. This feature allows the user to easily position the track cursor on the edge of the plot area, at which the latest data points are often located. The margin around the plot area that would still trigger MouseMovePlotArea is configurable using JsChartViewer.setPlotAreaMouseMargin.

JsChartViewer.attachHandler can be used to attach a function as the MouseMovePlotArea event handler of a chart. This should be performed only after the chart is loaded. It is recommended that the code to attach the MouseMovePlotArea event handler be executed in the <body> or window onload event handler of the web page.

JsChartViewer Drawing Methods

To facilitate drawing track cursors, JsChartViewer includes a number of methods to draw lines, rectangles and text over the chart as follows.

Method | Description
JsChartViewer.drawHLine | Draws a horizontal line on the chart.
JsChartViewer.drawVLine | Draws a vertical line on the chart.
JsChartViewer.showCrossHair | Displays the crosshair cursor.
JsChartViewer.showTextBox | Draws a textbox on the chart.
JsChartViewer.hideObj | Hides one or more objects drawn by JsChartViewer.
JsChartViewer.setAutoHide | Hides one or more objects drawn by JsChartViewer when a certain event occurs.
JsChartViewer.removeAutoHide | Cancels the automatic action sets up by JsChartViewer.setAutoHide.
JsChartViewer.htmlRect | Generates HTML code that represents an inline color box.

Snapping to the Nearest X Data Position

Very often, the track cursor is not drawn exactly at the mouse cursor position, but is drawn at the data point position nearest to the mouse cursor in the x direction. ChartDirector includes a method JsXYChart.getNearestXValue, which will search all data in the chart to get the x data value nearest to a given point. This value can then be used to obtain the x pixel coordinate (using JsXYChart.getXCoor) for drawing the track cursor. It can also be used to look up the data points (using JsLayer.getXIndexOf) so as to draw dots that track the data points, generate dynamic data labels, axis labels or legend entries.

Files Required for Javascript Chart Viewer

To use the Javascript Chart Viewer, your web site would need to contain the following files, which should be in the same directory. In your web page, please include a <script> tag to load "cdjcv.js".

Filename | Description
cdjcv.js | The main Javascript library file.
wait.gif | Rotating clock wait symbol.
spacer.gif | A 1-pixel transparent image.
zoomin.cur | Zoom in cursor.
zoomin.cur | Zoom out cursor.
nozoom.cur | No zoom cursor.

Sample Track Cursors

ChartDirector includes a number of sample drawing routines in its sample code. You may reuse them, or modify them for your own needs. You may also develop your own track cursor drawing code to implement the track cursor behaviour you want.

Sample Code | Description
Track Line with Legend (Web) | Demonstrates a track cursor that consists of a vertical line snapped to the nearest x data position. There are dots to highlight the nearest data points, and a dynamically updated legend showing their values.
Track Line with Data Labels (Web) | Demonstrates a track cursor that consists of a vertical line snapped to the nearest x data position with a floating x-axis label. There are also dots to highlight the nearest data points, with labels beside them displaying their values.
Track Line with Axis Labels (Web) | Demonstrates a track cursor that uses horizontal and vertical lines to connect the nearest data points to the x-axis and y-axis, with floating axis labels showing their values.
Track Box with Legend (Web) | Demonstrates a track cursor that consists of a rectangle enclosing the slot corresponding to the nearest x-axis label. A floating legend box that moves with the mouse cursor is used to display the data values in that slot.
Crosshair with Axis Labels (Web) | Demonstrates a track cursor that consists of a vertical line and a horizontal line at the mouse cursor position, thereby forming a crosshair. Floating axis labels are used to display the cursor position.
Finance Chart Track Line (Web) | This is similar to Track Line with Legend (Web), but is modified to apply to the FinanceChart object.
Zooming and Scrolling with Track Line (Web) | Demonstrates how to apply track cursors to a Zoomable and Scrollable chart. The track cursor drawing code is the same as that in Track Line with Legend (Web).
Realtime Chart with Track Line (Web) | Demonstrates how to apply track cursors to a Realtime chart. The track cursor drawing code is the same as that in Track Line with Legend (Web).


Track Line with Legend (Web)

Track Line with Legend (Web)

NOTE: This section describes Track Line with Legend for web applications only. For Windows applications, please refer to Track Line with Legend (Windows).

This sample program demonstrates a track cursor programmed with the following features:

  • A vertical line that follows the mouse cursor on the plot area and snaps to the nearest x data value.

  • Small dots that shows the data points at the nearest x data value.

  • Dynamically updated legend entries that shows the value of the data points at the nearest x data value.

On the server side, the code draws the chart as usual, and outputs both the image and the Javascript Chart Model of the chart.

On the browser side, in the window onload event handler, Javascript is used to set up the JsChartViewer.MouseMovePlotArea event handler. The MouseMovePlotArea event handler calls trackLineLegend to draw the track cursor when the mouse moves on the plot area. The windows onload event handler also directly calls trackLineLegend to initialize the track cursor to the right side of the plot area. This is to ensure the chart initially has a legend that reflects the latest data values.

The trackLineLegend Javascript function is the routine that draws the track cursor. Its key elements are:

  • The code first uses JsChartViewer.hideObj to clear the previous track cursor, if any.

  • The nearest x data value is obtained using JsXYChart.getNearestXValue.

  • A vertical line is drawn at the nearest x data value using JsChartViewer.drawVLine.

  • The code then iterates through all data sets in all layers to find all the data points at the nearest x data value. For each of these points, it formats a legend entry for the point, which consists of a colored square as the icon (creating using JsChartViewer.htmlRect), the data set name (obtained using JsDataSet.getDataName), and data value (obtained using JsDataSet.getValue). The code also gets the point's y position using DataSet.getPosition, and draws a square dot using JsChartViewer.showTextBox and JsChartViewer.htmlRect.

  • Finally, the code combines all the legend entries and draws them at the top of the plot area using JsChartViewer.showTextBox.

Source Code Listing

[JSP Version] jspdemo/tracklegend.jsp
<%@page import="ChartDirector.*" %>
<%@page import="java.util.*" %>
<%
// Data for the chart as 3 random data series
RanSeries r = new RanSeries(127);
double[] data0 = r.getSeries(100, 100, -15, 15);
double[] data1 = r.getSeries(100, 150, -15, 15);
double[] data2 = r.getSeries(100, 200, -15, 15);
Date[] timeStamps = r.getDateSeries(100, new GregorianCalendar(2011, 0, 1).getTime(), 86400);

// Create a XYChart object of size 640 x 400 pixels
XYChart c = new XYChart(640, 400);

// Add a title to the chart using 18 pts Times New Roman Bold Italic font
c.addTitle("    Product Line Global Revenue", "Times New Roman Bold Italic", 18);

// Set the plotarea at (50, 55) with width 70 pixels less than chart width, and height 90 pixels
// less than chart height. Use a vertical gradient from light blue (f0f6ff) to sky blue (a0c0ff) as
// background. Set border to transparent and grid lines to white (ffffff).
c.setPlotArea(50, 55, c.getWidth() - 70, c.getHeight() - 90, c.linearGradientColor(0, 55, 0,
    c.getHeight() - 35, 0xf0f6ff, 0xa0c0ff), -1, Chart.Transparent, 0xffffff, 0xffffff);

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

// Set the axis stem to transparent
c.xAxis().setColors(Chart.Transparent);
c.yAxis().setColors(Chart.Transparent);

// Configure x-axis label format
c.xAxis().setMultiFormat(Chart.StartOfYearFilter(), "{value|mm/yyyy} ", Chart.StartOfMonthFilter(),
    "{value|mm}");

// Add axis title using 10pts Arial Bold Italic font
c.yAxis().setTitle("USD millions", "Arial Bold Italic", 10);

// Add a line layer to the chart using a line width of 2 pixels.
LineLayer layer = c.addLineLayer2();
layer.setLineWidth(2);

// Add 3 data series to the line layer
layer.setXData(timeStamps);
layer.addDataSet(data0, 0xff3333, "Alpha");
layer.addDataSet(data1, 0x008800, "Beta");
layer.addDataSet(data2, 0x3333cc, "Gamma");

// Create the WebChartViewer object
WebChartViewer viewer = new WebChartViewer(request, "chart1");

// Output the chart
String chartQuery = c.makeSession(viewer.getRequest(), viewer.getId());

// Set the chart URL to the viewer
viewer.setImageUrl("getchart.jsp?" + chartQuery);

// Output Javascript chart model to the browser to support tracking cursor
viewer.setChartModel(c.getJsChartModel());
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <title>Track Line with Legend</title>
    <script type="text/javascript" src="cdjcv.js"></script>
</head>
<body style="margin:5px 0px 0px 5px">
<script type="text/javascript">

//
// Use the window load event to set up the MouseMovePlotArea event handler
//
JsChartViewer.addEventListener(window, 'load', function() {
    var viewer = JsChartViewer.get('<%=viewer.getId()%>');

    // Draw track cursor when mouse is moving over plotarea
    viewer.attachHandler("MouseMovePlotArea", function(e) {
        trackLineLegend(viewer, viewer.getPlotAreaMouseX());
    });

    // Initialize the track legend to show the rightmost data point
    trackLineLegend(viewer, viewer.getChart().getPlotArea().getRightX());
});

//
// Draw track line with legend
//
function trackLineLegend(viewer, mouseX)
{
    // Remove all previously drawn tracking object
    viewer.hideObj("all");

    // The chart and its plot area
    var c = viewer.getChart();
    var plotArea = c.getPlotArea();

    // Get the data x-value that is nearest to the mouse, and find its pixel coordinate.
    var xValue = c.getNearestXValue(mouseX);
    var xCoor = c.getXCoor(xValue);
    if (xCoor == null)
        return;

    // Draw a vertical track line at the x-position
    viewer.drawVLine("trackLine", xCoor, plotArea.getTopY(), plotArea.getBottomY(), "black 1px dotted");

    // Array to hold the legend entries
    var legendEntries = [];

    // Iterate through all layers to build the legend array
    for (var i = 0; i < c.getLayerCount(); ++i)
    {
        var layer = c.getLayerByZ(i);

        // The data array index of the x-value
        var xIndex = layer.getXIndexOf(xValue);

        // Iterate through all the data sets in the layer
        for (var j = 0; j < layer.getDataSetCount(); ++j)
        {
            var dataSet = layer.getDataSetByZ(j);

            // We are only interested in visible data sets with names, as they are required for legend entries.
            var dataName = dataSet.getDataName();
            var color = dataSet.getDataColor();
            if ((!dataName) || (color == null))
                continue;

            // Build the legend entry, consist of a colored square box, the name and the data value.
            var dataValue = dataSet.getValue(xIndex);
            legendEntries.push("<nobr>" + viewer.htmlRect(7, 7, color) + " " + dataName + ": " +
                ((dataValue == null) ? "N/A" : dataValue.toPrecision(4)) + viewer.htmlRect(20, 0) + "</nobr> ");

            // Draw a track dot for data points within the plot area
            var yCoor = c.getYCoor(dataSet.getPosition(xIndex), dataSet.getUseYAxis());
            if ((yCoor != null) && (yCoor >= plotArea.getTopY()) && (yCoor <= plotArea.getBottomY()))
            {
                viewer.showTextBox("dataPoint" + i + "_" + j, xCoor, yCoor, JsChartViewer.Center,
                    viewer.htmlRect(7, 7, color));
            }
        }
    }

    // Create the legend by joining the legend entries.
    var legend = "<nobr>[" + c.xAxis().getFormattedLabel(xValue, "mm/dd/yyyy") + "]" + viewer.htmlRect(20, 0) +
        "</nobr> " + legendEntries.reverse().join("");

    // Display the legend on the top of the plot area
    viewer.showTextBox("legend", plotArea.getLeftX(), plotArea.getTopY(), JsChartViewer.BottomLeft, legend,
        "width:" + (plotArea.getWidth() - 1) + "px;font:bold 11px Arial;padding:3px;");
}

</script>
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Track Line with Legend
</div>
<hr style="border:solid 1px #000080" />
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<!-- ****** Here is the chart image ****** -->
<%=viewer.renderHTML(response)%>
</body>
</html>


Track Line with Data Labels (Web)

Track Line with Data Labels (Web)

NOTE: This section describes Track Line with Data Labels for web applications only. For Windows applications, please refer to Track Line with Data Labels (Windows).

This sample program demonstrates a track cursor programmed with the following features:

  • A vertical line that follows the mouse cursor on the plot area and snaps to the nearest x data value, with a label on the x-axis displaying that value.

  • Small dots that shows the data points at the nearest x data value.

  • >Labels beside the small dots displaying the values of the data points.

On the server side, the code draws the chart as usual, and outputs both the image and the Javascript Chart Model of the chart.

On the browser side, in the window onload event handler, Javascript is used to set up the JsChartViewer.MouseMovePlotArea event handler. The MouseMovePlotArea event handler calls trackLineLabel to draw the track cursor when the mouse moves on the plot area. It also calls JsChartViewer.setAutoHide to automatically remove the track cursor when the mouse leaves the plot area.

The trackLineLabel Javascript function is the routine that draws the track cursor. Its key elements are:

  • The code first uses JsChartViewer.hideObj to clear the previous track cursor, if any.

  • The nearest x data value is obtained using JsXYChart.getNearestXValue.

  • A vertical line is drawn at the nearest x data value using JsChartViewer.drawVLine.

  • The x-axis label at the nearest x value is drawn using JsChartViewer.showTextBox.

  • The code then iterates through all data sets in all layers to find all the data points at the nearest x data value. For each of these points, it gets the point's y position using JsDataSet.getPosition, and draws a square dot using JsChartViewer.showTextBox and JsChartViewer.htmlRect. It also formats the point's data value (obtained using JsDataSet.getValue) and displays it next to the dot using JsChartViewer.showTextBox.

Source Code Listing

[JSP Version] jspdemo/tracklabel.jsp
<%@page import="ChartDirector.*" %>
<%@page import="java.util.*" %>
<%
// Data for the chart as 3 random data series
RanSeries r = new RanSeries(127);
double[] data0 = r.getSeries(100, 100, -15, 15);
double[] data1 = r.getSeries(100, 150, -15, 15);
double[] data2 = r.getSeries(100, 200, -15, 15);
Date[] timeStamps = r.getDateSeries(100, new GregorianCalendar(2011, 0, 1).getTime(), 86400);

// Create a XYChart object of size 640 x 400 pixels
XYChart c = new XYChart(640, 400);

// Add a title to the chart using 18 pts Times New Roman Bold Italic font
c.addTitle("    Product Line Global Revenue", "Times New Roman Bold Italic", 18);

// Set the plotarea at (50, 55) with width 70 pixels less than chart width, and height 90 pixels
// less than chart height. Use a vertical gradient from light blue (f0f6ff) to sky blue (a0c0ff) as
// background. Set border to transparent and grid lines to white (ffffff).
c.setPlotArea(50, 55, c.getWidth() - 70, c.getHeight() - 90, c.linearGradientColor(0, 55, 0,
    c.getHeight() - 35, 0xf0f6ff, 0xa0c0ff), -1, Chart.Transparent, 0xffffff, 0xffffff);

// Add a legend box at (50, 25) using horizontal layout. Use 10pts Arial Bold as font. Set the
// background and border color to Transparent.
c.addLegend(50, 25, false, "Arial Bold", 10).setBackground(Chart.Transparent);

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

// Set the axis stem to transparent
c.xAxis().setColors(Chart.Transparent);
c.yAxis().setColors(Chart.Transparent);

// Configure x-axis label format
c.xAxis().setMultiFormat(Chart.StartOfYearFilter(), "{value|mm/yyyy} ", Chart.StartOfMonthFilter(),
    "{value|mm}");

// Add axis title using 10pts Arial Bold Italic font
c.yAxis().setTitle("USD millions", "Arial Bold Italic", 10);

// Add a line layer to the chart using a line width of 2 pixels.
LineLayer layer = c.addLineLayer2();
layer.setLineWidth(2);

// Add 3 data series to the line layer
layer.setXData(timeStamps);
layer.addDataSet(data0, 0xff3333, "Alpha");
layer.addDataSet(data1, 0x008800, "Beta");
layer.addDataSet(data2, 0x3333cc, "Gamma");

// Create the WebChartViewer object
WebChartViewer viewer = new WebChartViewer(request, "chart1");

// Output the chart
String chartQuery = c.makeSession(viewer.getRequest(), viewer.getId());

// Set the chart URL to the viewer
viewer.setImageUrl("getchart.jsp?" + chartQuery);

// Output Javascript chart model to the browser to support tracking cursor
viewer.setChartModel(c.getJsChartModel());
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <title>Track Line with Data Labels</title>
    <script type="text/javascript" src="cdjcv.js"></script>
</head>
<body style="margin:5px 0px 0px 5px">
<script type="text/javascript">

//
// Use the window load event to set up the MouseMovePlotArea event handler
//
JsChartViewer.addEventListener(window, 'load', function() {
    var viewer = JsChartViewer.get('<%=viewer.getId()%>');

    // Draw track cursor when mouse is moving over plotarea. Hide it when mouse leaves plot area.
    viewer.attachHandler("MouseMovePlotArea", function(e) {
        trackLineLabel(viewer, viewer.getPlotAreaMouseX());
        viewer.setAutoHide("all", "MouseOutPlotArea");
    });
});

//
// Draw track line with data labels
//
function trackLineLabel(viewer, mouseX)
{
    // Remove all previously drawn tracking object
    viewer.hideObj("all");

    // The chart and its plot area
    var c = viewer.getChart();
    var plotArea = c.getPlotArea();

    // Get the data x-value that is nearest to the mouse, and find its pixel coordinate.
    var xValue = c.getNearestXValue(mouseX);
    var xCoor = c.getXCoor(xValue);

    // Draw a vertical track line at the x-position
    viewer.drawVLine("trackLine", xCoor, plotArea.getTopY(), plotArea.getBottomY(), "black 1px dotted");

    // Draw a label on the x-axis to show the track line position
    viewer.showTextBox("xAxisLabel", xCoor, plotArea.getBottomY() + 4, JsChartViewer.Top,
        c.xAxis().getFormattedLabel(xValue, "mmm dd, yyyy"),
        "font:bold 11px Arial;color:#FFFFFF;background-color:#000000;padding:0px 3px");

    // Iterate through all layers to draw the data labels
    for (var i = 0; i < c.getLayerCount(); ++i)
    {
        var layer = c.getLayerByZ(i);

        // The data array index of the x-value
        var xIndex = layer.getXIndexOf(xValue);

        // Iterate through all the data sets in the layer
        for (var j = 0; j < layer.getDataSetCount(); ++j)
        {
            var dataSet = layer.getDataSetByZ(j);

            // Get the color and position of the data label
            var color = dataSet.getDataColor();
            var yCoor = c.getYCoor(dataSet.getPosition(xIndex), dataSet.getUseYAxis());

            // Draw a track dot with a label next to it for visible data points in the plot area
            if ((yCoor != null) && (yCoor >= plotArea.getTopY()) && (yCoor <= plotArea.getBottomY()) &&
                (color != null))
            {
                viewer.showTextBox("dataPoint" + i + "_" + j, xCoor, yCoor, JsChartViewer.Center,
                    viewer.htmlRect(7, 7, color));

                viewer.showTextBox("dataLabel" + i + "_" + j, xCoor + 5, yCoor, JsChartViewer.Left,
                    dataSet.getValue(xIndex).toPrecision(4),
                    "padding:0px 3px;font:bold 10px Arial;background-color:" + color + ";color:#FFFFFF");
            }
        }
    }
}

</script>
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Track Line with Data Labels
</div>
<hr style="border:solid 1px #000080" />
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<!-- ****** Here is the chart image ****** -->
<%=viewer.renderHTML(response)%>
</body>
</html>


Track Line with Axis Labels (Web)

Track Line with Axis Labels (Web)

NOTE: This section describes Track Line with Axis Labels for web applications only. For Windows applications, please refer to Track Line with Axis Labels (Windows).

This sample program demonstrates a track cursor programmed with the following features:

  • A vertical line that connects the data points to the x-axis, with an x-axis label displaying the x value.

  • Horizontal lines that connect the data points to the y-axes, with y-axis labels displaying their values.

On the server side, the code draws the chart as usual, and outputs both the image and the Javascript Chart Model of the chart.

On the browser side, in the window onload event handler, Javascript is used to set up the JsChartViewer.MouseMovePlotArea event handler. The MouseMovePlotArea event handler calls trackLineAxis to draw the track cursor when the mouse moves on the plot area. It also calls JsChartViewer.setAutoHide to automatically remove the track cursor when the mouse leaves the plot area.

The trackLineAxis Javascript function is the routine that draws the track cursor. Its key elements are:

  • The code first uses JsChartViewer.hideObj to clear the previous track cursor, if any.

  • The nearest x data value is obtained using JsXYChart.getNearestXValue.

  • The code iterates through all data sets in all layers to find the highest data point at the nearest x data value. It then draws a vertical line from that point to the x-axis using JsChartViewer.drawVLine, and the corresponding x-axis label using JsChartViewer.showTextBox.

  • The code iterates through all data sets in all layers once more to find all the data points at the nearest x data value. For each of these points, it draws a horizontal line to connect the point to the y-axis using JsChartViewer.drawHLine, draws the axis label using JsChartViewer.showTextBox, and draws a square dot at the point using JsChartViewer.showTextBox and JsChartViewer.htmlRect.

Source Code Listing

[JSP Version] jspdemo/trackaxis.jsp
<%@page import="ChartDirector.*" %>
<%@page import="java.util.*" %>
<%
// Data for the chart as 2 random data series
RanSeries r = new RanSeries(127);
double[] data0 = r.getSeries(180, 10, -1.5, 1.5);
double[] data1 = r.getSeries(180, 150, -15, 15);
Date[] timeStamps = r.getDateSeries(180, new GregorianCalendar(2011, 0, 1).getTime(), 86400);

// Create a XYChart object of size 670 x 400 pixels
XYChart c = new XYChart(670, 400);

// Add a title to the chart using 18 pts Times New Roman Bold Italic font
c.addTitle("Plasma Stabilizer Energy Usage", "Times New Roman Bold Italic", 18);

// Set the plotarea at (50, 55) with width 100 pixels less than chart width, and height 90 pixels
// less than chart height. Use a vertical gradient from light blue (f0f6ff) to sky blue (a0c0ff) as
// background. Set border to transparent and grid lines to white (ffffff).
c.setPlotArea(50, 55, c.getWidth() - 100, c.getHeight() - 90, c.linearGradientColor(0, 55, 0,
    c.getHeight() - 35, 0xf0f6ff, 0xa0c0ff), -1, Chart.Transparent, 0xffffff, 0xffffff);

// Add a legend box at (50, 25) using horizontal layout. Use 10pts Arial Bold as font. Set the
// background and border color to Transparent.
c.addLegend(50, 25, false, "Arial Bold", 10).setBackground(Chart.Transparent);

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

// Set the axis stem to transparent
c.xAxis().setColors(Chart.Transparent);
c.yAxis().setColors(Chart.Transparent);
c.yAxis2().setColors(Chart.Transparent);

// Configure x-axis label format
c.xAxis().setMultiFormat(Chart.StartOfYearFilter(), "{value|mm/yyyy} ", Chart.StartOfMonthFilter(),
    "{value|mm}");

// Add axis title using 10pts Arial Bold Italic font
c.yAxis().setTitle("Power Usage (Watt)", "Arial Bold Italic", 10);
c.yAxis2().setTitle("Effective Load (kg)", "Arial Bold Italic", 10);

// Add a line layer to the chart using a line width of 2 pixels.
LineLayer layer = c.addLineLayer2();
layer.setLineWidth(2);

// Add 2 data series to the line layer
layer.setXData(timeStamps);
layer.addDataSet(data0, 0xcc0000, "Power Usage");
layer.addDataSet(data1, 0x008800, "Effective Load").setUseYAxis2();

// Create the WebChartViewer object
WebChartViewer viewer = new WebChartViewer(request, "chart1");

// Output the chart
String chartQuery = c.makeSession(viewer.getRequest(), viewer.getId());

// Set the chart URL to the viewer
viewer.setImageUrl("getchart.jsp?" + chartQuery);

// Output Javascript chart model to the browser to support tracking cursor
viewer.setChartModel(c.getJsChartModel());
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <title>Track Line with Axis Labels</title>
    <script type="text/javascript" src="cdjcv.js"></script>
</head>
<body style="margin:5px 0px 0px 5px">
<script type="text/javascript">

//
// Use the window load event to set up the MouseMovePlotArea event handler
//
JsChartViewer.addEventListener(window, 'load', function() {
    var viewer = JsChartViewer.get('<%=viewer.getId()%>');

    // Draw track cursor when mouse is moving over plotarea. Hide it when mouse leaves plot area.
    viewer.attachHandler("MouseMovePlotArea", function(e) {
        trackLineAxis(viewer, viewer.getPlotAreaMouseX());
        viewer.setAutoHide("all", "MouseOutPlotArea");
    });
});

//
// Draw track line with axis labels
//
function trackLineAxis(viewer, mouseX)
{
    // Remove all previously drawn tracking object
    viewer.hideObj("all");

    // The chart and its plot area
    var c = viewer.getChart();
    var plotArea = c.getPlotArea();

    // Get the data x-value that is nearest to the mouse, and find its pixel coordinate.
    var xValue = c.getNearestXValue(mouseX);
    var xCoor = c.getXCoor(xValue);

    // The vertical track line is drawn up to the highest data point (the point with smallest
    // y-coordinate). We need to iterate all datasets in all layers to determine where it is.
    var minY = plotArea.getBottomY();

    // Iterate through all layers to find the highest data point
    for (var i = 0; i < c.getLayerCount(); ++i)
    {
        var layer = c.getLayerByZ(i);

        // The data array index of the x-value
        var xIndex = layer.getXIndexOf(xValue);

        // Iterate through all the data sets in the layer
        for (var j = 0; j < layer.getDataSetCount(); ++j)
        {
            var dataSet = layer.getDataSetByZ(j);
            var yCoor = c.getYCoor(dataSet.getPosition(xIndex), dataSet.getUseYAxis());
            if ((yCoor != null) && (dataSet.getDataColor() != null))
                minY = Math.min(minY, yCoor);
        }
    }

    // Draw a vertical track line at the x-position up to the highest data point.
    viewer.drawVLine("trackLine", xCoor, Math.max(minY, plotArea.getTopY()),
        plotArea.getBottomY() + 3, "black 1px dotted");

    // Draw a label on the x-axis to show the track line position
    viewer.showTextBox("xAxisLabel", xCoor, plotArea.getBottomY() + 3, JsChartViewer.Top,
        c.xAxis().getFormattedLabel(xValue, "mmm dd, yyyy"),
        "font:bold 11px Arial;color:#FFFFFF;background-color:#000000;padding:2px 3px");

    // Iterate through all layers to draw the axis labels for the data points
    for (var i = 0; i < c.getLayerCount(); ++i)
    {
      var layer = c.getLayerByZ(i);

        // The data array index of the x-value
        var xIndex = layer.getXIndexOf(xValue);

        // Iterate through all the data sets in the layer
        for (var j = 0; j < layer.getDataSetCount(); ++j)
        {
            var dataSet = layer.getDataSetByZ(j);

            // The positional value, axis binding, pixel coordinate and color of the data point.
            var dataPoint = dataSet.getPosition(xIndex);
            var yAxis = dataSet.getUseYAxis();
            var yCoor = c.getYCoor(dataPoint, yAxis);
            var color = dataSet.getDataColor();

            // Draw the axis label only for visible data points of named data sets
            if ((yCoor != null) && (yCoor >= plotArea.getTopY()) && (yCoor <= plotArea.getBottomY()) &&
                (color != null))
            {
                // The axis label consists of 3 parts - a track dot for the data point, an axis label,
                // and a line joining the track dot to the axis label.

                // Draw the line first. The end point of the line at the axis label side depends on
                // whether the label is at the left or right side of the axis (that is, on whether
                // the axis is on the left or right side of the plot area).
                var xPos = yAxis.getX() + ((yAxis.getAlignment() == JsChartViewer.Left) ? -4 : 4);
                viewer.drawHLine("joinLine" + i + "_" + j, yCoor, xPos, xCoor, color + " 1px dotted");

                // Draw the axis label. If the axis is on the left side of the plot area, the labels
                // should right aligned to the axis, and vice versa.
                viewer.showTextBox("yAxisLabel" + i + "_" + j, xPos, yCoor,
                    (yAxis.getAlignment() == JsChartViewer.Left) ? JsChartViewer.Right : JsChartViewer.Left,
                    dataPoint.toPrecision(4),
                    "padding:2px 3px;font:bold 11px Arial;background-color:" + color + ";color:#FFFFFF");

                // Draw the track dot
                viewer.showTextBox("dataPoint" + i + "_" + j, xCoor, yCoor, JsChartViewer.Center,
                    viewer.htmlRect(7, 7, color));
            }
        }
    }
}

</script>
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Track Line with Axis Labels
</div>
<hr style="border:solid 1px #000080" />
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<!-- ****** Here is the chart image ****** -->
<%=viewer.renderHTML(response)%>
</body>
</html>


Track Box with Legend (Web)

Track Box with Legend (Web)

NOTE: This section describes Track Box with Legend for web applications only. For Windows applications, please refer to Track Box with Legend (Windows).

This sample program demonstrates a track cursor programmed with the following features:

  • A box that horizontally centers around the x data value nearest to the mouse cursor.

  • A floating legend box that moves with the mouse cursor, displaying the data values at the x data value nearest to the mouse cursor.

On the server side, the code draws the chart as usual, and outputs both the image and the Javascript Chart Model of the chart.

On the browser side, in the window onload event handler, Javascript is used to set up the JsChartViewer.MouseMovePlotArea event handler. The MouseMovePlotArea event handler calls trackBoxLegend to draw the track cursor when the mouse moves on the plot area. It also calls JsChartViewer.setAutoHide to automatically remove the track cursor when the mouse leaves the plot area.

The trackBoxLegend Javascript function is the routine that draws the track cursor. Its key elements are:

  • The code first uses JsChartViewer.hideObj to clear the previous track cursor, if any.

  • The nearest x data value is obtained using JsXYChart.getNearestXValue.

  • The code draws a rectangle that horizontally spans from (x - 0.5) to (x + 0.5) with JsChartViewer.showTextBox. The +/- 0.5 offset is the suitable value to use for a label based x-axis (that is, for axis set up with Axis.setLabels or Axis.setLabels2). For this type of axis, the label distance is assumed to be 1 x-axis unit irrespective of what are the labels, so an offset of 0.5 refers to the middle position between two labels.

  • The code then iterates through all data sets in all layers to find all the data points at the nearest x data value. For each of these points, it formats a legend entry for the point, which consists of a colored square as the icon (creating using JsChartViewer.htmlRect), data set name (obtained using JsDataSet.getDataName), and the data value (obtained using JsDataSet.getValue).

  • Finally, the code combines all the legend entries into a legend box and draws it near the mouse cursor using JsChartViewer.showTextBox.

Source Code Listing

[JSP Version] jspdemo/trackbox.jsp
<%@page import="ChartDirector.*" %>
<%
// The data for the bar chart
double[] data0 = {100, 125, 245, 147, 67};
double[] data1 = {85, 156, 179, 211, 123};
double[] data2 = {97, 87, 56, 267, 157};
String[] labels = {"Mon", "Tue", "Wed", "Thur", "Fri"};

// Create a XYChart object of size 540 x 375 pixels
XYChart c = new 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(Chart.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
BarLayer layer = c.addBarLayer2(Chart.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(Chart.Transparent, Chart.glassEffect(Chart.NormalGlare, Chart.Left));

// Configure the bars within a group to touch each others (no gap)
layer.setBarGap(0.2, Chart.TouchBar);

// Create the WebChartViewer object
WebChartViewer viewer = new WebChartViewer(request, "chart1");

// Output the chart
String chartQuery = c.makeSession(viewer.getRequest(), viewer.getId());

// Set the chart URL to the viewer
viewer.setImageUrl("getchart.jsp?" + chartQuery);

// Output Javascript chart model to the browser to support tracking cursor
viewer.setChartModel(c.getJsChartModel());
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <title>Track Box with Legend</title>
    <script type="text/javascript" src="cdjcv.js"></script>
</head>
<body style="margin:5px 0px 0px 5px">
<script type="text/javascript">

//
// Use the window load event to set up the MouseMovePlotArea event handler
//
JsChartViewer.addEventListener(window, 'load', function() {
    var viewer = JsChartViewer.get('<%=viewer.getId()%>');

    // Draw track cursor when mouse is moving over plotarea. Hide it when mouse leaves plot area.
    viewer.attachHandler("MouseMovePlotArea", function(e) {
        trackBoxLegend(viewer, viewer.getPlotAreaMouseX(), viewer.getPlotAreaMouseY());
        viewer.setAutoHide("all", "MouseOutPlotArea");
    });
});

//
// Draw track box with legend
//
function trackBoxLegend(viewer, mouseX, mouseY)
{
    // Remove all previously drawn tracking object
    viewer.hideObj("all");

    // The chart and its plot area
    var c = viewer.getChart();
    var plotArea = c.getPlotArea();

    // Get the data x-value that is nearest to the mouse
    var xValue = c.getNearestXValue(mouseX);

    // Compute the position of the box. This example assumes a label based x-axis, in which the labeling spacing
    // is one x-axis unit. So the left and right sides of the box is 0.5 unit from the central x-value.
    var boxLeft = Math.min(c.getXCoor(xValue - 0.5), c.getXCoor(xValue + 0.5));
    var boxWidth = Math.max(0, Math.abs(c.getXCoor(xValue + 0.5) - c.getXCoor(xValue - 0.5)) - 1);
    var boxTop = plotArea.getTopY();
    var boxHeight = Math.max(0, plotArea.getHeight() - 2);

    // Draw the track box
    viewer.showTextBox("trackBox", boxLeft, boxTop, JsChartViewer.TopLeft, "",
        "width:" + boxWidth + "px;height:" + boxHeight + "px;border:solid 1px black;");

    // Array to hold the legend entries
    var legendEntries = [];

    // Iterate through all layers to build the legend array
    for (var i = 0; i < c.getLayerCount(); ++i)
    {
        var layer = c.getLayerByZ(i);

        // The data array index of the x-value
        var xIndex = layer.getXIndexOf(xValue);

        // Iterate through all the data sets in the layer
        for (var j = 0; j < layer.getDataSetCount(); ++j)
        {
            var dataSet = layer.getDataSetByZ(j);

            // Build the legend entry, consist of a colored square box, the name and the data value.
            var dataColor = dataSet.getDataColor();
            var dataValue = dataSet.getValue(xIndex);
            if ((dataValue != null) && (dataColor != null))
            {
                legendEntries.push("<nobr>" + viewer.htmlRect(7, 7, dataColor) + " " +
                    dataSet.getDataName() + ": " + dataValue.toPrecision(4) + "</nobr> ");
            }
        }
    }

    // Create the legend by joining the legend entries
    if (legendEntries.length > 0)
    {
        var legend = "<u>" + c.xAxis().getFormattedLabel(xValue) + "</u><br />" + legendEntries.reverse().join("<br />");

        // Display the legend at the bottom-right side of the mouse cursor
        viewer.showTextBox("legend", mouseX + 16, mouseY + 16, JsChartViewer.TopLeft, legend,
            "border:solid 1px black;background:#ffffcc;padding:3px;font:bold 11px Arial;");
    }
}

</script>
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Track Box with Legend
</div>
<hr style="border:solid 1px #000080" />
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<!-- ****** Here is the chart image ****** -->
<%=viewer.renderHTML(response)%>
</body>
</html>


Finance Chart Track Line (Web)

Finance Chart Track Line (Web)

NOTE: This section describes Finance Chart Track Line for web applications only. For Windows applications, please refer to Finance Chart Track Line (Windows).

This sample program demonstrates a track cursor for a finance chart programmed with the following features:

  • A vertical line that follows the mouse cursor on the plot area and snaps to the nearest trading session.

  • Dynamically updated legend entries that shows the price, volume and other technical indicator for the nearest trading session.

On the server side, the code draws the finance chart with the legend box set to transparent (so that the default legend box is not displayed), It outputs both the image and the Javascript Chart Model of the chart.

On the browser side, in the window onload event handler, Javascript is used to set up the JsChartViewer.MouseMovePlotArea event handler. The MouseMovePlotArea event handler calls trackFinance to draw the track cursor when the mouse moves on the plot area. The windows onload event handler also directly calls trackFinance to initialize the track cursor to the right side of the plot area. This is to ensure the chart initially has a legend that reflects the latest data values.

The trackFinance Javascript function is the routine that draws the track cursor. Its key elements are:

  • The code first uses JsChartViewer.hideObj to clear the previous track cursor, if any.

  • The nearest trading session is obtained from the first JsXYChart in the FinanceChart using JsXYChart.getNearestXValue.

  • The code iterates through all the JsXYChart objects in the FinanceChart. For each JsXYChart, the code iterates through all the layers to create dynamic legend entries. The FinanceChart creates default static legend entries for all indicators showing their latest values (even though the default static legend box is set to transparent in the chart). The code creates the dynamic legend entries by replacing the values in the static legend entries.

  • If a layer contains 4 data sets, the code assumes it is either a CandleStickLayer or HLOCLayer. It formats a legend entry consisting of the open, high, low, close values, as well as an up/down icon and the percentage change.

  • If a layer contains 2 data sets, the code assumes the layer is for a "band" or "channel" (such as Bollinger Band or Donchian Channel). The code formats a legend entry by replacing the values in the default legend entry (obtained using JsDataSet.getDataName).

  • If a layer contains 3 data sets, the code assumes the layer is for volume bars, with the 3 data sets representing volume bars of different colors for up, down and flat days. The code computes the volume by adding the values from the three data sets, and formats a legend entry by replacing the value in the default legend entry (obtained using JsDataSet.getDataName) with the computed value.

  • In all other cases, the code iterates the data sets. For each of them, it formats a legend by replacing the value in the default legend entry (obtained using JsDataSet.getDataName) with the value for the nearest trading session (obtained using JsDataSet.getValue).

  • Finally, the code combines all the legend entries into a legend box and draws it on top of the plot area using JsChartViewer.showTextBox. It also draws a vertical line at the nearest trading session using JsChartViewer.drawVLine.

Source Code Listing

[JSP Version] jspdemo/trackfinance.jsp
<%@page import="ChartDirector.*" %>
<%@page import="java.util.*" %>
<%
// Create a finance chart demo containing 100 days of data
int noOfDays = 100;

// To compute moving averages starting from the first day, we need to get extra data points before
// the first day
int 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 rantable = new RanTable(9, 6, noOfDays + extraDays);

// Set the 1st col to be the timeStamp, starting from Sep 4, 2011, with each row representing one
// day, and counting week days only (jump over Sat and Sun)
rantable.setDateCol(0, new GregorianCalendar(2011, 8, 4).getTime(), 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
double[] timeStamps = rantable.getCol(0);
double[] highData = rantable.getCol(1);
double[] lowData = rantable.getCol(2);
double[] openData = rantable.getCol(3);
double[] closeData = rantable.getCol(4);
double[] volData = rantable.getCol(5);

// Create a FinanceChart object of width 720 pixels
FinanceChart c = new FinanceChart(720);

// Add a title to the chart
c.addTitle("Finance Chart Demonstration");

// Disable default legend box, as we are using dynamic legend
c.setLegendStyle("normal", 8, Chart.Transparent, Chart.Transparent);

// Set the data into the finance chart object
c.setData(timeStamps, highData, lowData, openData, closeData, volData, extraDays);

// Add the main chart with 240 pixels in height
c.addMainChart(240);

// 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 candlestick symbols to the main chart, using green/red for up/down days
c.addCandleStick(0x00ff00, 0xff0000);

// 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 75 pixels volume bars sub-chart to the bottom of the main chart, using green/red/grey for
// up/down/flat days
c.addVolBars(75, 0x99ff99, 0xff9999, 0x808080);

// Append a 14-days RSI indicator chart (75 pixels high) 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(75, 14, 0x800080, 20, 0xff0000, 0x0000ff);

// Append a MACD(26, 12) indicator chart (75 pixels high) after the main chart, using 9 days for
// computing divergence.
c.addMACD(75, 26, 12, 9, 0x0000ff, 0xff00ff, 0x008000);

// Create the WebChartViewer object
WebChartViewer viewer = new WebChartViewer(request, "chart1");

// Output the chart
String chartQuery = c.makeSession(viewer.getRequest(), viewer.getId());

// Set the chart URL to the viewer
viewer.setImageUrl("getchart.jsp?" + chartQuery);

// Output Javascript chart model to the browser to support tracking cursor
viewer.setChartModel(c.getJsChartModel());
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <title>Finance Chart Track Line</title>
    <script type="text/javascript" src="cdjcv.js"></script>
</head>
<body style="margin:5px 0px 0px 5px">
<script type="text/javascript">

//
// Use the window load event to set up the MouseMovePlotArea event handler
//
JsChartViewer.addEventListener(window, 'load', function() {
    var viewer = JsChartViewer.get('<%=viewer.getId()%>');

    // Draw track cursor when mouse is moving over plotarea
    viewer.attachHandler("MouseMovePlotArea", function(e) {
        traceFinance(viewer, viewer.getPlotAreaMouseX());
    });

    // Initialize the track line with legend to show the latest data point
    if (viewer.getChart())
        traceFinance(viewer, viewer.getChart().getPlotArea().getRightX());
});

//
// Draw finance chart track line with legend
//
function traceFinance(viewer, mouseX)
{
    // Remove all previously drawn tracking object
    viewer.hideObj("all");

    // It is possible for a FinanceChart to be empty, so we need to check for it.
    if (!viewer.getChart())
        return;

    // Get the data x-value that is nearest to the mouse
    var xValue = viewer.getChart().getNearestXValue(mouseX);

    // Iterate the XY charts (main price chart and indicator charts) in the FinanceChart
    var c = null;
    for (var i = 0; i < viewer.getChartCount(); ++i)
    {
        c = viewer.getChart(i);

        // Variables to hold the legend entries
        var ohlcLegend = "";
        var legendEntries = [];

        // Iterate through all layers to build the legend array
        for (var j = 0; j < c.getLayerCount(); ++j)
        {
            var layer = c.getLayerByZ(j);
            var xIndex = layer.getXIndexOf(xValue);
            var dataSetCount = layer.getDataSetCount();

            // In a FinanceChart, only layers showing OHLC data can have 4 data sets
            if (dataSetCount == 4)
            {
                var highValue = layer.getDataSet(0).getValue(xIndex);
                var lowValue = layer.getDataSet(1).getValue(xIndex);
                var openValue = layer.getDataSet(2).getValue(xIndex);
                var closeValue = layer.getDataSet(3).getValue(xIndex);

                if (closeValue == null)
                    continue;

                // Build the OHLC legend
                ohlcLegend =
                    "Open: " + openValue.toPrecision(4) + ", High: " + highValue.toPrecision(4) +
                    ", Low: " + lowValue.toPrecision(4) + ", Close: " + closeValue.toPrecision(4);

                // We also draw an upward or downward triangle for up and down days and the % change
                var lastCloseValue = layer.getDataSet(3).getValue(xIndex - 1);
                if (lastCloseValue != null)
                {
                    var change = closeValue - lastCloseValue;
                    var percent = change * 100 / closeValue;
                    if (change >= 0)
                        ohlcLegend += "&nbsp;&nbsp;<span style='color:#008800;'>&#9650; ";
                    else
                        ohlcLegend += "&nbsp;&nbsp;<span style='color:#CC0000;'>&#9660; ";
                    ohlcLegend += change.toPrecision(4) + " (" + percent.toFixed(2) + "%)</span>";
                }

                // Add a spacer box, and make sure the line does not wrap within the legend entry
                ohlcLegend = "<nobr>" + ohlcLegend + viewer.htmlRect(20, 0) + "</nobr> ";
            }
            else
            {
                // Iterate through all the data sets in the layer
                for (var k = 0; k < dataSetCount; ++k)
                {
                    var dataSet = layer.getDataSetByZ(k);
                    var name = dataSet.getDataName();
                    var value = dataSet.getValue(xIndex);
                    if ((!name) || (value == null))
                        continue;

                    // In a FinanceChart, the data set name consists of the indicator name and its latest value. It is
                    // like "Vol: 123M" or "RSI (14): 55.34". As we are generating the values dynamically, we need to
                    // extract the indictor name out, and also the volume unit (if any).

                    // The unit character, if any, is the last character and must not be a digit.
                    var unitChar = name.charAt(name.length - 1);
                    if ((unitChar >= '0') && (unitChar <= '9'))
                        unitChar = '';

                    // The indicator name is the part of the name up to the colon character.
                    var delimiterPosition = name.indexOf(':');
                    if (delimiterPosition != -1)
                        name = name.substring(0, delimiterPosition);

                    // In a FinanceChart, if there are two data sets, it must be representing a range.
                    if (dataSetCount == 2)
                    {
                        // We show both values in the range
                        var value2 = layer.getDataSetByZ(1 - k).getValue(xIndex);
                        name = name + ": " + Math.min(value, value2).toPrecision(4) + " - "
                            + Math.max(value, value2).toPrecision(4);
                    }
                    else
                    {
                        // In a FinanceChart, only the layer for volume bars has 3 data sets for up/down/flat days
                        if (dataSetCount == 3)
                        {
                            // The actual volume is the sum of the 3 data sets.
                            value = layer.getDataSet(0).getValue(xIndex) + layer.getDataSet(1).getValue(xIndex) +
                                layer.getDataSet(2).getValue(xIndex);
                        }

                        // Create the legend entry
                        name = name + ": " + value.toPrecision(4) + unitChar;
                    }

                    // Build the legend entry, consist of a colored square box and the name (with the data value in it).
                    legendEntries.push("<nobr>" + viewer.htmlRect(5, 5, dataSet.getDataColor(),
                        "solid 1px black") + " " + name + viewer.htmlRect(20, 0) + "</nobr>");
                }
            }
        }

        // The legend is formed by concatenating the legend entries.
        var legend = legendEntries.reverse().join(" ");

        // Add the date and the ohlcLegend (if any) at the beginning of the legend
        legend = "<nobr>[" + c.xAxis().getFormattedLabel(xValue, "mmm dd, yyyy") + "]" + viewer.htmlRect(20, 0) +
            "</nobr> " + ohlcLegend + legend;

        // Get the plot area position relative to the entire FinanceChart
        var plotArea = c.getPlotArea();
        var plotAreaLeftX = plotArea.getLeftX() + c.getAbsOffsetX();
        var plotAreaTopY = plotArea.getTopY() + c.getAbsOffsetY();

        // Draw a vertical track line at the x-position
        viewer.drawVLine("trackLine" + i, c.getXCoor(xValue) + c.getAbsOffsetX(), plotAreaTopY,
            plotAreaTopY + plotArea.getHeight(), "black 1px dotted");

        // Display the legend on the top of the plot area
        viewer.showTextBox("legend" + i, plotAreaLeftX + 1, plotAreaTopY + 1, JsChartViewer.TopLeft, legend,
            "padding-left:5px;width:" + (plotArea.getWidth() - 1) + "px;font:11px Arial;");
    }
}

</script>
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Finance Chart Track Line
</div>
<hr style="border:solid 1px #000080" />
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<!-- ****** Here is the chart image ****** -->
<%=viewer.renderHTML(response)%>
</body>
</html>


Crosshair with Axis Labels (Web)

Crosshair with Axis Labels (Web)

NOTE: This section describes Crosshair with Axis Labels for web applications only. For Windows applications, please refer to Crosshair with Axis Labels (Windows).

This sample program demonstrates a track cursor programmed as a crosshair cursor with axis labels. In additional, it demonstrates using hot spot events to pop up a box when the mouse is over a data point or the trend line, showing information about these objects with HTML formatting.

The key elements of the server side charting code are as follows:

  • The code draws the chart as usual.

  • The code configures the image map for the scatter layer to call the Javascript function showDataPointToolTip on mouse over, and call hideToolTip on mouse out.

  • The code configures the image map for the trend layer to call the Javascript function showTrendLineToolTip on mouse over, and call hideToolTip on mouse out.

  • The code outputs the chart image, the image map and the Javascript Chart Model to the browser.

      On the browser side, in the window onload event handler, Javascript is used to set up the JsChartViewer.MouseMovePlotArea event handler. The MouseMovePlotArea event handler calls crossHairAxisLabel to draw the track cursor when the mouse moves on the plot area. It also calls JsChartViewer.setAutoHide to automatically remove the track cursor when the mouse leaves the plot area.

      The crossHairAxisLabel Javascript function is the routine that draws the track cursor. Its key elements are:

    • The code uses JsChartViewer.showCrossHair to draw a crosshair on the chart.

    • The code gets the JsAxis objects representing the x and y axes of the chart, and draws labels on them using JsChartViewer.showTextBox.

    The showDataPointToolTip and showTrendLineToolTip Javascript functions are the routines that draw the pop up box to display tooltips for the data points and the trend line. They use JsChartViewer.showTextBox to draw the box 20 pixels away from the mouse cursor. The hideToolTip hides the pop up box using JsChartViewer.hideObj.

Source Code Listing

[JSP Version] jspdemo/crosshair.jsp
<%@page import="ChartDirector.*" %>
<%
// The XY data of the first data series
double[] dataX = {50, 55, 37, 24, 42, 49, 63, 72, 83, 59};
double[] dataY = {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 520 x 490 pixels
XYChart c = new XYChart(520, 490);

// Set the plotarea at (60, 40) and of size 450 x 400 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(60, 40, 450, 400, 0xffffff, -1, 0xc0c0c0, 0xc0c0c0, -1);

// Add a title to the chart using 18 point Times Bold Itatic font.
c.addTitle("      Chemical X Thermal Conductivity", "Times New Roman Bold Italic", 18);

// Add titles to the axes using 12 pts Arial Bold Italic font
c.yAxis().setTitle("Thermal Conductivity (W/K)", "Arial Bold Italic", 12);
c.xAxis().setTitle("Concentration (g/liter)", "Arial Bold Italic", 12);

// Set the axes line width to 3 pixels
c.yAxis().setWidth(3);
c.xAxis().setWidth(3);

// Add a scatter layer using (dataX, dataY)
ScatterLayer scatterLayer = c.addScatterLayer(dataX, dataY, "", Chart.GlassSphereShape, 13, 0xcc0000
    );

// Show custom Javascript tooltip for the scatter layer
scatterLayer.setHTMLImageMap("", "",
    "onmouseover='showDataPointToolTip({x}, {value})' onmouseout='hideToolTip()'");

// Add a trend line layer for (dataX, dataY)
TrendLayer trendLayer = c.addTrendLayer2(dataX, dataY, 0xcc0000);

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

// Show custom Javascript tooltip for the trend layer
trendLayer.setHTMLImageMap("", "",
    "onmouseover='showTrendLineToolTip({slope}, {intercept})' onmouseout='hideToolTip()'");

// Add a legend box at (60, 35) (top of the chart) with horizontal layout. Use 10 pts Arial Bold
// Italic font. Set the background and border color to Transparent and use line style legend icons.
LegendBox legendBox = c.addLegend(60, 35, false, "Arial Bold Italic", 9);
legendBox.setBackground(Chart.Transparent);
legendBox.setLineStyleKey(true);

// Add entries to the legend box
legendBox.addKey("95% Line Confidence", 0x806666ff);
legendBox.addKey("95% Point Confidence", 0x8066ff66);
legendBox.addKey(java.text.MessageFormat.format(
    "Trend Line: y = {0,number,#.####} x + {1,number,#.####}", new Object[]{new Double(
    trendLayer.getSlope()), new Double(trendLayer.getIntercept())}), 0xcc0000, 3);

// Create the WebChartViewer object
WebChartViewer viewer = new WebChartViewer(request, "chart1");

// Output the chart
String chartQuery = c.makeSession(viewer.getRequest(), viewer.getId());

// Include tool tip for the chart
String imageMap = c.getHTMLImageMap("");

// Set the chart URL and image map to the viewer
viewer.setImageUrl("getchart.jsp?" + chartQuery);
viewer.setImageMap(imageMap);

// Output Javascript chart model to the browser to support tracking cursor
viewer.setChartModel(c.getJsChartModel());
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <title>Crosshair with Axis Labels</title>
    <script type="text/javascript" src="cdjcv.js"></script>
</head>
<body style="margin:5px 0px 0px 5px">
<script type="text/javascript">

//
// Use the window load event to set up the MouseMovePlotArea event handler
//
JsChartViewer.addEventListener(window, 'load', function() {
    var viewer = JsChartViewer.get('<%=viewer.getId()%>');

    // Draw track cursor when mouse is moving over plotarea. Hide it when mouse leaves plot area.
    viewer.attachHandler("MouseMovePlotArea", function(e) {
        crossHairAxisLabel(viewer, viewer.getPlotAreaMouseX(), viewer.getPlotAreaMouseY());
        viewer.setAutoHide("all", "MouseOutPlotArea");
    });
});

//
// Draw cross hair cursor with axis labels
//
function crossHairAxisLabel(viewer, x, y)
{
    // Show cross hair
    viewer.showCrossHair(x, y);

    // The chart, its plot area and axes
    var c = viewer.getChart();
    var xAxis = c.xAxis();
    var yAxis = c.yAxis();

    // The axis label style
    var labelStyle = "padding:2px 4px; font: bold 8pt arial; border:1px solid black; background-color:#DDDDFF";

    // Draw x-axis label
    var yPos = xAxis.getY() + ((xAxis.getAlignment() == JsChartViewer.Top) ? -2 : 3);
    var alignment = (xAxis.getAlignment() == JsChartViewer.Top) ? JsChartViewer.Bottom : JsChartViewer.Top;
    viewer.showTextBox("xAxisLabel", x, yPos, alignment, c.getXValue(x).toPrecision(4), labelStyle);

    // Draw y-axis label
    var xPos = yAxis.getX() + ((yAxis.getAlignment() == JsChartViewer.Left) ? -2 : 3);
    var alignment = (yAxis.getAlignment() == JsChartViewer.Left) ? JsChartViewer.Right : JsChartViewer.Left;
    viewer.showTextBox("yAxisLabel", xPos, y, alignment, c.getYValue(y, yAxis).toPrecision(4), labelStyle);
}

//
// Show custom tooltip for data points
//
function showDataPointToolTip(x, y)
{
    var viewer = JsChartViewer.get('<%=viewer.getId()%>');
    viewer.showTextBox("toolTipBox", viewer.getChartMouseX() + 20, viewer.getChartMouseY() + 20, JsChartViewer.TopLeft,
        "<table><tr><td>Concentration</td><td>: " + x.toPrecision(4) +
        " g/liter</td></tr><tr><td>Conductivity</td><td>: " + y.toPrecision(4) + " W/K</td></tr></table>",
        "padding:0px; font:bold 8pt arial; border:1px solid black; background-color:#DDDDFF");
}

//
// Show custom tooltip for the trend line
//
function showTrendLineToolTip(slope, intercept)
{
    var viewer = JsChartViewer.get('<%=viewer.getId()%>');
    viewer.showTextBox("toolTipBox", viewer.getChartMouseX() + 20, viewer.getChartMouseY() + 20, JsChartViewer.TopLeft,
        "Trend Line: y = " + slope.toFixed(4) + " x + " + intercept.toFixed(4),
        "padding:2px 4px; font:bold 8pt arial; border:1px solid black; background-color:#DDDDFF");
}

//
// Hide custom tooltip
//
function hideToolTip()
{
    var viewer = JsChartViewer.get('<%=viewer.getId()%>');
    viewer.hideObj("toolTipBox");
}

</script>
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Crosshair with Axis Labels
</div>
<hr style="border:solid 1px #000080" />
<div style="font-size:10pt; font-family:verdana; margin-bottom:1.5em">
    <a href="viewsource.jsp?file=<%=request.getServletPath()%>">View Source Code</a>
</div>
<!-- ****** Here is the chart image ****** -->
<%=viewer.renderHTML(response)%>
</body>
</html>


Zoomable and Scrollable Charts

Zoomable and Scrollable Charts

This section describes the ChartDirector Zooming and Scrolling Framework for creating zooming and scrollable charts.

For Windows Applications

Zooming and Scrolling Framework (Windows)
Description of the ChartDirector Zooming and Scroll Framework for Windows applications.

Simple Zooming and Scrolling (Windows)
This sample program demonstrates a simple zoomable and scrollable chart with tooltips, using mouse click and drag to control zooming and scrolling.

Zooming and Scrolling with Track Line (1) (Windows)
In addition to using mouse click and drag, this example demonstrates using a scroll bar for scrolling, and mouse wheel for zooming. It also includes a track cursor that updates the legend dynamically to display the data values as the mouse cursor moves over the chart.

Zooming and Scrolling with Track Line (2) (Windows)
This example extends Zooming and Scrolling with Track Line (1) (Windows) by adding two date picker controls. The user can use them to change the start and end dates of the chart. Conversely, if the start and end dates of the chart are changed by other means (such as using mouse drag to scroll/zoom, mouse wheel or using the scroll bar), the date picker controls will be updated.

XY Zooming and Scrolling (Windows)
This example demonstrates zooming and scrolling in both horizontal and vertical directions. In addition to using mouse click and drag, this example demonstrates using a slider and the mouse wheel to control zooming. There is also a "navigation pad" which can be thought as a representation of the view port. You can drag the pad to move the view port around (that is, to perform 2D scrolling). This example also includes a crosshair track cursor with dynamic labels on the x-axis and y-axis showing the mouse cursor position, and an image map for data point tooltips.

For Web Applications

Zooming and Scrolling Framework (Web)
Description of the ChartDirector Zooming and Scroll Framework for web applications.

Simple Zooming and Scrolling (Web)
This sample program demonstrates a simple zoomable and scrollable chart with tooltips, using mouse click and drag to control zooming and scrolling.

Zooming and Scrolling with Track Line (Web)
Besides using mouse click and drag for zooming and scrolling, this example has buttons for jumping immediately to display data for the last 30 days, last 90 days, last year or all time. There are check boxes to select the data series to plot, and an update button to immediately update the chart. In addition, the chart includes a track cursor that updates the legend dynamically to display the data values as the mouse cursor moves over the chart.

XY Zooming and Scrolling (Web)
This example demonstrates zooming and scrolling in both horizontal and vertical directions. In addition to using mouse click and drag, this example has a "navigation pad" which can be thought as a representation of the view port. You can drag the pad to move the view port around (that is, to perform 2D scrolling).


Zooming and Scrolling Framework (Windows)

Zooming and Scrolling Framework (Windows)

NOTE: This section describes Zooming and Scrolling Framework for Windows applications only. For web applications, please refer to Zooming and Scrolling Framework (Web).

Introduction

The ChartDirector Zooming and Scrolling Framework is a framework for "logical zooming" of charts. "Logical zooming" means the chart is plotted with more details as it is zoomed in, but the chart objects do not necessary become bigger. For example, the font size, line width, symbol size, etc, may remain the same. The chart may even change type or data when it is zoomed in. For example, for a finance chart, it may start as a daily candlestick chart when the time range is long, and becomes a realtime intraday line chart when zoomed to one day.

The main elements of the ChartDirector Zooming and Scrolling Framework include a click and drag user interface to control zooming and scrolling, and a set of methods to manage axis scales. To implement a zoomable and scrollable chart, the charting code would need to be written to create the required chart type based on the axis scales.

The View Port

In the ChartDirector Zooming and Scrolling framework, the view port is used to determine which part of the data range should be plotted.

The view port can be imagined as a rectangular window over the entire XY data range. For example, suppose the full data range is 10 years in the horizontal direction. A view port width of 0.1 means only 10% of the horizontal data range should be plotted. In other words, the chart is zoomed in so that only 1 year of data is visible. The view port left side will determine exactly which year of data that is visible.

The view port position and size can be get and set using the following methods. The full data range is always assumed to be 0 to 1. So the view port position and size should be between 0 to 1.

Method | Description
ChartViewer.getViewPortLeft | Gets the position of the left side of the view port.
ChartViewer.setViewPortLeft | Sets the position of the left side of the view port.
ChartViewer.getViewPortTop | Gets the position of the top side of the view port.
ChartViewer.setViewPortTop | Sets the position of the top side of the view port.
ChartViewer.getViewPortWidth | Gets the width of the view port.
ChartViewer.setViewPortWidth | Sets the width of the view port.
ChartViewer.getViewPortHeight | Gets the height of the view port.
ChartViewer.setViewPortHeight | Sets the height of the view port.

The Zoom and Scroll User Interface

The ChartViewer control allows using mouse actions on the chart to control zooming and scrolling. Several mouse usage modes are supported, including drag to scroll, drag to select a region to zoom into, click to zoom in, and click to zoom out. They can be selected using ChartViewer.setMouseUsage. The zooming and scrolling direction can be horizontal only, vertical only, or both, configurable using ChartViewer.setZoomDirection and ChartViewer.setScrollDirection.

When the user performs zooming or scrolling operations, ChartViewer will update the view port to reflect the new visible region. It will then fire the ViewPortListener.viewPortChanged event . The event handler can then redraw the chart.

Zoom and Scroll with External Controls

In addition to using mouse actions on the plot area, it is often desirable to have other ways to control zooming and scrolling. For example, in finance charts, there are often buttons that allow the user to jump to the last 30 days of data, which are essentially a type of zooming and scrolling. Sometimes people would like to use scroll bar controls for scrolling and mouse wheel for zooming.

To perform zooming and scrolling using external controls, the controls can update the view port and then fire ViewPortChanged events by using ChartViewer.updateViewPort. For example, if a scroll bar is used for scrolling, in event handler of the scroll bar, it may update the view port to reflect the current scroll bar position, and then call ChartViewer.updateViewPort.

The ViewPortChanged Event

The ViewPortListener.viewPortChanged event occurs when the view port is changed. In the simplest case, the event handler just needs to call the charting code to redraw the chart to reflect the changed view port.

If external controls are used, they may need to be updated to reflect the view port. For example, suppose the user can drag the chart or drag a scroll bar to scroll the chart. If the user drags the chart, the scroll bar would need to be updated too to reflect the new view port position.

In zooming and scrolling, the view port events can be "intermediate events". For example, in "drag to scroll", as the user drags the mouse, the view port will be updated rapidly and generate a lot of ViewPortChanged events. These events are "intermediate events" because the view port is still changing. When the user finishes dragging and releases the mouse, ChartDirector will fire a ViewPortChanged event. Only this "final event" corresponds to a stable view port.

To efficiently handle intermediate events, the ViewPortChanged event handler is called with two boolean flags - needUpdateChart and needUpdateImageMap - to determine if the chart and/or image map needs to be updated. For intermediate events, ChartDirector will indicate only the chart needs update. For the final event, ChartDirector will indicate that the image map needs update. It may indicate the chart needs update if the view port has changed between the last intermediate event and the final event.

If external controls are used to control zooming and scrolling and the chart requires image map, it is suggested the external controls set the needUpdateChart and needUpdateImageMap flags properly when calling ChartViewer.updateViewPort. However, for some controls, it may be impossible to distinguish between intermediate and final events. One way to handle this case is to delay updating the image map until the mouse moves over the chart. It is because the image map is for configuring hot spots on the chart, so it is not needed until the mouse is over the chart.

Managing Axis Scale

The view port always assumes the full data range to be 0 to 1. In practice, a chart can have multiple x-axes and y-axes, using a combination of date/time, linear and logarithmic scales.

To facilitate conversion between the view port and the axis scale, ChartDirector includes a number of methods as follows:

Method | Description
ChartViewer.setFullRange | Defines the full range of a view port data scale.
ChartViewer.getValueAtViewPort | Converts a view port coordinate to a value of the specified data scale.
ChartViewer.getViewPortAtValue | Converts a value of the specified data scale to a view port coordinate.
ChartViewer.syncLinearAxisWithViewPort | Synchronizes a linear Axis with the part of the data scale in view port.
ChartViewer.syncLogAxisWithViewPort | Synchronizes a logarithmic Axis with the part of the data scale in view port.
ChartViewer.syncDateAxisWithViewPort | Synchronizes a date/time Axis with the part of the data scale in view port.

In typical usage, ChartViewer.setFullRange is used to define the full data ranges for the axes in the chart. ChartViewer.getValueAtViewPort and ChartViewer.getViewPortAtValue can then be used to map between data values and view port positions. ChartViewer.syncLinearAxisWithViewPort, ChartViewer.syncLogAxisWithViewPort and ChartViewer.syncDateAxisWithViewPort can be used to synchronize the axis scale with the view port position.

If ChartViewer.syncLinearAxisWithViewPort, ChartViewer.syncLogAxisWithViewPort or ChartViewer.syncDateAxisWithViewPort is called without first defining the full data range, ChartDirector will automatically configure the axis scale based on the data in the chart, and assume it to be the full data range. This is useful if the full data range is not known but must be inferred from the data.

Zooming and Scrolling Examples

Sample Code | Description
Simple Zooming and Scrolling (Windows) | A simple zoomable and scrollable chart with tooltips, using mouse click and drag to control zooming and scrolling.
Zooming and Scrolling with Track Line (1) (Windows) | In addition to using mouse click and drag, this example demonstrates using a scroll bar for scrolling, and mouse wheel for zooming. It also includes a track cursor that updates the legend dynamically to display the data values as the mouse cursor moves over the chart.
Zooming and Scrolling with Track Line (2) (Windows) | This example extends Zooming and Scrolling with Track Line (1) (Windows) by adding two date picker controls. The user can use them to change the start and end dates of the chart. Conversely, if the start and end dates of the chart are changed by other means (such as using mouse drag to scroll/zoom, mouse wheel or using the scroll bar), the date picker controls will be updated.
XY Zooming and Scrolling (Windows) | This example demonstrates zooming and scrolling in both horizontal and vertical directions. In addition to using mouse click and drag, this example demonstrates using a slider and the mouse wheel to control zooming. There is also a "navigation pad" which can be thought as a representation of the view port. You can drag the pad to move the view port around (that is, to perform 2D scrolling). This example also includes a crosshair track cursor with dynamic labels on the x-axis and y-axis showing the mouse cursor position, and an image map for data point tooltips.


Simple Zooming and Scrolling (Windows)

Simple Zooming and Scrolling (Windows)

NOTE: This section describes Simple Zooming and Scrolling for Windows applications only. For web applications, please refer to Simple Zooming and Scrolling (Web).

This sample program demonstrates simple zoomable and scrollable chart with tooltips, using mouse click and drag to control zooming and scrolling.

The main source code listing of this sample program is included at the end of this section. The code consists of the following main parts:

  • Initialization: It loads data into memory and initializes the ChartViewer.

  • The ViewPortListener.viewPortChanged event handler: It simply updates the chart and the image map.

  • drawChart: This is the main charting code. It first gets the visible data range from the view port using ChartViewer.getValueAtViewPort. Then it gets the data in that data range. After that it plots the chart as usual, with the x-axis configured to synchronize with the view port using ChartViewer.syncDateAxisWithViewPort.

Source Code Listing

[Java Version] javademo/simplezoomscroll.java
import ChartDirector.*;
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class simplezoomscroll extends JFrame implements DemoModule
{
    // Data arrays for the scrollable / zoomable chart.
    private Date[] timeStamps;
    private double[] dataSeriesA;
    private double[] dataSeriesB;
    private double[] dataSeriesC;

    // Will set to true at the end of initialization
    private boolean hasFinishedInitialization;

    //
    // Controls in the JFrame
    //
    private ChartViewer chartViewer1;
    private JButton pointerPB;
    private JButton zoomInPB;
    private JButton zoomOutPB;

    //
    // The main method to allow this demo to run as a standalone program.
    //
    public static void main(String args[])
    {
        simplezoomscroll demo = new simplezoomscroll();
        demo.setDefaultCloseOperation(EXIT_ON_CLOSE);
        demo.setupFrame();
        demo.setVisible(true);
    }

    //
    // Set up the JFrame
    //
    private void setupFrame()
    {
        // Do nothing if already initialized
        if (hasFinishedInitialization)
            return;

        // Set JFrame title to name of this demo program
        setTitle(toString());
        setResizable(false);

        // Top label bar
        JLabel topLabel = new JLabel("Advanced Software Engineering");
        topLabel.setForeground(new java.awt.Color(255, 255, 51));
        topLabel.setBackground(new java.awt.Color(0, 0, 128));
        topLabel.setBorder(new javax.swing.border.EmptyBorder(2, 0, 2, 5));
        topLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        topLabel.setOpaque(true);
        getContentPane().add(topLabel, java.awt.BorderLayout.NORTH);

        // Left panel
         JPanel leftPanel = new JPanel(null);
        leftPanel.setBorder(javax.swing.BorderFactory.createRaisedBevelBorder());

        // Pointer push button
        pointerPB = new JButton("Pointer", loadImageIcon("pointer.gif"));
        pointerPB.setHorizontalAlignment(SwingConstants.LEFT);
        pointerPB.setMargin(new Insets(5, 5, 5, 5));
        pointerPB.addActionListener(new ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt)    {
                pointerPB_Clicked();
            }});
        leftPanel.add(pointerPB).setBounds(1, 0, 148, 24);

        // Zoom In push button
        zoomInPB = new JButton("Zoom In", loadImageIcon("zoomin.gif"));
        zoomInPB.setHorizontalAlignment(SwingConstants.LEFT);
        zoomInPB.setMargin(new Insets(5, 5, 5, 5));
        zoomInPB.addActionListener(new ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt)    {
                zoomInPB_Clicked();
            }});
        leftPanel.add(zoomInPB).setBounds(1, 24, 148, 24);

        // Zoom out push button
        zoomOutPB = new JButton("Zoom Out", loadImageIcon("zoomout.gif"));
        zoomOutPB.setHorizontalAlignment(SwingConstants.LEFT);
        zoomOutPB.setMargin(new Insets(5, 5, 5, 5));
        zoomOutPB.addActionListener(new ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt)    {
                zoomOutPB_Clicked();
            }});
        leftPanel.add(zoomOutPB).setBounds(1, 48, 148, 24);

        // Total expected panel size
        leftPanel.setPreferredSize(new Dimension(150, 264));

        // Chart Viewer
        chartViewer1 = new ChartViewer();
        chartViewer1.setBackground(new java.awt.Color(255, 255, 255));
        chartViewer1.setOpaque(true);
        chartViewer1.setPreferredSize(new Dimension(616, 316));
        chartViewer1.setHorizontalAlignment(SwingConstants.CENTER);
        chartViewer1.addViewPortListener(new ViewPortAdapter() {
            public void viewPortChanged(ViewPortChangedEvent e) {
                chartViewer1_ViewPortChanged(e);
            }
        });

        // Put the ChartViewer in the right panel
        JPanel rightPanel = new JPanel(new BorderLayout());
        rightPanel.add(chartViewer1, java.awt.BorderLayout.CENTER);

        // Put the leftPanel and rightPanel on the JFrame
        getContentPane().add(leftPanel, java.awt.BorderLayout.WEST);
        getContentPane().add(rightPanel, java.awt.BorderLayout.CENTER);

        // Set all UI fonts (except labels)
        Font uiFont = new Font("Dialog", Font.PLAIN, 11);
        for (int i = 0; i < leftPanel.getComponentCount(); ++i)
        {
            Component c = leftPanel.getComponent(i);
            if (!(c instanceof JLabel))
                c.setFont(uiFont);
        }

        //
        // At this point, the user interface layout has been completed.
        // Can load data and plot chart now.
        //

        // Load the data
        loadData();

        // Initialize the ChartViewer
        initChartViewer(chartViewer1);

        // Trigger a view port update to draw chart.
        pack();
        hasFinishedInitialization = true;
        chartViewer1.updateViewPort(true, true);
    }

    //
    // A utility to load an image icon from the Java class path
    //
    private ImageIcon loadImageIcon(String path)
    {
        try { return new ImageIcon(getClass().getClassLoader().getResource(path)); }
        catch (Exception e) { return null; }
    }

    //
    // Load the data
    //
    private void loadData()
    {
        // In this example, we just use random numbers as data.
        RanSeries r = new RanSeries(127);
        timeStamps = r.getDateSeries(1827, new GregorianCalendar(2007, 0, 1).getTime(), 86400);
        dataSeriesA = r.getSeries2(1827, 150, -10, 10);
        dataSeriesB = r.getSeries2(1827, 200, -10, 10);
        dataSeriesC = r.getSeries2(1827, 250, -8, 8);
    }

    //
    // Initialize the WinChartViewer
    //
    private void initChartViewer(ChartViewer viewer)
    {
        // Set the full x range to be the duration of the data
        viewer.setFullRange("x", timeStamps[0], timeStamps[timeStamps.length - 1]);

        // Initialize the view port to show the latest 20% of the time range
        viewer.setViewPortWidth(0.2);
        viewer.setViewPortLeft(1 - viewer.getViewPortWidth());

        // Set the maximum zoom to 10 points
        viewer.setZoomInWidthLimit(10.0 / timeStamps.length);

        // Initially set the mouse usage to "Pointer" mode (Drag to Scroll mode)
        pointerPB.doClick();
    }

    //
    // The ViewPortChanged event handler. This event occurs if the user scrolls or zooms in
    // or out the chart by dragging or clicking on the chart. It can also be triggered by
    // calling ChartViewer.updateViewPort.
    //
    private void chartViewer1_ViewPortChanged(ViewPortChangedEvent e)
    {
        if (e.needUpdateChart())
            drawChart(chartViewer1);
        if (e.needUpdateImageMap())
            updateImageMap(chartViewer1);
    }

    //
    // Draw the chart.
    //
    private void drawChart(ChartViewer viewer)
    {
        // Get the start date and end date that are visible on the chart.
        Date viewPortStartDate = Chart.NTime(viewer.getValueAtViewPort("x", viewer.getViewPortLeft()));
        Date viewPortEndDate = Chart.NTime(viewer.getValueAtViewPort("x", viewer.getViewPortLeft() +
            viewer.getViewPortWidth()));

        // Get the array indexes that corresponds to the visible start and end dates
        int startIndex = (int)Math.floor(Chart.bSearch(timeStamps, viewPortStartDate));
        int endIndex = (int)Math.ceil(Chart.bSearch(timeStamps, viewPortEndDate));
        int noOfPoints = endIndex - startIndex + 1;

        // Extract the part of the data array that are visible.
        Date[] viewPortTimeStamps = (Date[])Chart.arraySlice(timeStamps, startIndex, noOfPoints);
        double[] viewPortDataSeriesA = (double[])Chart.arraySlice(dataSeriesA, startIndex, noOfPoints);
        double[] viewPortDataSeriesB = (double[])Chart.arraySlice(dataSeriesB, startIndex, noOfPoints);
        double[] viewPortDataSeriesC = (double[])Chart.arraySlice(dataSeriesC, startIndex, noOfPoints);

        //
        // At this stage, we have extracted the visible data. We can use those data to plot the chart.
        //

        //================================================================================
        // 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.
        XYChart c = new XYChart(600, 300, 0xf0f0ff, 0, 1);
        c.setRoundedFrame();

        // Re-cycle the resources of the existing chart, if any. This can improve performance
        // by reducing the frequency of garbage collections.
        c.recycle(viewer.getChart());

        // Set the plotarea at (52, 60) and of size 520 x 205 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(52, 60, 520, 205, 0xffffff, -1, -1, 0xcccccc, 0xcccccc);

        // As the data can lie outside the plotarea in a zoomed chart, we need to enable clipping.
        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("Simple Zooming and Scrolling", "Times New Roman Bold Italic", 15
            ).setBackground(0xccccff, 0x0, Chart.glassEffect());

        // 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(Chart.Transparent, Chart.Transparent);

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

        // Add a title to the y-axis
        c.yAxis().setTitle("Price (USD)", "Arial Bold", 9);

        //================================================================================
        // Add data to chart
        //================================================================================

        //
        // In this example, we represent the data by lines. You may modify the code below to use other
        // representations (areas, scatter plot, etc).
        //

        // Add a line layer for the lines, using a line width of 2 pixels
        LineLayer layer = c.addLineLayer2();
        layer.setLineWidth(2);

        // In this demo, we do not have too many data points. In real code, the chart may contain a lot
        // of data points when fully zoomed out - much more than the number of horizontal pixels in this
        // plot area. So it is a good idea to use fast line mode.
        layer.setFastLineMode();

        // Now we add the 3 data series to a line layer, using the color red (ff0000), green (00cc00)
        // and blue (0000ff)
        layer.setXData(viewPortTimeStamps);
        layer.addDataSet(viewPortDataSeriesA, 0xff0000, "Product Alpha");
        layer.addDataSet(viewPortDataSeriesB, 0x00cc00, "Product Beta");
        layer.addDataSet(viewPortDataSeriesC, 0x0000ff, "Product Gamma");

        //================================================================================
        // Configure axis scale and labelling
        //================================================================================

        // Set the x-axis as a date/time axis with the scale according to the view port x range.
        viewer.syncDateAxisWithViewPort("x", c.xAxis());

        // In this demo, we rely on ChartDirector to auto-label the axis. We ask ChartDirector to ensure
        // the x-axis labels are at least 75 pixels apart to avoid too many labels.
        c.xAxis().setTickDensity(75);

        //================================================================================
        // Output the chart
        //================================================================================

        viewer.setChart(c);
    }

    //
    // Update the image map
    //
    private void updateImageMap(ChartViewer viewer)
    {
        // Include tool tip for the chart
        if (viewer.getImageMap() == null)
        {
            viewer.setImageMap(viewer.getChart().getHTMLImageMap("clickable", "",
                "title='[{dataSetName}] {x|mmm dd, yyyy}: USD {value|2}'"));
        }
    }

    //
    // Click event for the pointerPB.
    //
    private void pointerPB_Clicked()
    {
        pointerPB.setBackground(new Color(0x80, 0xff, 0x80));
        zoomInPB.setBackground(null);
        zoomOutPB.setBackground(null);
        chartViewer1.setMouseUsage(Chart.MouseUsageScrollOnDrag);
    }

    //
    // Click event for the zoomInPB.
    //
    private void zoomInPB_Clicked()
    {
        pointerPB.setBackground(null);
        zoomInPB.setBackground(new Color(0x80, 0xff, 0x80));
        zoomOutPB.setBackground(null);
        chartViewer1.setMouseUsage(Chart.MouseUsageZoomIn);
    }

    //
    // Click event for the zoomOutPB.
    //
    private void zoomOutPB_Clicked()
    {
        pointerPB.setBackground(null);
        zoomInPB.setBackground(null);
        zoomOutPB.setBackground(new Color(0x80, 0xff, 0x80));
        chartViewer1.setMouseUsage(Chart.MouseUsageZoomOut);
    }

    //
    // Implementation of the DemoModule interface to allow this demo to run inside the
    // ChartDirectorDemo browser
    //

    // Name of demo program
    public String toString()
    {
        return "Simple Zooming and Scrolling";
    }

    // Number of charts produced in this demo
    public int getNoOfCharts()
    {
        // This demo open its own frame instead of using the right pane of the ChartDirectorDemo
        // browser for display, so we just load the frame, then returns 0.
        setupFrame();
        setVisible(true);
        return 0;
    }

    // Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // do nothing, as the ChartDirectorDemo browser right pane is not used
    }
}


Zooming and Scrolling with Track Line (1) (Windows)

Zooming and Scrolling with Track Line (1) (Windows)

NOTE: This section describes Zooming and Scrolling with Track Line for Windows applications only. For web applications, please refer to Zooming and Scrolling with Track Line (Web).

In addition to using mouse click and drag, this example demonstrates using a scroll bar for scrolling, and mouse wheel for zooming. It also includes a track cursor that updates the legend dynamically to display the data values as the mouse cursor moves over the chart.

The main source code listing of this sample program is included at the end of this section. The code consists of the following main parts:

  • Initialization: It loads data into memory and initializes the ChartViewer.

  • The ViewPortListener.viewPortChanged event handler: When the view port changed, the following things need to be updated - the scroll bar, the chart and the track cursor.

  • drawChart: This is the main charting code. It first gets the visible data range from the view port using ChartViewer.getValueAtViewPort. Then it gets the data in that data range. After that it plots the chart as usual, with the x-axis configured to synchronize with the view port using ChartViewer.syncDateAxisWithViewPort. In this sample program, Axis.setFormatCondition, Axis.setMultiFormat and Axis.setMultiFormat2 are used to choose select different x-axis label format depending on the axis scale.

  • Scroll bar handling code: When the scroll bar moves, the view port will be updated to reflect the scroll bar position and a ViewPortListener.viewPortChanged event will be fired.

  • Mouse wheel handling code: When the mouse wheel moves, the view port will be updated to reflect zooming in or out, and a ViewPortListener.viewPortChanged event will be fired.

  • Track Cursor drawing code: This is essentially the same as the track cursor drawing code in Track Line with Legend (Windows). Please refer to that example for the explanation of the code.

Source Code Listing

[Java Version] javademo/zoomscrolltrack.java
import ChartDirector.*;
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class zoomscrolltrack extends JFrame implements DemoModule
{
    // Data arrays for the scrollable / zoomable chart.
    private Date[] timeStamps;
    private double[] dataSeriesA;
    private double[] dataSeriesB;
    private double[] dataSeriesC;

    // The earliest date and the duration in seconds for horizontal scrolling
    private Date minDate;
    private double dateRange;

    // The vertical range of the chart for vertical scrolling
    private double maxValue;
    private double minValue;

    // The current visible duration of the view port in seconds
    private double currentDuration = 360 * 86400;
    // In this demo, the maximum zoom-in is set to 10 days
    private double minDuration = 10 * 86400;

    // Will set to true at the end of initialization
    private boolean hasFinishedInitialization;

    //
    // Controls in the JFrame
    //
    private JButton pointerPB;
    private JButton zoomInPB;
    private JButton zoomOutPB;
    private ChartViewer chartViewer1;
    private JScrollBar hScrollBar1;

    //
    // The main method to allow this demo to run as a standalone program.
    //
    public static void main(String args[])
    {
        zoomscrolltrack demo = new zoomscrolltrack();
        demo.setDefaultCloseOperation(EXIT_ON_CLOSE);
        demo.setupFrame();
        demo.setVisible(true);
    }

    //
    // Set up the JFrame
    //
    private void setupFrame()
    {
        // Do nothing if already initialized
        if (hasFinishedInitialization)
            return;

        // Set JFrame title to name of this demo program
         setTitle(toString());
        setResizable(false);

        // Top label bar
        JLabel topLabel = new JLabel("Advanced Software Engineering");
        topLabel.setForeground(new java.awt.Color(255, 255, 51));
        topLabel.setBackground(new java.awt.Color(0, 0, 128));
        topLabel.setBorder(new javax.swing.border.EmptyBorder(2, 0, 2, 5));
        topLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        topLabel.setOpaque(true);
        getContentPane().add(topLabel, java.awt.BorderLayout.NORTH);

        // Left panel
         JPanel leftPanel = new JPanel(null);
        leftPanel.setBorder(javax.swing.BorderFactory.createRaisedBevelBorder());

        // Pointer push button
        pointerPB = new JButton("Pointer", loadImageIcon("pointer.gif"));
        pointerPB.setHorizontalAlignment(SwingConstants.LEFT);
        pointerPB.setMargin(new Insets(5, 5, 5, 5));
        pointerPB.addActionListener(new ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt)    {
                pointerPB_Clicked();
            }});
        leftPanel.add(pointerPB).setBounds(1, 0, 148, 24);

        // Zoom In push button
        zoomInPB = new JButton("Zoom In", loadImageIcon("zoomin.gif"));
        zoomInPB.setHorizontalAlignment(SwingConstants.LEFT);
        zoomInPB.setMargin(new Insets(5, 5, 5, 5));
        zoomInPB.addActionListener(new ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt)    {
                zoomInPB_Clicked();
            }});
        leftPanel.add(zoomInPB).setBounds(1, 24, 148, 24);

        // Zoom out push button
        zoomOutPB = new JButton("Zoom Out", loadImageIcon("zoomout.gif"));
        zoomOutPB.setHorizontalAlignment(SwingConstants.LEFT);
        zoomOutPB.setMargin(new Insets(5, 5, 5, 5));
        zoomOutPB.addActionListener(new ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt)    {
                zoomOutPB_Clicked();
            }});
        leftPanel.add(zoomOutPB).setBounds(1, 48, 148, 24);

        // Total expected panel size
        leftPanel.setPreferredSize(new Dimension(150, 264));

        // Chart Viewer
        chartViewer1 = new ChartViewer();
        chartViewer1.setBackground(new java.awt.Color(255, 255, 255));
        chartViewer1.setOpaque(true);
        chartViewer1.setPreferredSize(new Dimension(656, 366));
        chartViewer1.setHorizontalAlignment(SwingConstants.CENTER);
        chartViewer1.setHotSpotCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        chartViewer1.addViewPortListener(new ViewPortAdapter() {
            public void viewPortChanged(ViewPortChangedEvent e) {
                chartViewer1_ViewPortChanged(e);
            }
        });
        chartViewer1.addTrackCursorListener(new TrackCursorAdapter() {
            public void mouseMovedPlotArea(MouseEvent e) {
                chartViewer1_MouseMovedPlotArea(e);
            }
        });
        chartViewer1.addMouseWheelListener(new MouseWheelListener() {
            public void mouseWheelMoved(MouseWheelEvent e) {
                chartViewer1_MouseWheel(e);
            }
        });

        // Horizontal Scroll bar
        hScrollBar1 = new JScrollBar(JScrollBar.HORIZONTAL, 0, 100000000, 0, 1000000000);
        hScrollBar1.addAdjustmentListener(new AdjustmentListener() {
            public void adjustmentValueChanged(AdjustmentEvent e) {
                hScrollBar1_ValueChanged();
            }
        });

        // Put the ChartViewer and the scroll bars in the right panel
        JPanel rightPanel = new JPanel(new BorderLayout());
        rightPanel.add(chartViewer1, java.awt.BorderLayout.CENTER);
        rightPanel.add(hScrollBar1, java.awt.BorderLayout.SOUTH);

        // Put the leftPanel and rightPanel on the JFrame
        getContentPane().add(leftPanel, java.awt.BorderLayout.WEST);
        getContentPane().add(rightPanel, java.awt.BorderLayout.CENTER);

        // Set all UI fonts (except labels)
        Font uiFont = new Font("Dialog", Font.PLAIN, 11);
        for (int i = 0; i < leftPanel.getComponentCount(); ++i)
        {
            Component c = leftPanel.getComponent(i);
            if (!(c instanceof JLabel))
                c.setFont(uiFont);
        }

        //
        // At this point, the user interface layout has been completed.
        // Can load data and plot chart now.
        //

        // Load the data
        loadData();

        // Initialize the ChartViewer
        initChartViewer(chartViewer1);

        // Trigger a view port update to draw chart.
        pack();
        hasFinishedInitialization = true;
        chartViewer1.updateViewPort(true, true);
    }

    //
    // A utility to load an image icon from the Java class path
    //
    private ImageIcon loadImageIcon(String path)
    {
        try { return new ImageIcon(getClass().getClassLoader().getResource(path)); }
        catch (Exception e) { return null; }
    }

    //
    // Load the data
    //
    private void loadData()
    {
        // In this example, we just use random numbers as data.
        RanSeries r = new RanSeries(127);
        timeStamps = r.getDateSeries(1827, new GregorianCalendar(2007, 0, 1).getTime(), 86400);
        dataSeriesA = r.getSeries2(1827, 150, -10, 10);
        dataSeriesB = r.getSeries2(1827, 200, -10, 10);
        dataSeriesC = r.getSeries2(1827, 250, -8, 8);
    }

    //
    // Initialize the WinChartViewer
    //
    private void initChartViewer(ChartViewer viewer)
    {
        // Set the full x range to be the duration of the data
        viewer.setFullRange("x", timeStamps[0], timeStamps[timeStamps.length - 1]);

        // Initialize the view port to show the latest 20% of the time range
        viewer.setViewPortWidth(0.2);
        viewer.setViewPortLeft(1 - viewer.getViewPortWidth());

        // Set the maximum zoom to 10 points
        viewer.setZoomInWidthLimit(10.0 / timeStamps.length);

        // Initially set the mouse usage to "Pointer" mode (Drag to Scroll mode)
        pointerPB.doClick();
    }

    //
    // The ViewPortChanged event handler. This event occurs if the user scrolls or zooms in
    // or out the chart by dragging or clicking on the chart. It can also be triggered by
    // calling WinChartViewer.updateViewPort.
    //
    private void chartViewer1_ViewPortChanged(ViewPortChangedEvent e)
    {
        // In addition to updating the chart, we may also need to update other controls that
        // changes based on the view port.
        updateControls(chartViewer1);

        // Update the chart if necessary
        if (e.needUpdateChart())
            drawChart(chartViewer1);

        // We need to update the track line too. If the mouse is moving on the chart (eg. if
        // the user drags the mouse on the chart to scroll it), the track line will be updated
        // in the MouseMovePlotArea event. Otherwise, we need to update the track line here.
        if (!chartViewer1.isInMouseMoveEvent())
        {
            trackLineLegend((XYChart)chartViewer1.getChart(), chartViewer1.getPlotAreaMouseX());
            chartViewer1.updateDisplay();
        }
    }

    //
    // Update controls when the view port changed
    //
    private void updateControls(ChartViewer viewer)
    {
        // In this demo, we need to update the scroll bar to reflect the view port position and
        // width of the view port.
        hScrollBar1.setEnabled(chartViewer1.getViewPortWidth() < 1);
        hScrollBar1.setVisibleAmount((int)Math.ceil(chartViewer1.getViewPortWidth() *
            (hScrollBar1.getMaximum() - hScrollBar1.getMinimum())));
        hScrollBar1.setBlockIncrement(hScrollBar1.getVisibleAmount());
        hScrollBar1.setUnitIncrement((int)Math.ceil(hScrollBar1.getVisibleAmount() * 0.1));
        hScrollBar1.setValue((int)Math.round(chartViewer1.getViewPortLeft() *
            (hScrollBar1.getMaximum() - hScrollBar1.getMinimum())) + hScrollBar1.getMinimum());
    }

    //
    // Draw the chart.
    //
    private void drawChart(ChartViewer viewer)
    {
        // Get the start date and end date that are visible on the chart.
        Date viewPortStartDate = Chart.NTime(viewer.getValueAtViewPort("x", viewer.getViewPortLeft()));
        Date viewPortEndDate = Chart.NTime(viewer.getValueAtViewPort("x", viewer.getViewPortLeft() +
            viewer.getViewPortWidth()));

        // Get the array indexes that corresponds to the visible start and end dates
        int startIndex = (int)Math.floor(Chart.bSearch(timeStamps, viewPortStartDate));
        int endIndex = (int)Math.ceil(Chart.bSearch(timeStamps, viewPortEndDate));
        int noOfPoints = endIndex - startIndex + 1;

        // Extract the part of the data array that are visible.
        Date[] viewPortTimeStamps = (Date[])Chart.arraySlice(timeStamps, startIndex, noOfPoints);
        double[] viewPortDataSeriesA = (double[])Chart.arraySlice(dataSeriesA, startIndex, noOfPoints);
        double[] viewPortDataSeriesB = (double[])Chart.arraySlice(dataSeriesB, startIndex, noOfPoints);
        double[] viewPortDataSeriesC = (double[])Chart.arraySlice(dataSeriesC, startIndex, noOfPoints);

        //
        // At this stage, we have extracted the visible data. We can use those data to plot the chart.
        //

        //================================================================================
        // Configure overall chart appearance.
        //================================================================================

        // Create an XYChart object of size 640 x 350 pixels
        XYChart c = new XYChart(640, 350);

        // Re-cycle the resources of the existing chart, if any. This can improve performance
        // by reducing the frequency of garbage collections.
        c.recycle(chartViewer1.getChart());

        // Set the plotarea at (55, 55) with width 80 pixels less than chart width, and height 90 pixels
        // less than chart height. Use a vertical gradient from light blue (f0f6ff) to sky blue (a0c0ff)
        // as background. Set border to transparent and grid lines to white (ffffff).
        c.setPlotArea(55, 55, c.getWidth() - 80, c.getHeight() - 90, c.linearGradientColor(0, 55, 0,
            c.getHeight() - 35, 0xf0f6ff, 0xa0c0ff), -1, Chart.Transparent, 0xffffff, 0xffffff);

        // As the data can lie outside the plotarea in a zoomed chart, we need enable clipping.
        c.setClipping();

        // Add a title to the chart using 18 pts Times New Roman Bold Italic font
        c.addTitle("   Zooming and Scrolling with Track Line (1)", "Times New Roman Bold Italic", 18);

        // Set legend icon style to use line style icon, sized for 8pt font
        c.getLegend().setLineStyleKey();
        c.getLegend().setFontSize(8);

        // Set the axis stem to transparent
        c.xAxis().setColors(Chart.Transparent);
        c.yAxis().setColors(Chart.Transparent);

        // Add axis title using 10pts Arial Bold Italic font
        c.yAxis().setTitle("Ionic Temperature (C)", "Arial Bold Italic", 10);

        //================================================================================
        // Add data to chart
        //================================================================================

        //
        // In this example, we represent the data by lines. You may modify the code below to use other
        // representations (areas, scatter plot, etc).
        //

        // Add a line layer for the lines, using a line width of 2 pixels
        LineLayer layer = c.addLineLayer2();
        layer.setLineWidth(2);

        // In this demo, we do not have too many data points. In real code, the chart may contain a lot
        // of data points when fully zoomed out - much more than the number of horizontal pixels in this
        // plot area. So it is a good idea to use fast line mode.
        layer.setFastLineMode();

        // Now we add the 3 data series to a line layer, using the color red (ff33333), green (008800)
        // and blue (3333cc)
        layer.setXData(viewPortTimeStamps);
        layer.addDataSet(viewPortDataSeriesA, 0xff3333, "Alpha");
        layer.addDataSet(viewPortDataSeriesB, 0x008800, "Beta");
        layer.addDataSet(viewPortDataSeriesC, 0x3333cc, "Gamma");

        //================================================================================
        // Configure axis scale and labelling
        //================================================================================

        // Set the x-axis as a date/time axis with the scale according to the view port x range.
        viewer.syncDateAxisWithViewPort("x", c.xAxis());

        //
        // In this demo, the time range can be from a few years to a few days. We demonstrate how to set
        // up different date/time format based on the time range.
        //

        // If all ticks are yearly aligned, then we use "yyyy" as the label format.
        c.xAxis().setFormatCondition("align", 360 * 86400);
        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", 30 * 86400);
        c.xAxis().setMultiFormat(Chart.StartOfYearFilter(), "<*font=bold*>{value|mmm yyyy}",
            Chart.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(Chart.StartOfYearFilter(),
            "<*block,halign=left*><*font=bold*>{value|mmm dd<*br*>yyyy}", Chart.StartOfMonthFilter(),
            "<*font=bold*>{value|mmm dd}");
        c.xAxis().setMultiFormat2(Chart.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(Chart.StartOfDayFilter(), "<*font=bold*>{value|hh:nn<*br*>mmm dd}",
            Chart.AllPassFilter(), "{value|hh:nn}");

        //================================================================================
        // Output the chart
        //================================================================================

        viewer.setChart(c);
    }

    //
    // Click event for the pointerPB.
    //
    private void pointerPB_Clicked()
    {
        pointerPB.setBackground(new Color(0x80, 0xff, 0x80));
        zoomInPB.setBackground(null);
        zoomOutPB.setBackground(null);
        chartViewer1.setMouseUsage(Chart.MouseUsageScrollOnDrag);
    }

    //
    // Click event for the zoomInPB.
    //
    private void zoomInPB_Clicked()
    {
        pointerPB.setBackground(null);
        zoomInPB.setBackground(new Color(0x80, 0xff, 0x80));
        zoomOutPB.setBackground(null);
        chartViewer1.setMouseUsage(Chart.MouseUsageZoomIn);
    }

    //
    // Click event for the zoomOutPB.
    //
    private void zoomOutPB_Clicked()
    {
        pointerPB.setBackground(null);
        zoomInPB.setBackground(null);
        zoomOutPB.setBackground(new Color(0x80, 0xff, 0x80));
        chartViewer1.setMouseUsage(Chart.MouseUsageZoomOut);
    }

    //
    // Horizontal ScrollBar ValueChanged event handler
    //
    private void hScrollBar1_ValueChanged()
    {
        if (hasFinishedInitialization && !chartViewer1.isInViewPortChangedEvent())
        {
            // Get the view port left as according to the scroll bar
            double newViewPortLeft = ((double)(hScrollBar1.getValue() - hScrollBar1.getMinimum()))
                / (hScrollBar1.getMaximum() - hScrollBar1.getMinimum());

            // Check if view port has really changed - sometimes the scroll bar may issue redundant
            // value changed events when value has not actually changed.
            if (Math.abs(chartViewer1.getViewPortLeft() - newViewPortLeft) >
                0.00001 * chartViewer1.getViewPortWidth())
            {
                // Set the view port based on the scroll bar
                chartViewer1.setViewPortLeft(newViewPortLeft);

                // Update the chart display without updating the image maps. We delay updating
                // the image map because the chart may still be unstable (still scrolling).
                chartViewer1.updateViewPort(true, false);
            }
        }
    }

    //
    // Mouse Wheel event handler
    //
    private void chartViewer1_MouseWheel(MouseWheelEvent e)
    {
        // We zoom in or out by 10% depending on the mouse wheel direction.
        double rx = e.getWheelRotation() < 0 ? 0.9 : 1 / 0.9;
        double ry = rx;

        // We do not zoom in beyond the zoom in width or height limit.
        rx = Math.max(rx, chartViewer1.getZoomInWidthLimit() / chartViewer1.getViewPortWidth());
        ry = Math.max(ry, chartViewer1.getZoomInWidthLimit()/ chartViewer1.getViewPortHeight());
        if ((rx == 1) && (ry == 1))
            return;

        XYChart c = (XYChart)chartViewer1.getChart();

        //
        // Set the view port position and size so that it is zoom in/out around the mouse by the
        // desired ratio.
        //

        double mouseOffset = (e.getX() - c.getPlotArea().getLeftX()) /
            (double)c.getPlotArea().getWidth();
        chartViewer1.setViewPortLeft(chartViewer1.getViewPortLeft() + mouseOffset * (1 - rx) *
            chartViewer1.getViewPortWidth());
        chartViewer1.setViewPortWidth(chartViewer1.getViewPortWidth() * rx);

        double mouseOffsetY = (e.getY() - c.getPlotArea().getTopY()) /
            (double)c.getPlotArea().getHeight();
        chartViewer1.setViewPortTop(chartViewer1.getViewPortTop() + mouseOffsetY * (1 - ry) *
            chartViewer1.getViewPortHeight());
        chartViewer1.setViewPortHeight(chartViewer1.getViewPortHeight() * ry);

        // Trigger a view port changed event to update the chart
        chartViewer1.updateViewPort(true, false);
    }

    //
    // Draw track cursor when mouse is moving over plotarea
    //
    private void chartViewer1_MouseMovedPlotArea(MouseEvent e)
    {
        ChartViewer viewer = (ChartViewer)e.getSource();
        trackLineLegend((XYChart)viewer.getChart(), viewer.getPlotAreaMouseX());
        viewer.updateDisplay();
    }

    //
    // Draw the track line with legend
    //
    private void trackLineLegend(XYChart c, int mouseX)
    {
        // Clear the current dynamic layer and get the DrawArea object to draw on it.
        DrawArea d = c.initDynamicLayer();

        // The plot area object
        PlotArea plotArea = c.getPlotArea();

        // Get the data x-value that is nearest to the mouse, and find its pixel coordinate.
        double xValue = c.getNearestXValue(mouseX);
        int xCoor = c.getXCoor(xValue);

        // Draw a vertical track line at the x-position
        d.vline(plotArea.getTopY(), plotArea.getBottomY(), xCoor, d.dashLineColor(0x000000, 0x0101));

        // Container to hold the legend entries
        ArrayList legendEntries = new ArrayList();

        // Iterate through all layers to build the legend array
        for (int i = 0; i < c.getLayerCount(); ++i) {
            Layer layer = c.getLayerByZ(i);

            // The data array index of the x-value
            int xIndex = layer.getXIndexOf(xValue);

            // Iterate through all the data sets in the layer
            for (int j = 0; j < layer.getDataSetCount(); ++j) {
                ChartDirector.DataSet dataSet = layer.getDataSetByZ(j);

                // We are only interested in visible data sets with names
                String dataName = dataSet.getDataName();
                int color = dataSet.getDataColor();
                if ((!(dataName == null || dataName.length() == 0)) && (color != Chart.Transparent)) {
                    // Build the legend entry, consist of the legend icon, name and data value.
                    double dataValue = dataSet.getValue(xIndex);
                    legendEntries.add("<*block*>" + dataSet.getLegendIcon() + " " + dataName + ": " + ((
                        dataValue == Chart.NoValue) ? "N/A" : c.formatValue(dataValue, "{value|P4}")) +
                        "<*/*>");

                    // Draw a track dot for data points within the plot area
                    int yCoor = c.getYCoor(dataSet.getPosition(xIndex), dataSet.getUseYAxis());
                    if ((yCoor >= plotArea.getTopY()) && (yCoor <= plotArea.getBottomY())) {
                        d.circle(xCoor, yCoor, 4, 4, color, color);
                    }
                }
            }
        }

        // Create the legend by joining the legend entries
        Collections.reverse(legendEntries);
        String legendText = "<*block,maxWidth=" + plotArea.getWidth() + "*><*block*><*font=Arial Bold*>[" +
            c.xAxis().getFormattedLabel(xValue, "mmm dd, yyyy") + "]<*/*>        " + Chart.stringJoin(
            legendEntries, "        ") + "<*/*>";

        // Display the legend on the top of the plot area
        TTFText t = d.text(legendText, "Arial", 8);
        t.draw(plotArea.getLeftX() + 5, plotArea.getTopY() - 3, 0x000000, Chart.BottomLeft);
    }

    //
    // Implementation of the DemoModule interface to allow this demo to run inside the
    // ChartDirectorDemo browser
    //

    // Name of demo program
    public String toString()
    {
        return "Zoom/Scroll with Track Line";
    }

    // Number of charts produced in this demo
    public int getNoOfCharts()
    {
        // This demo open its own frame instead of using the right pane of the ChartDirectorDemo
        // browser for display, so we just load the frame, then returns 0.
        setupFrame();
        setVisible(true);
        return 0;
    }

    // Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // do nothing, as the ChartDirectorDemo browser right pane is not used
    }
}


Zooming and Scrolling with Track Line (2) (Windows)

Zooming and Scrolling with Track Line (2) (Windows)

This sample program demonstrates a zoomable and scrollable chart controlled with mouse click and drag, as well as with a scroll bar, the mouse wheel, and two date picker controls to pick the start and end dates. It also includes a track cursor that displays dynamic labels next to the data points showing their values as the mouse cursor moves over the chart.

The main source code listing of this sample program is included at the end of this section. The code consists of the following main parts:

  • Initialization: It loads data into memory and initializes the ChartViewer.

  • The ViewPortListener.viewPortChanged event handler: When the view port changed, the following things need to be updated - external controls (including the scroll bar and the date picker controls), the chart and the track cursor.

  • drawChart: This is the main charting code. It first gets the visible data range from the view port using ChartViewer.getValueAtViewPort. Then it gets the data in that data range. After that it plots the chart as usual, with the x-axis configured to synchronize with the view port using ChartViewer.syncDateAxisWithViewPort. In this sample program, Axis.setFormatCondition, Axis.setMultiFormat and Axis.setMultiFormat2 are used to choose select different x-axis label format depending on the axis scale.

  • Scroll bar handling code: When the scroll bar moves, the view port will be updated to reflect the scroll bar position and a ViewPortListener.viewPortChanged event will be fired.

  • Date picker handling code: When the start date or end date is modified by a date picker control, the view port will be updated to reflect the new date range and a ViewPortListener.viewPortChanged event will be fired.

  • Mouse wheel handling code: When the mouse wheel moves, the view port will be updated to reflect zooming in or out, and a ViewPortListener.viewPortChanged event will be fired.

  • Track Cursor drawing code: This is essentially the same as the track cursor drawing code in Track Line with Data Labels (Windows). Please refer to that example for the explanation of the code.

Source Code Listing

[Java Version] javademo/zoomscrolltrack2.java
import ChartDirector.*;
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class zoomscrolltrack2 extends JFrame implements DemoModule
{
    // Data arrays for the scrollable / zoomable chart.
    private Date[] timeStamps;
    private double[] dataSeriesA;
    private double[] dataSeriesB;
    private double[] dataSeriesC;

    // The earliest date and the duration in seconds for horizontal scrolling
    private Date minDate;
    private double dateRange;

    // The vertical range of the chart for vertical scrolling
    private double maxValue;
    private double minValue;

    // The current visible duration of the view port in seconds
    private double currentDuration = 360 * 86400;
    // In this demo, the maximum zoom-in is set to 10 days
    private double minDuration = 10 * 86400;

    // Will set to true at the end of initialization
    private boolean hasFinishedInitialization;

    //
    // Controls in the JFrame
    //
    private JButton pointerPB;
    private JButton zoomInPB;
    private JButton zoomOutPB;
    private JComboBox startYear;
    private JComboBox startMonth;
    private JComboBox startDay;
    private JComboBox endYear;
    private JComboBox endMonth;
    private JComboBox endDay;
    private ChartViewer chartViewer1;
    private JScrollBar hScrollBar1;

    //
    // The main method to allow this demo to run as a standalone program.
    //
    public static void main(String args[])
    {
        zoomscrolltrack2 demo = new zoomscrolltrack2();
        demo.setDefaultCloseOperation(EXIT_ON_CLOSE);
        demo.setupFrame();
        demo.setVisible(true);
    }

    //
    // Set up the JFrame
    //
    private void setupFrame()
    {
        // Do nothing if already initialized
        if (hasFinishedInitialization)
            return;

        // Set JFrame title to name of this demo program
         setTitle(toString());
        setResizable(false);

        // Top label bar
        JLabel topLabel = new JLabel("Advanced Software Engineering");
        topLabel.setForeground(new java.awt.Color(255, 255, 51));
        topLabel.setBackground(new java.awt.Color(0, 0, 128));
        topLabel.setBorder(new javax.swing.border.EmptyBorder(2, 0, 2, 5));
        topLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        topLabel.setOpaque(true);
        getContentPane().add(topLabel, java.awt.BorderLayout.NORTH);

        // Left panel
         JPanel leftPanel = new JPanel(null);
        leftPanel.setBorder(javax.swing.BorderFactory.createRaisedBevelBorder());

        // Pointer push button
        pointerPB = new JButton("Pointer", loadImageIcon("pointer.gif"));
        pointerPB.setHorizontalAlignment(SwingConstants.LEFT);
        pointerPB.setMargin(new Insets(5, 5, 5, 5));
        pointerPB.addActionListener(new ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt)    {
                pointerPB_Clicked();
            }});
        leftPanel.add(pointerPB).setBounds(1, 0, 148, 24);

        // Zoom In push button
        zoomInPB = new JButton("Zoom In", loadImageIcon("zoomin.gif"));
        zoomInPB.setHorizontalAlignment(SwingConstants.LEFT);
        zoomInPB.setMargin(new Insets(5, 5, 5, 5));
        zoomInPB.addActionListener(new ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt)    {
                zoomInPB_Clicked();
            }});
        leftPanel.add(zoomInPB).setBounds(1, 24, 148, 24);

        // Zoom out push button
        zoomOutPB = new JButton("Zoom Out", loadImageIcon("zoomout.gif"));
        zoomOutPB.setHorizontalAlignment(SwingConstants.LEFT);
        zoomOutPB.setMargin(new Insets(5, 5, 5, 5));
        zoomOutPB.addActionListener(new ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt)    {
                zoomOutPB_Clicked();
            }});
        leftPanel.add(zoomOutPB).setBounds(1, 48, 148, 24);

        // Start Date label
        leftPanel.add(new JLabel("Start Date")).setBounds(5, 180, 130, 20);

        // Start Year, Start Month, Start Day combo boxes
        startYear = new JComboBox();
        startMonth = new JComboBox();
        startDay = new JComboBox();
        leftPanel.add(startYear).setBounds(1, 200, 60, 20);
        leftPanel.add(startMonth).setBounds(61, 200, 44, 20);
        leftPanel.add(startDay).setBounds(105, 200, 44, 20);
        ActionListener startDateHandler = new ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                startDate_ValueChanged();
            }};
        startYear.addActionListener(startDateHandler);
        startMonth.addActionListener(startDateHandler);
        startDay.addActionListener(startDateHandler);

        // End Date label
        leftPanel.add(new JLabel("End Date")).setBounds(5, 232, 130, 20);

        // End Year, End Month, End Day combo boxes
        endYear = new JComboBox();
        endMonth = new JComboBox();
        endDay = new JComboBox();
        leftPanel.add(endYear).setBounds(1, 252, 60, 20);
        leftPanel.add(endMonth).setBounds(61, 252, 44, 20);
        leftPanel.add(endDay).setBounds(105, 252, 44, 20);
        ActionListener endDateHandler = new ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                endDate_ValueChanged();
            }};
        endYear.addActionListener(endDateHandler);
        endMonth.addActionListener(endDateHandler);
        endDay.addActionListener(endDateHandler);

        // Total expected panel size
        leftPanel.setPreferredSize(new Dimension(150, 264));

        // Chart Viewer
        chartViewer1 = new ChartViewer();
        chartViewer1.setBackground(new java.awt.Color(255, 255, 255));
        chartViewer1.setOpaque(true);
        chartViewer1.setPreferredSize(new Dimension(656, 366));
        chartViewer1.setHorizontalAlignment(SwingConstants.CENTER);
        chartViewer1.setHotSpotCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        chartViewer1.addViewPortListener(new ViewPortAdapter() {
            public void viewPortChanged(ViewPortChangedEvent e) {
                chartViewer1_ViewPortChanged(e);
            }
        });
        chartViewer1.addTrackCursorListener(new TrackCursorAdapter() {
            public void mouseMovedPlotArea(MouseEvent e) {
                chartViewer1_MouseMovedPlotArea(e);
            }
        });
        chartViewer1.addMouseWheelListener(new MouseWheelListener() {
            public void mouseWheelMoved(MouseWheelEvent e) {
                chartViewer1_MouseWheel(e);
            }
        });

        // Horizontal Scroll bar
        hScrollBar1 = new JScrollBar(JScrollBar.HORIZONTAL, 0, 100000000, 0, 1000000000);
        hScrollBar1.addAdjustmentListener(new AdjustmentListener() {
            public void adjustmentValueChanged(AdjustmentEvent e) {
                hScrollBar1_ValueChanged();
            }
        });

        // Put the ChartViewer and the scroll bars in the right panel
        JPanel rightPanel = new JPanel(new BorderLayout());
        rightPanel.add(chartViewer1, java.awt.BorderLayout.CENTER);
        rightPanel.add(hScrollBar1, java.awt.BorderLayout.SOUTH);

        // Put the leftPanel and rightPanel on the JFrame
        getContentPane().add(leftPanel, java.awt.BorderLayout.WEST);
        getContentPane().add(rightPanel, java.awt.BorderLayout.CENTER);

        // Set all UI fonts (except labels)
        Font uiFont = new Font("Dialog", Font.PLAIN, 11);
        for (int i = 0; i < leftPanel.getComponentCount(); ++i)
        {
            Component c = leftPanel.getComponent(i);
            if (!(c instanceof JLabel))
                c.setFont(uiFont);
        }

        //
        // At this point, the user interface layout has been completed.
        // Can load data and plot chart now.
        //

        // Load the data
        loadData();

        // Initialize date controls to reflect the date range in the data
        initDateControls();

        // Initialize the ChartViewer
        initChartViewer(chartViewer1);

        // Trigger a view port update to draw chart.
        pack();
        hasFinishedInitialization = true;
        chartViewer1.updateViewPort(true, true);
    }

    //
    // A utility to load an image icon from the Java class path
    //
    private ImageIcon loadImageIcon(String path)
    {
        try { return new ImageIcon(getClass().getClassLoader().getResource(path)); }
        catch (Exception e) { return null; }
    }

    //
    // Load the data
    //
    private void loadData()
    {
        // In this example, we just use random numbers as data.
        RanSeries r = new RanSeries(127);
        timeStamps = r.getDateSeries(1827, new GregorianCalendar(2007, 0, 1).getTime(), 86400);
        dataSeriesA = r.getSeries2(1827, 150, -10, 10);
        dataSeriesB = r.getSeries2(1827, 200, -10, 10);
        dataSeriesC = r.getSeries2(1827, 250, -8, 8);
    }

    //
    // Initialize date controls
    //
    private void initDateControls()
    {
        // Set the date range of the startYear and endYear combo boxes to match the scrollable date range.
        GregorianCalendar calendar = new GregorianCalendar();
        calendar.setTime(timeStamps[0]);
        int minYear = calendar.get(Calendar.YEAR);
        calendar.setTime(timeStamps[timeStamps.length - 1]);
        int maxYear = calendar.get(Calendar.YEAR);

        startYear.removeAllItems();
        endYear.removeAllItems();
        for (int i = minYear; i <= maxYear; ++i)
        {
            startYear.addItem(new Integer(i));
            endYear.addItem(new Integer(i));
        }

        // Initialize the startMonth and endMonth combo boxes.
        for (int i = 1; i <= 12; ++i)
        {
            startMonth.addItem(new Integer(i));
            endMonth.addItem(new Integer(i));
        }
    }

    //
    // Initialize the WinChartViewer
    //
    private void initChartViewer(ChartViewer viewer)
    {
        // Set the full x range to be the duration of the data
        viewer.setFullRange("x", timeStamps[0], timeStamps[timeStamps.length - 1]);

        // Initialize the view port to show the latest 20% of the time range
        viewer.setViewPortWidth(0.2);
        viewer.setViewPortLeft(1 - viewer.getViewPortWidth());

        // Set the maximum zoom to 10 points
        viewer.setZoomInWidthLimit(10.0 / timeStamps.length);

        // Initially set the mouse usage to "Pointer" mode (Drag to Scroll mode)
        pointerPB.doClick();
    }

    //
    // The ViewPortChanged event handler. This event occurs if the user scrolls or zooms in
    // or out the chart by dragging or clicking on the chart. It can also be triggered by
    // calling WinChartViewer.updateViewPort.
    //
    private void chartViewer1_ViewPortChanged(ViewPortChangedEvent e)
    {
        // In addition to updating the chart, we may also need to update other controls that
        // changes based on the view port.
        updateControls(chartViewer1);

        // Update the chart if necessary
        if (e.needUpdateChart())
            drawChart(chartViewer1);

        // We need to update the track line too. If the mouse is moving on the chart (eg. if
        // the user drags the mouse on the chart to scroll it), the track line will be updated
        // in the MouseMovedPlotArea event. Otherwise, we need to update the track line here.
        if ((!chartViewer1.isInMouseMoveEvent()) && chartViewer1.isMouseOnPlotArea())
        {
            trackLineLabel((XYChart)chartViewer1.getChart(), chartViewer1.getPlotAreaMouseX());
            chartViewer1.updateDisplay();
        }
    }

    //
    // Update controls when the view port changed
    //
    private void updateControls(ChartViewer viewer)
    {
        // Update the start date and end date control to reflect the view port.
        Date startDate = Chart.NTime(viewer.getValueAtViewPort("x", viewer.getViewPortLeft()));
        setDateCtrl(startDate, startYear, startMonth, startDay);
        Date endDate =  Chart.NTime(viewer.getValueAtViewPort("x", viewer.getViewPortLeft() +
            viewer.getViewPortWidth()));
        setDateCtrl(endDate, endYear, endMonth, endDay);

        // Update the scroll bar to reflect the view port position and width of the view port.
        hScrollBar1.setEnabled(chartViewer1.getViewPortWidth() < 1);
        hScrollBar1.setVisibleAmount((int)Math.ceil(chartViewer1.getViewPortWidth() *
            (hScrollBar1.getMaximum() - hScrollBar1.getMinimum())));
        hScrollBar1.setBlockIncrement(hScrollBar1.getVisibleAmount());
        hScrollBar1.setUnitIncrement((int)Math.ceil(hScrollBar1.getVisibleAmount() * 0.1));
        hScrollBar1.setValue((int)Math.round(chartViewer1.getViewPortLeft() *
            (hScrollBar1.getMaximum() - hScrollBar1.getMinimum())) + hScrollBar1.getMinimum());
    }

    //
    // Sets the year/month/day combo boxes to the given date.
    //
    private void setDateCtrl(Date d, JComboBox year, JComboBox month, JComboBox day)
    {
        GregorianCalendar startYMD = new GregorianCalendar();
        startYMD.setTime(d);

        year.setSelectedItem(new Integer(startYMD.get(Calendar.YEAR)));
        month.setSelectedIndex(startYMD.get(Calendar.MONTH));
        normalizeDateCtrl(year, month, day);
        day.setSelectedIndex(startYMD.get(Calendar.DAY_OF_MONTH) - 1);
    }

    //
    // Normalize the day combo boxes so that it shows 28 to 31 days depending on the month/year.
    //
    private void normalizeDateCtrl(JComboBox year, JComboBox month, JComboBox day)
    {
        final int[] daysTable = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        int daysInMonth = daysTable[startMonth.getSelectedIndex()];
        if ((daysInMonth == 28) && (((Integer)year.getSelectedItem()).intValue() % 4 == 0))
            ++daysInMonth;

        while (daysInMonth < day.getItemCount())
            day.removeItemAt(day.getItemCount() - 1);
        while (daysInMonth > day.getItemCount())
            day.addItem(new Integer(day.getItemCount() + 1));
    }

    //
    // Draw the chart.
    //
    private void drawChart(ChartViewer viewer)
    {
        // Get the start date and end date that are visible on the chart.
        Date viewPortStartDate = Chart.NTime(viewer.getValueAtViewPort("x", viewer.getViewPortLeft()));
        Date viewPortEndDate = Chart.NTime(viewer.getValueAtViewPort("x", viewer.getViewPortLeft() +
            viewer.getViewPortWidth()));

        // Get the array indexes that corresponds to the visible start and end dates
        int startIndex = (int)Math.floor(Chart.bSearch(timeStamps, viewPortStartDate));
        int endIndex = (int)Math.ceil(Chart.bSearch(timeStamps, viewPortEndDate));
        int noOfPoints = endIndex - startIndex + 1;

        // Extract the part of the data array that are visible.
        Date[] viewPortTimeStamps = (Date[])Chart.arraySlice(timeStamps, startIndex, noOfPoints);
        double[] viewPortDataSeriesA = (double[])Chart.arraySlice(dataSeriesA, startIndex, noOfPoints);
        double[] viewPortDataSeriesB = (double[])Chart.arraySlice(dataSeriesB, startIndex, noOfPoints);
        double[] viewPortDataSeriesC = (double[])Chart.arraySlice(dataSeriesC, startIndex, noOfPoints);

        //
        // At this stage, we have extracted the visible data. We can use those data to plot the chart.
        //

        //================================================================================
        // Configure overall chart appearance.
        //================================================================================

        // Create an XYChart object of size 640 x 350 pixels
        XYChart c = new XYChart(640, 350);

        // Re-cycle the resources of the existing chart, if any. This can improve performance
        // by reducing the frequency of garbage collections.
        c.recycle(chartViewer1.getChart());

        // Set the plotarea at (55, 50) with width 80 pixels less than chart width, and height 85 pixels
        // less than chart height. Use a vertical gradient from light blue (f0f6ff) to sky blue (a0c0ff)
        // as background. Set border to transparent and grid lines to white (ffffff).
        c.setPlotArea(55, 50, c.getWidth() - 80, c.getHeight() - 85, c.linearGradientColor(0, 50, 0,
            c.getHeight() - 35, 0xf0f6ff, 0xa0c0ff), -1, Chart.Transparent, 0xffffff, 0xffffff);

        // As the data can lie outside the plotarea in a zoomed chart, we need enable clipping.
        c.setClipping();

        // Add a title to the chart using 18 pts Times New Roman Bold Italic font
        c.addTitle("   Zooming and Scrolling with Track Line (2)", "Times New Roman Bold Italic", 18);

        // Add a legend box at (55, 25) using horizontal layout. Use 8pts Arial Bold as font. Set the
        // background and border color to Transparent and use line style legend key.
        LegendBox b = c.addLegend(55, 25, false, "Arial Bold", 8);
        b.setBackground(Chart.Transparent);
        b.setLineStyleKey();

        // Set the axis stem to transparent
        c.xAxis().setColors(Chart.Transparent);
        c.yAxis().setColors(Chart.Transparent);

        // Add axis title using 10pts Arial Bold Italic font
        c.yAxis().setTitle("Ionic Temperature (C)", "Arial Bold Italic", 10);

        //================================================================================
        // Add data to chart
        //================================================================================

        //
        // In this example, we represent the data by lines. You may modify the code below to use other
        // representations (areas, scatter plot, etc).
        //

        // Add a line layer for the lines, using a line width of 2 pixels
        LineLayer layer = c.addLineLayer2();
        layer.setLineWidth(2);

        // In this demo, we do not have too many data points. In real code, the chart may contain a lot
        // of data points when fully zoomed out - much more than the number of horizontal pixels in this
        // plot area. So it is a good idea to use fast line mode.
        layer.setFastLineMode();

        // Now we add the 3 data series to a line layer, using the color red (ff33333), green (008800)
        // and blue (3333cc)
        layer.setXData(viewPortTimeStamps);
        layer.addDataSet(viewPortDataSeriesA, 0xff3333, "Alpha");
        layer.addDataSet(viewPortDataSeriesB, 0x008800, "Beta");
        layer.addDataSet(viewPortDataSeriesC, 0x3333cc, "Gamma");

        //================================================================================
        // Configure axis scale and labelling
        //================================================================================

        // Set the x-axis as a date/time axis with the scale according to the view port x range.
        viewer.syncDateAxisWithViewPort("x", c.xAxis());

        //
        // In this demo, the time range can be from a few years to a few days. We demonstrate how to set
        // up different date/time format based on the time range.
        //

        // If all ticks are yearly aligned, then we use "yyyy" as the label format.
        c.xAxis().setFormatCondition("align", 360 * 86400);
        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", 30 * 86400);
        c.xAxis().setMultiFormat(Chart.StartOfYearFilter(), "<*font=bold*>{value|mmm yyyy}",
            Chart.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(Chart.StartOfYearFilter(),
            "<*block,halign=left*><*font=bold*>{value|mmm dd<*br*>yyyy}", Chart.StartOfMonthFilter(),
            "<*font=bold*>{value|mmm dd}");
        c.xAxis().setMultiFormat2(Chart.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(Chart.StartOfDayFilter(), "<*font=bold*>{value|hh:nn<*br*>mmm dd}",
            Chart.AllPassFilter(), "{value|hh:nn}");

        //================================================================================
        // Output the chart
        //================================================================================

        viewer.setChart(c);
    }

    //
    // Click event for the pointerPB.
    //
    private void pointerPB_Clicked()
    {
        pointerPB.setBackground(new Color(0x80, 0xff, 0x80));
        zoomInPB.setBackground(null);
        zoomOutPB.setBackground(null);
        chartViewer1.setMouseUsage(Chart.MouseUsageScrollOnDrag);
    }

    //
    // Click event for the zoomInPB.
    //
    private void zoomInPB_Clicked()
    {
        pointerPB.setBackground(null);
        zoomInPB.setBackground(new Color(0x80, 0xff, 0x80));
        zoomOutPB.setBackground(null);
        chartViewer1.setMouseUsage(Chart.MouseUsageZoomIn);
    }

    //
    // Click event for the zoomOutPB.
    //
    private void zoomOutPB_Clicked()
    {
        pointerPB.setBackground(null);
        zoomInPB.setBackground(null);
        zoomOutPB.setBackground(new Color(0x80, 0xff, 0x80));
        chartViewer1.setMouseUsage(Chart.MouseUsageZoomOut);
    }

    //
    // Horizontal ScrollBar ValueChanged event handler
    //
    private void hScrollBar1_ValueChanged()
    {
        if (hasFinishedInitialization && !chartViewer1.isInViewPortChangedEvent())
        {
            // Get the view port left as according to the scroll bar
            double newViewPortLeft = ((double)(hScrollBar1.getValue() - hScrollBar1.getMinimum()))
                / (hScrollBar1.getMaximum() - hScrollBar1.getMinimum());

            // Check if view port has really changed - sometimes the scroll bar may issue redundant
            // value changed events when value has not actually changed.
            if (Math.abs(chartViewer1.getViewPortLeft() - newViewPortLeft) >
                0.00001 * chartViewer1.getViewPortWidth())
            {
                // Set the view port based on the scroll bar
                chartViewer1.setViewPortLeft(newViewPortLeft);

                // Update the chart display without updating the image maps. We delay updating
                // the image map because the chart may still be unstable (still scrolling).
                chartViewer1.updateViewPort(true, false);
            }
        }
    }

    //
    // Start Date control event handler
    //
    private void startDate_ValueChanged()
    {
        // The date control can update the view port only if it is not currently being updated in the
        // view port changed event (that is, only if the date is changed due to user action).
        if (hasFinishedInitialization && !chartViewer1.isInViewPortChangedEvent())
        {
            Date startDate = new GregorianCalendar(((Integer)startYear.getSelectedItem()).intValue(),
                startMonth.getSelectedIndex(), startDay.getSelectedIndex() + 1).getTime();

            // The updated view port width
            double vpWidth = chartViewer1.getViewPortLeft() + chartViewer1.getViewPortWidth() -
                chartViewer1.getViewPortAtValue("x", Chart.CTime(startDate));

            // Make sure the updated view port width is within bounds
            vpWidth = Math.max(chartViewer1.getZoomInWidthLimit(), Math.min(vpWidth,
                chartViewer1.getViewPortLeft() + chartViewer1.getViewPortWidth()));

            // Update view port and trigger a view port changed event to update the chart
            chartViewer1.setViewPortLeft(chartViewer1.getViewPortLeft() +
                chartViewer1.getViewPortWidth() - vpWidth);
            chartViewer1.setViewPortWidth(vpWidth);
            chartViewer1.updateViewPort(true, false);
        }
    }

    //
    // End Date control event handler
    //
    private void endDate_ValueChanged()
    {
        // The date control can update the view port only if it is not currently being updated in the
        // view port changed event (that is, only if the date is changed due to user action).
        if (hasFinishedInitialization && !chartViewer1.isInViewPortChangedEvent())
        {
            Date endDate = new GregorianCalendar(((Integer)endYear.getSelectedItem()).intValue(),
                endMonth.getSelectedIndex(), endDay.getSelectedIndex() + 1).getTime();

            // The updated view port width
            double vpWidth = chartViewer1.getViewPortAtValue("x", Chart.CTime(endDate)) -
                chartViewer1.getViewPortLeft();

            // Make sure the updated view port width is within bounds
            vpWidth = Math.max(chartViewer1.getZoomInWidthLimit(), Math.min(vpWidth,
                1 - chartViewer1.getViewPortLeft()));

            // Update view port and trigger a view port changed event to update the chart
            chartViewer1.setViewPortWidth(vpWidth);
            chartViewer1.updateViewPort(true, false);
        }
    }

    //
    // Mouse Wheel event handler
    //
    private void chartViewer1_MouseWheel(MouseWheelEvent e)
    {
        // We zoom in or out by 10% depending on the mouse wheel direction.
        double rx = e.getWheelRotation() < 0 ? 0.9 : 1 / 0.9;
        double ry = rx;

        // We do not zoom in beyond the zoom in width or height limit.
        rx = Math.max(rx, chartViewer1.getZoomInWidthLimit() / chartViewer1.getViewPortWidth());
        ry = Math.max(ry, chartViewer1.getZoomInWidthLimit()/ chartViewer1.getViewPortHeight());
        if ((rx == 1) && (ry == 1))
            return;

        XYChart c = (XYChart)chartViewer1.getChart();

        //
        // Set the view port position and size so that it is zoom in/out around the mouse by the
        // desired ratio.
        //

        double mouseOffset = (e.getX() - c.getPlotArea().getLeftX()) /
            (double)c.getPlotArea().getWidth();
        chartViewer1.setViewPortLeft(chartViewer1.getViewPortLeft() + mouseOffset * (1 - rx) *
            chartViewer1.getViewPortWidth());
        chartViewer1.setViewPortWidth(chartViewer1.getViewPortWidth() * rx);

        double mouseOffsetY = (e.getY() - c.getPlotArea().getTopY()) /
            (double)c.getPlotArea().getHeight();
        chartViewer1.setViewPortTop(chartViewer1.getViewPortTop() + mouseOffsetY * (1 - ry) *
            chartViewer1.getViewPortHeight());
        chartViewer1.setViewPortHeight(chartViewer1.getViewPortHeight() * ry);

        // Trigger a view port changed event to update the chart
        chartViewer1.updateViewPort(true, false);
    }

    //
    // Draw track cursor when mouse is moving over plotarea
    //
    private void chartViewer1_MouseMovedPlotArea(MouseEvent e)
    {
        ChartViewer viewer = (ChartViewer)e.getSource();
        trackLineLabel((XYChart)viewer.getChart(), viewer.getPlotAreaMouseX());
        viewer.updateDisplay();

        // Hide the track cursor when the mouse leaves the plot area
        viewer.removeDynamicLayer("MouseExitedPlotArea");
    }

    //
    // Draw track line with data labels
    //
    private void trackLineLabel(XYChart c, int mouseX)
    {
        // Clear the current dynamic layer and get the DrawArea object to draw on it.
        DrawArea d = c.initDynamicLayer();

        // The plot area object
        PlotArea plotArea = c.getPlotArea();

        // Get the data x-value that is nearest to the mouse, and find its pixel coordinate.
        double xValue = c.getNearestXValue(mouseX);
        int xCoor = c.getXCoor(xValue);

        // Draw a vertical track line at the x-position
        d.vline(plotArea.getTopY(), plotArea.getBottomY(), xCoor, d.dashLineColor(0x000000, 0x0101));

        // Draw a label on the x-axis to show the track line position.
        String xlabel = "<*font,bgColor=000000*> " + c.xAxis().getFormattedLabel(xValue, "mmm dd, yyyy") +
            " <*/font*>";
        TTFText t = d.text(xlabel, "Arial Bold", 8);

        // Restrict the x-pixel position of the label to make sure it stays inside the chart image.
        int xLabelPos = Math.max(0, Math.min(xCoor - t.getWidth() / 2, c.getWidth() - t.getWidth()));
        t.draw(xLabelPos, plotArea.getBottomY() + 6, 0xffffff);

        // Iterate through all layers to draw the data labels
        for (int i = 0; i < c.getLayerCount(); ++i) {
            Layer layer = c.getLayerByZ(i);

            // The data array index of the x-value
            int xIndex = layer.getXIndexOf(xValue);

            // Iterate through all the data sets in the layer
            for (int j = 0; j < layer.getDataSetCount(); ++j) {
                ChartDirector.DataSet dataSet = layer.getDataSetByZ(j);

                // Get the color and position of the data label
                int color = dataSet.getDataColor();
                int yCoor = c.getYCoor(dataSet.getPosition(xIndex), dataSet.getUseYAxis());

                // Draw a track dot with a label next to it for visible data points in the plot area
                if ((yCoor >= plotArea.getTopY()) && (yCoor <= plotArea.getBottomY()) && (color !=
                    Chart.Transparent) && (!(dataSet.getDataName() == null || dataSet.getDataName().length()
                     == 0))) {

                    d.circle(xCoor, yCoor, 4, 4, color, color);

                    String label = "<*font,bgColor=" + Integer.toHexString(color) + "*> " + c.formatValue(
                        dataSet.getValue(xIndex), "{value|P4}") + " <*/font*>";
                    t = d.text(label, "Arial Bold", 8);

                    // Draw the label on the right side of the dot if the mouse is on the left side the chart,
                    // and vice versa. This ensures the label will not go outside the chart image.
                    if (xCoor <= (plotArea.getLeftX() + plotArea.getRightX()) / 2) {
                        t.draw(xCoor + 5, yCoor, 0xffffff, Chart.Left);
                    } else {
                        t.draw(xCoor - 5, yCoor, 0xffffff, Chart.Right);
                    }
                }
            }
        }
    }

    //
    // Implementation of the DemoModule interface to allow this demo to run inside the
    // ChartDirectorDemo browser
    //

    // Name of demo program
    public String toString()
    {
        return "Zoom/Scroll with Track Line (2)";
    }

    // Number of charts produced in this demo
    public int getNoOfCharts()
    {
        // This demo open its own frame instead of using the right pane of the ChartDirectorDemo
        // browser for display, so we just load the frame, then returns 0.
        setupFrame();
        setVisible(true);
        return 0;
    }

    // Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // do nothing, as the ChartDirectorDemo browser right pane is not used
    }
}


XY Zooming and Scrolling (Windows)

XY Zooming and Scrolling (Windows)

NOTE: This section describes XY Zooming and Scrolling for Windows applications only. For web applications, please refer to XY Zooming and Scrolling (Web).

This example demonstrates zooming and scrolling in both horizontal and vertical directions. In addition to using mouse click and drag, this example demonstrates using a slider and the mouse wheel to control zooming. There is also a "navigation pad" which can be thought as a representation of the view port. You can drag the pad to move the view port around (that is, to perform 2D scrolling). This example also includes a crosshair track cursor with dynamic labels on the x-axis and y-axis showing the mouse cursor position, and an image map for data point tooltips.

The main source code listing of this sample program is included at the end of this section. The code consists of the following main parts:

  • Initialization: It loads data into memory and initializes the ChartViewer.

  • The ViewPortListener.viewPortChanged event handler: When the view port changed, the following things need to be updated - external controls (including the slider and the navigation pad), the chart and the track cursor.

  • drawChart: This is the main charting code. It plots the chart as usual, with the x-axis and y-axis configured to synchronize with the view port using ChartViewer.syncDateAxisWithViewPort.

  • Slider handling code: When the slider moves, the view port will be updated to reflect the slider position and a ViewPortListener.viewPortChanged event will be fired.

  • Navigation pad implementation: The navigation pad is a custom user interface consisting of a draggable rectangle inside a container rectangle. This can be imagined as a 2D scroll bar. When the inner rectangle is dragged, the view port will be updated to reflect the new rectangle position, and a ViewPortListener.viewPortChanged event will be fired. Conversely, if the view port is changed, the size and position of the draggable rectangle will be updated to reflect the view port.

  • Mouse wheel handling code: When the mouse wheel moves, the view port will be updated to reflect zooming in or out, and a ViewPortListener.viewPortChanged event will be fired.

  • Track Cursor drawing code: This is essentially the same as the track cursor drawing code in Crosshair with Axis Labels (Windows). Please refer to that example for the explanation of the code.

Source Code Listing

[Java Version] javademo/xyzoomscroll.java
import ChartDirector.*;
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class xyzoomscroll extends JFrame implements DemoModule
{
    // XY data points for the chart
    private double[] dataX0;
    private double[] dataY0;
    private double[] dataX1;
    private double[] dataY1;
    private double[] dataX2;
    private double[] dataY2;

    // Internal variables to keep track of mouse positions during dragging of navigateWindow.
    private boolean isDraggingNavigatePad;
    private int mouseDownXCoor;
    private int mouseDownYCoor;

    // Will set to true at the end of initialization
    private boolean hasFinishedInitialization;

    //
    // Controls in the JFrame
    //
    private ChartViewer chartViewer1;
    private JButton pointerPB;
    private JButton zoomInPB;
    private JButton zoomOutPB;
    private JSlider zoomBar;
    private JLabel navigatePad;
    private JPanel navigateWindow;

    //
    // The main method to allow this demo to run as a standalone program.
    //
    public static void main(String args[])
    {
        xyzoomscroll demo = new xyzoomscroll();
        demo.setDefaultCloseOperation(EXIT_ON_CLOSE);
        demo.setupFrame();
        demo.setVisible(true);
    }

    //
    // Set up the JFrame
    //
    private void setupFrame()
    {
        // Do nothing if already initialized
        if (hasFinishedInitialization)
            return;

        // Set JFrame title to name of this demo program
        setTitle(toString());
        setResizable(false);

        // Font to use for user interface elements
        Font uiFont = new Font("Dialog", Font.PLAIN, 11);

        // Top label bar
        JLabel topLabel = new JLabel("Advanced Software Engineering");
        topLabel.setForeground(new java.awt.Color(255, 255, 51));
        topLabel.setBackground(new java.awt.Color(0, 0, 128));
        topLabel.setBorder(new javax.swing.border.EmptyBorder(2, 0, 2, 5));
        topLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        topLabel.setOpaque(true);
        getContentPane().add(topLabel, java.awt.BorderLayout.NORTH);

        // Left panel
        JPanel leftPanel = new JPanel(null);
        leftPanel.setBorder(javax.swing.BorderFactory.createRaisedBevelBorder());

        // Pointer push button
        pointerPB = new JButton("Pointer", loadImageIcon("pointer.gif"));
        pointerPB.setHorizontalAlignment(SwingConstants.LEFT);
        pointerPB.setMargin(new Insets(5, 5, 5, 5));
        pointerPB.addActionListener(new ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pointerPB_Clicked();
            }});
        leftPanel.add(pointerPB).setBounds(1, 0, 118, 24);

        // Zoom In push button
        zoomInPB = new JButton("Zoom In", loadImageIcon("zoomin.gif"));
        zoomInPB.setHorizontalAlignment(SwingConstants.LEFT);
        zoomInPB.setMargin(new Insets(5, 5, 5, 5));
        zoomInPB.addActionListener(new ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                zoomInPB_Clicked();
            }});
        leftPanel.add(zoomInPB).setBounds(1, 24, 118, 24);

        // Zoom out push button
        zoomOutPB = new JButton("Zoom Out", loadImageIcon("zoomout.gif"));
        zoomOutPB.setHorizontalAlignment(SwingConstants.LEFT);
        zoomOutPB.setMargin(new Insets(5, 5, 5, 5));
        zoomOutPB.addActionListener(new ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                zoomOutPB_Clicked();
            }});
        leftPanel.add(zoomOutPB).setBounds(1, 48, 118, 24);

        // Zoom level label
        JLabel zoomLabel = new JLabel("Zoom Level");
        zoomLabel.setHorizontalAlignment(SwingConstants.CENTER);
        leftPanel.add(zoomLabel).setBounds(5, 220, 108, 20);

        // Zoom level bar
        zoomBar = new JSlider(1, 100, 50);
        zoomBar.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent e) {
                zoomBar_ValueChanged(e);
            }
        });
        leftPanel.add(zoomBar).setBounds(5, 240, 110, 20);

        // Navigation Pad
        navigatePad = new JLabel();
        navigatePad.setBackground(new Color(0xc0, 0xc0, 0xff));
        navigatePad.setOpaque(true);
        navigatePad.setBorder(javax.swing.BorderFactory.createLoweredBevelBorder());
        navigateWindow = new JPanel();
        navigateWindow.setBackground(new Color(0xe0, 0xe0, 0xe0));
        navigateWindow.setBorder(javax.swing.BorderFactory.createLineBorder(Color.black));
        navigateWindow.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                navigateWindow_MouseDown(e);
            }
            public void mouseReleased(MouseEvent e) {
                navigateWindow_MouseUp(e);
            }
        });
        navigateWindow.addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseDragged(MouseEvent e)  {
                navigateWindow_MouseMove(e);
            }
        });
        navigatePad.add(navigateWindow);
        leftPanel.add(navigatePad).setBounds(1, 310, 118, 118);

        // Total expected panel size
        leftPanel.setPreferredSize(new java.awt.Dimension(120, 440));

        // Chart Viewer
        chartViewer1 = new ChartViewer();
        chartViewer1.setBackground(new java.awt.Color(0xc0, 0xc0, 0xff));
        chartViewer1.setOpaque(true);
        chartViewer1.setHotSpotCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        chartViewer1.setScrollDirection(Chart.DirectionHorizontalVertical);
        chartViewer1.setZoomDirection(Chart.DirectionHorizontalVertical);
        chartViewer1.setPreferredSize(new Dimension(500, 480));
        chartViewer1.addViewPortListener(new ViewPortAdapter() {
            public void viewPortChanged(ViewPortChangedEvent e) {
                chartViewer1_ViewPortChanged(e);
            }
        });
        chartViewer1.addHotSpotListener(new HotSpotAdapter() {
            public void hotSpotClicked(HotSpotEvent e) {
                chartViewer1_HotSpotClicked(e);
        }});
        chartViewer1.addTrackCursorListener(new TrackCursorAdapter() {
            public void mouseMovedPlotArea(MouseEvent e) {
                chartViewer1_MouseMovedPlotArea(e);
            }
        });
        chartViewer1.addMouseWheelListener(new MouseWheelListener() {
            public void mouseWheelMoved(MouseWheelEvent e) {
                chartViewer1_MouseWheel(e);
            }
        });

        // Put the leftPanel and rightPanel on the JFrame
        getContentPane().add(leftPanel, java.awt.BorderLayout.WEST);
        getContentPane().add(chartViewer1, java.awt.BorderLayout.CENTER);

        // Set all UI fonts (except labels)
        for (int i = 0; i < leftPanel.getComponentCount(); ++i)
        {
            Component c = leftPanel.getComponent(i);
            if (!(c instanceof JLabel))
                c.setFont(uiFont);
        }

        //
        // At this point, the user interface layout has been completed.
        // Can load data and plot chart now.
        //

        // Load the data
        loadData();

        // Initialize the ChartViewer
        initChartViewer(chartViewer1);

        // Trigger a view port update to draw chart.
        pack();
        hasFinishedInitialization = true;
        chartViewer1.updateViewPort(true, true);
    }

    //
    // A utility to load an image icon from the Java class path
    //
    private ImageIcon loadImageIcon(String path)
    {
        try { return new ImageIcon(getClass().getClassLoader().getResource(path)); }
        catch (Exception e) { return null; }
    }

    //
    // Load the data
    //
    private void loadData()
    {
        //
        // For simplicity, in this demo, we just use hard coded data.
        //
        dataX0 = new double[] {10, 15, 6, -12, 14, -8, 13, -3, 16, 12, 10.5, -7, 3, -10, -5, 2, 5};
        dataY0 = new double[] {130, 150, 80, 110, -110, -105, -130, -15, -170, 125,  125, 60, 25,
            150, 150, 15, 120};
        dataX1 = new double[] {6, 7, -4, 3.5, 7, 8, -9, -10, -12, 11, 8, -3, -2, 8, 4, -15, 15};
        dataY1 = new double[] {65, -40, -40, 45, -70, -80, 80, 10, -100, 105, 60, 50, 20, 170, -25,
            50, 75};
        dataX2 = new double[] {-10, -12, 11, 8, 6, 12, -4, 3.5, 7, 8, -9, 3, -13, 16, -7.5, -10,
            -15};
        dataY2 = new double[] {65, -80, -40, 45, -70, -80, 80, 90, -100, 105, 60, -75, -150, -40,
            120, -50, -30};
    }

    //
    // Initialize the ChartViewer
    //
    private void initChartViewer(ChartViewer viewer)
    {
        // Initially set the mouse usage to "Pointer" mode (Drag to Scroll mode)
        pointerPB.doClick();
    }

    //
    // The ViewPortChanged event handler. This event occurs if the user scrolls or zooms in
    // or out the chart by dragging or clicking on the chart. It can also be triggered by
    // calling WinChartViewer.updateViewPort.
    //
    private void chartViewer1_ViewPortChanged(ViewPortChangedEvent e)
    {
        // In addition to updating the chart, we may also need to update other controls that
        // changes based on the view port.
        updateControls(chartViewer1);

        // Update the chart if necessary
        if (e.needUpdateChart())
            drawChart(chartViewer1);

        // Update the image map if necessary
        if (e.needUpdateImageMap())
            updateImageMap(chartViewer1);

        // We need to update the track line too. If the mouse is moving on the chart (eg. if
        // the user drags the mouse on the chart to scroll it), the track line will be updated
        // in the MouseMovePlotArea event. Otherwise, we need to update the track line here.
        if ((!chartViewer1.isInMouseMoveEvent()) && chartViewer1.isMouseOnPlotArea())
        {
            crossHair((XYChart)chartViewer1.getChart(), chartViewer1.getPlotAreaMouseX(),
                chartViewer1.getPlotAreaMouseY());
            chartViewer1.updateDisplay();
        }
    }

    //
    // Update controls when the view port changed
    //
    private void updateControls(ChartViewer viewer)
    {
        // We need to update the navigator window size and position only if the view port changes are not
        // caused by the navigateWindow itself.
        if (!isDraggingNavigatePad)
        {
            navigateWindow.setBounds(
                (int)Math.round(chartViewer1.getViewPortLeft() * (navigatePad.getWidth() - 4) + 2),
                (int)Math.round(chartViewer1.getViewPortTop() * (navigatePad.getHeight() - 4) + 2),
                (int)Math.max(1.0, chartViewer1.getViewPortWidth() * (navigatePad.getWidth() - 4)),
                (int)Math.max(1.0, chartViewer1.getViewPortHeight() * (navigatePad.getHeight() - 4))
            );
        }

        // Synchronize the zoom bar value with the view port width/height
        zoomBar.setValue((int)Math.round(Math.min(chartViewer1.getViewPortWidth(),
            chartViewer1.getViewPortHeight()) * zoomBar.getMaximum()));
    }

    //
    // Draw the chart.
    //
    private void drawChart(ChartViewer viewer)
    {
        // Create an XYChart object 500 x 480 pixels in size, with light blue (c0c0ff) as
        // background color
        XYChart c = new XYChart(500, 480, 0xc0c0ff);

        // Re-cycle the resources of the existing chart, if any. This can improve performance
        // by reducing the frequency of garbage collections.
        c.recycle(chartViewer1.getChart());

        // 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(Chart.XYAxisAtOrigin, Chart.XAxisSymmetric + Chart.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.
        LegendBox legendBox = c.addLegend(450, 40, true, "arialbd.ttf", 8);
        legendBox.setAlignment(Chart.TopRight);
        legendBox.setBackground(0x40dddddd);

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

        // 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 50 pixels between major ticks and 25 pixels between minor ticks.
        c.xAxis().setTickDensity(50, 25);
        c.yAxis().setTickDensity(50, 25);

        //
        // 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", Chart.Cross2Shape(), 11, 0xff3333);

        // Add scatter layer, using 11 pixels green (33ff33) circle symbols
        c.addScatterLayer(dataX1, dataY1, "Group B", Chart.CircleShape, 11,    0x33ff33);

        // Add scatter layer, using 11 pixels blue (3333ff) triangle symbols
        c.addScatterLayer(dataX2, dataY2, "Group C", Chart.TriangleSymbol, 11, 0x3333ff);

        //
        // In this example, we have not explicitly configured the full x and y range. In this case, the
        // first time syncLinearAxisWithViewPort is called, ChartDirector will auto-scale the axis and
        // assume the resulting range is the full range. In subsequent calls, ChartDirector will set the
        // axis range based on the view port and the full range.
        //
        viewer.syncLinearAxisWithViewPort("x", c.xAxis());
        viewer.syncLinearAxisWithViewPort("y", c.yAxis());

        // Set the chart image to the ChartViewer
        chartViewer1.setChart(c);
    }

    //
    // Update the image map used on the chart.
    //
    private void updateImageMap(ChartViewer viewer)
    {
        // Include tool tip for the chart
        if (viewer.getImageMap() == null)
        {
            viewer.setImageMap(viewer.getChart().getHTMLImageMap("clickable", "",
                "title='[{dataSetName}] Alpha = {x}, Beta = {value}'"));
        }
    }

    //
    // Handler when a hot spot is clicked. In this demo, we just list out the hot spot parameters
    // in a pop up dialog.
    //
    private void chartViewer1_HotSpotClicked(HotSpotEvent e)
    {
        // We show the pop up dialog only when the mouse action is not in zoom-in or zoom-out mode.
        if ((chartViewer1.getMouseUsage() != Chart.MouseUsageZoomIn) &&
            (chartViewer1.getMouseUsage() != Chart.MouseUsageZoomOut))
            showHotSpotParam(e);
    }

    //
    // Utility to list out all hot spot parameters on a pop-up dialog
    //
    private void showHotSpotParam(HotSpotEvent e)
    {
        // Get all parameters and sort them by key
        Hashtable parameters = e.getAttrValues();
        Object[] attributes = parameters.keySet().toArray();
        Arrays.sort(attributes);

        // Create a JTable to show the hot spot attribute/value pairs
        Object[][] rows = new Object[parameters.size()][2];
        for (int i = 0; i < attributes.length; ++i)
        {
            rows[i][0] = attributes[i];
            rows[i][1] = parameters.get(attributes[i]);
        }
        JTable table = new JTable(rows, new Object[] {"Parameter", "Value"});

        // Show the table in a dialog
        JDialog d = new JDialog(this, "Hot Spot Parameters", true);
        d.setSize(300, 300);
        Container container = d.getContentPane();

        // Just add some descriptive text to the dialg
        JTextArea t = new JTextArea ("This dialog is for demonstration only." +
            " In this demo, we simply list out all hot spot parameters.");
        t.setLineWrap(true);
        t.setWrapStyleWord(true);
        t.setEditable(false);
        t.setOpaque(false);
        t.setMargin(new Insets(5, 5, 5, 5));
        container.add(t, BorderLayout.NORTH);

        // Create the scroll pane on the dialog and add the table to it.
        JScrollPane scrollPane = new JScrollPane(table);
        container.add(scrollPane);

        // Show the dialog on where the mouse click occur
        Point topLeft = ((ChartViewer)e.getSource()).getLocationOnScreen();
        d.setLocation(topLeft.x + e.getX(), topLeft.y + e.getY());
        d.setVisible(true);
    }

    //
    // Pointer (Drag to Scroll) button event handler
    //
    private void pointerPB_Clicked()
    {
        pointerPB.setBackground(new Color(0x80, 0xff, 0x80));
        zoomInPB.setBackground(null);
        zoomOutPB.setBackground(null);
        chartViewer1.setMouseUsage(Chart.MouseUsageScrollOnDrag);
    }

    //
    // Zoom In button event handler
    //
    private void zoomInPB_Clicked()
    {
        pointerPB.setBackground(null);
        zoomInPB.setBackground(new Color(0x80, 0xff, 0x80));
        zoomOutPB.setBackground(null);
        chartViewer1.setMouseUsage(Chart.MouseUsageZoomIn);
    }

    //
    // Zoom Out button event handler
    //
    private void zoomOutPB_Clicked()
    {
        pointerPB.setBackground(null);
        zoomInPB.setBackground(null);
        zoomOutPB.setBackground(new Color(0x80, 0xff, 0x80));
        chartViewer1.setMouseUsage(Chart.MouseUsageZoomOut);
    }

    //
    // ValueChanged event handler for zoomBar. Zoom in around the center point and try to
    // maintain the aspect ratio
    //
    private void zoomBar_ValueChanged(javax.swing.event.ChangeEvent e)
    {
        if (!chartViewer1.isInViewPortChangedEvent())
        {
            // Remember the center point
            double centerX = chartViewer1.getViewPortLeft() + chartViewer1.getViewPortWidth() / 2;
            double centerY = chartViewer1.getViewPortTop() + chartViewer1.getViewPortHeight() / 2;

            // Aspect ratio and zoom factor
            double aspectRatio = chartViewer1.getViewPortWidth() / chartViewer1.getViewPortHeight();
            double zoomTo = ((double)zoomBar.getValue()) / zoomBar.getMaximum();

            // Zoom while respecting the aspect ratio
            chartViewer1.setViewPortWidth(zoomTo * Math.max(1, aspectRatio));
            chartViewer1.setViewPortHeight(zoomTo * Math.max(1, 1 / aspectRatio));

            // Adjust ViewPortLeft and ViewPortTop to keep center point unchanged
            chartViewer1.setViewPortLeft(centerX - chartViewer1.getViewPortWidth() / 2);
            chartViewer1.setViewPortTop(centerY - chartViewer1.getViewPortHeight() / 2);

            // Update the chart, but no need to update the image map yet, as the chart is still
            // zooming and is unstable
            chartViewer1.updateViewPort(true, false);
        }
    }

    //
    // The navigateWindow_MouseDown, navigateWindow_MouseMove and navigateWindow_MouseUp
    // methods implement the navigate window.
    //

    //
    // MouseDown event handler for the navigateWindow
    //
    private void navigateWindow_MouseDown(MouseEvent e)
    {
        if (e.getModifiers() == InputEvent.BUTTON1_MASK)
        {
            // Save the mouse coordinates to keep track of how far the navigateWindow has been
            // dragged.
            isDraggingNavigatePad = true;
            mouseDownXCoor = e.getX();
            mouseDownYCoor = e.getY();
        }
    }

    //
    // MouseMove event handler for the navigateWindow
    //
    private void navigateWindow_MouseMove(MouseEvent e)
    {
        if (isDraggingNavigatePad)
        {
            // Is currently dragging - move the navigateWindow based on the distances dragged
            int newLabelLeft = Math.max(2, navigateWindow.getX() + e.getX() - mouseDownXCoor);
            int newLabelTop = Math.max(2, navigateWindow.getY() + e.getY() - mouseDownYCoor);

            // Ensure the navigateWindow is within the navigatePad container
            if (newLabelLeft + navigateWindow.getWidth() > navigatePad.getWidth() - 2)
                newLabelLeft = navigatePad.getWidth() - navigateWindow.getWidth() - 2;
            if (newLabelTop + navigateWindow.getHeight() > navigatePad.getHeight() - 2)
                newLabelTop = navigatePad.getHeight() - navigateWindow.getHeight() - 2;

            // Update the navigateWindow position as it is being dragged
            navigateWindow.setLocation(newLabelLeft, newLabelTop);

            // Update the WinChartViewer ViewPort as well
            chartViewer1.setViewPortLeft(((double)navigateWindow.getX() - 2) /
                (navigatePad.getWidth() - 4));
            chartViewer1.setViewPortTop(((double)navigateWindow.getY() - 2) /
                (navigatePad.getHeight() - 4));

            // Update the chart, but no need to update the image map yet, as the chart is still
            // scrolling and is unstable
            chartViewer1.updateViewPort(true, false);
        }
    }

    //
    // MouseUp event handler for the navigateWindow
    //
    private void navigateWindow_MouseUp(MouseEvent e)
    {
        if (e.getModifiers() == InputEvent.BUTTON1_MASK)
            isDraggingNavigatePad = false;
    }

    //
    // Mouse Wheel event handler
    //
    private void chartViewer1_MouseWheel(MouseWheelEvent e)
    {
        // We zoom in or out by 10% depending on the mouse wheel direction.
        double rx = e.getWheelRotation() < 0 ? 0.9 : 1 / 0.9;
        double ry = rx;

        // We do not zoom in beyond the zoom in width or height limit.
        rx = Math.max(rx, chartViewer1.getZoomInWidthLimit() / chartViewer1.getViewPortWidth());
        ry = Math.max(ry, chartViewer1.getZoomInWidthLimit()/ chartViewer1.getViewPortHeight());
        if ((rx == 1) && (ry == 1))
            return;

        XYChart c = (XYChart)chartViewer1.getChart();

        //
        // Set the view port position and size so that it is zoom in/out around the mouse by the
        // desired ratio.
        //

        double mouseOffset = (chartViewer1.getChartMouseX() - c.getPlotArea().getLeftX()) /
            (double)c.getPlotArea().getWidth();
        chartViewer1.setViewPortLeft(chartViewer1.getViewPortLeft() + mouseOffset * (1 - rx) *
            chartViewer1.getViewPortWidth());
        chartViewer1.setViewPortWidth(chartViewer1.getViewPortWidth() * rx);

        double mouseOffsetY = (chartViewer1.getChartMouseY() - c.getPlotArea().getTopY()) /
            (double)c.getPlotArea().getHeight();
        chartViewer1.setViewPortTop(chartViewer1.getViewPortTop() + mouseOffsetY * (1 - ry) *
            chartViewer1.getViewPortHeight());
        chartViewer1.setViewPortHeight(chartViewer1.getViewPortHeight() * ry);

        // Trigger a view port changed event to update the chart
        chartViewer1.updateViewPort(true, false);
    }

    //
    // Draw track cursor when mouse is moving over plotarea
    //
    private void chartViewer1_MouseMovedPlotArea(MouseEvent e)
    {
        ChartViewer viewer = (ChartViewer)e.getSource();

        // Draw crosshair track cursor
        crossHair((XYChart)viewer.getChart(), viewer.getPlotAreaMouseX(), viewer.getPlotAreaMouseY());
        viewer.updateDisplay();

        // Hide the track cursor when the mouse leaves the plot area
        viewer.removeDynamicLayer("MouseExitedPlotArea");

        // Update image map if necessary
        updateImageMap(viewer);
    }

    //
    // Draw cross hair cursor with axis labels
    //
    private void crossHair(XYChart c, int mouseX, int mouseY)
    {
        // Clear the current dynamic layer and get the DrawArea object to draw on it.
        DrawArea d = c.initDynamicLayer();

        // The plot area object
        PlotArea plotArea = c.getPlotArea();

        // Draw a vertical line and a horizontal line as the cross hair
        d.vline(plotArea.getTopY(), plotArea.getBottomY(), mouseX, d.dashLineColor(0x000000, 0x0101));
        d.hline(plotArea.getLeftX(), plotArea.getRightX(), mouseY, d.dashLineColor(0x000000, 0x0101));

        // Draw y-axis label
        String label = "<*block,bgColor=FFFFDD,margin=3,edgeColor=000000*>" + c.formatValue(c.getYValue(
            mouseY, c.yAxis()), "{value|P4}") + "<*/*>";
        TTFText t = d.text(label, "Arial Bold", 8);
        t.draw(plotArea.getLeftX() - 5, mouseY, 0x000000, Chart.Right);

        // Draw x-axis label
        label = "<*block,bgColor=FFFFDD,margin=3,edgeColor=000000*>" + c.formatValue(c.getXValue(mouseX),
            "{value|P4}") + "<*/*>";
        t = d.text(label, "Arial Bold", 8);
        t.draw(mouseX, plotArea.getBottomY() + 5, 0x000000, Chart.Top);
    }

    //
    // Implementation of the DemoModule interface to allow this demo to run inside the
    // ChartDirectorDemo browser
    //

    // Name of demo program
    public String toString()
    {
        return "XY Zooming and Scrolling";
    }

    // Number of charts produced in this demo
    public int getNoOfCharts()
    {
        // This demo open its own frame instead of using the right pane of the ChartDirectorDemo
        // browser for display, so we just load the frame, then returns 0.
        setupFrame();
        setVisible(true);
        return 0;
    }

    // Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // do nothing, as the ChartDirectorDemo browser right pane is not used
    }
}


Zooming and Scrolling Framework (Web)

Zooming and Scrolling Framework (Web)

NOTE: This section describes Zooming and Scrolling Framework for web applications only. For Windows applications, please refer to Zooming and Scrolling Framework (Windows).

Introduction

The ChartDirector Zooming and Scrolling Framework is a framework for "logical zooming" of charts. "Logical zooming" means the chart is plotted with more details as it is zoomed in, but the chart objects do not necessary become bigger. For example, the font size, line width, symbol size, etc, may remain the same. The chart may even change type or data when it is zoomed in. For example, for a finance chart, it may start as a daily candlestick chart when the time range is long, and becomes a realtime intraday line chart when zoomed to one day.

The main elements of the ChartDirector Zooming and Scrolling Framework include a click and drag user interface to control zooming and scrolling, a set of methods to manage axis scales, and AJAX support to allow updating charts without refreshing the web page.

WebChartViewer and JsChartViewer

The ChartDirector Zooming and Scrolling Framework for web applications is implemented in two controls - the WebChartViewer on the server side, and the JsChartViewer on the browser side.

  • WebChartViewer : This is a server side control. It handles AJAX communications with the JsChartViewer on the browser side.

  • JsChartViewer : This is a browser side Javascript control that provides the click and drag user interface to control zooming and scrolling. It communicates with the WebChartViewer on the server side using AJAX means to update the chart.

In brief, for a typical web page with a zoomable and scrollable chart, the operation is as follows:

  • The user opens the web page, so the browser sends a request to the server for the web page.

  • On the server side, the charting code creates the chart and sets it to the WebChartViewer. The WebChartViewer would then generated the HTML for the chart, with other necessary information to support AJAX communications.

  • The browser receives the web page from the server and displays the chart. The user can then use mouse actions to zoom or scroll the chart.

  • When a zooming or scrolling action occurs, the JsChartViewer will send an AJAX request to the server to update the chart.

  • On the server side, a new chart is generated based on the updated axis scale, and the WebChartViewer returns it to the browser as an AJAX response. The browser can then display the updated chart to the user.

The last three steps may repeat as the user continues to zoom or scroll the chart.

The above is only a brief description and omit many details. For example, custom parameters may be included in the AJAX request/response. Besides click and drag, the framework also allows using external controls or custom methods for zooming and scrolling. In addition to updating the chart in an AJAX response, the framework also allows other custom things to be updated. These features will be discussed in the following sections.

The View Port

In the ChartDirector Zooming and Scrolling framework, the view port is used to determine which part of the data range should be plotted.

The view port can be imagined as a rectangular window over the entire XY data range. For example, suppose the full data range is 10 years in the horizontal direction. A view port width of 0.1 means only 10% of the horizontal data range should be plotted. In other words, the chart is zoomed in so that only 1 year of data is visible. The view port left side will determine exactly which year of data that is visible.

The view port position and size can be get and set on both the server side and the client side using the following methods. The full data range is always assumed to be 0 to 1. So the view port position and size should be between 0 to 1.

Server Side Methods

Method | Description
WebChartViewer.getViewPortLeft | Gets the position of the left side of the view port.
WebChartViewer.setViewPortLeft | Sets the position of the left side of the view port.
WebChartViewer.getViewPortTop | Gets the position of the top side of the view port.
WebChartViewer.setViewPortTop | Sets the position of the top side of the view port.
WebChartViewer.getViewPortWidth | Gets the width of the view port.
WebChartViewer.setViewPortWidth | Sets the width of the view port.
WebChartViewer.getViewPortHeight | Gets the height of the view port.
WebChartViewer.setViewPortHeight | Sets the height of the view port.

Browser Side Methods

Method | Description
JsChartViewer.getViewPortLeft | Gets the position of the left side of the view port.
JsChartViewer.setViewPortLeft | Sets the position of the left side of the view port.
JsChartViewer.getViewPortTop | Gets the position of the top side of the view port.
JsChartViewer.setViewPortTop | Sets the position of the top side of the view port.
JsChartViewer.getViewPortWidth | Gets the width of the view port.
JsChartViewer.setViewPortWidth | Sets the width of the view port.
JsChartViewer.getViewPortHeight | Gets the height of the view port.
JsChartViewer.setViewPortHeight | Sets the height of the view port.

The Zoom and Scroll User Interface

The JsChartViewer control allows using mouse actions on the chart to control zooming and scrolling. Several mouse usage modes are supported, including drag to scroll, drag to select a region to zoom into, click to zoom in, and click to zoom out. They can be selected using JsChartViewer.setMouseUsage. The zooming and scrolling direction can be horizontal only, vertical only, or both, configurable using JsChartViewer.setZoomDirection and JsChartViewer.setScrollDirection.

When the user performs zooming or scrolling, JsChartViewer will update the view port to reflect the new visible region and fires the JsChartViewer.ViewPortChanged event . In typical usage, JsChartViewer.attachHandler can be used to attach JsChartViewer.partialUpdate as the ViewPortChanged event handler. This will cause an AJAX request to be sent to the server to update the chart when the view port changes.

AJAX Chart Update and Full Page Update

Virtually all browsers support AJAX nowadays, so it is suggested AJAX be used to update the chart, as this does not require refreshing the whole web page. All zooming and scrolling examples included in ChartDirector use AJAX chart updates.

ChartDirector also supports non-AJAX chart update that requires refreshing the entire web page. This is for compatibility with previous versions of ChartDirector. Historically, non-AJAX chart update is called "full page update" in ChartDirector documentation, while AJAX based chart update is called "partial chart update". That is why the method that triggers AJAX chart update is called JsChartViewer.partialUpdate.

Zoom and Scroll with External Controls

In addition to using mouse actions on the plot area, it is often desirable to have other ways to control zooming and scrolling. For example, in finance charts, there are often links that allow the user to jump to certain predefined period (eg. the last 30, 90, 180 or 360 days), which are essentially a type of zooming and scrolling.

To perform zooming and scrolling using external controls, the controls can update the view port position and size, and then fire the JsChartViewer.ViewPortChanged event by using JsChartViewer.raiseViewPortChangedEvent.

In some cases, the updates may need to be bi-directional - that is, the external controls may need to be updated when the view port changes. For example, suppose a scroll bar control is used to scroll the chart (although there is no scroll bar controls in standard HTML, there are third party Javascript implementations). When the user drags on the scroll bar, it can update the view port. The user may also drag on the chart directly to scroll the chart. In this case, the scroll bar would need to be updated to reflect that the changed view port.

To handle updating external controls when the view port changes, one may use the JsChartViewer.PostUpdate event. This event occurs after the server has responded to the AJAX request from the browser, at which stage the view port should have been confirmed and validated by the server. External controls can be updated in the PostUpdate event handler to reflect the view port positions.

Custom Parameters in AJAX Requests and Responses

Apart from the view port state, in some cases, other custom parameters may be required to determine how to update the chart. For example, in a finance chart application, the server may need to know the "ticker symbol" to determine which data series to draw, and the "ticker symbol" can be controlled by the user through an HTML text box on the browser. In this case, during AJAX chart update, the contents of the HTML text box would also need to be sent to the server.

Similarly, in some cases, apart from updating the chart, the server may want to update other things in the web page. In this case, custom parameters would need to be sent from the server to the browser.

In ChartDirector, WebChartViewer.setCustomAttr, WebChartViewer.getCustomAttr, JsChartViewer.setCustomAttr and JsChartViewer.getCustomAttr can be used to transfer custom parameters between the server and the browser during an AJAX chart update.

In typical usage, to transfer parameters from the browser to the server, one may use JsChartViewer.setCustomAttr in a JsChartViewer.PreUpdate event. The PreUpdate event occurs just before an AJAX chart update, so any parameters set will be transferred immediately to the server. On the server side, WebChartViewer.getCustomAttr can be used to retrieve the parameters. If the server needs to transfer custom parameters to the browser side, it can use WebChartViewer.setCustomAttr. The browser can retrieve the parameters using JsChartViewer.getCustomAttr in a JsChartViewer.PostUpdate event, which occurs immediately after the browser receives an AJAX response from the server.

Managing Axis Scale

The view port always assumes the full data range to be 0 to 1. In practice, a chart can have multiple x-axes and y-axes, using a combination of date/time, linear and logarithmic scales.

To facilitate conversion between the view port and the axis scale, ChartDirector includes a number of methods as follows:

Method | Description
WebChartViewer.setFullRange | Defines the full range of a view port data scale.
WebChartViewer.getValueAtViewPort JsChartViewer.getValueAtViewPort | Converts a view port coordinate to a value of the specified data scale.
WebChartViewer.getViewPortAtValue JsChartViewer.getViewPortAtValue | Converts a value of the specified data scale to a view port coordinate.
WebChartViewer.syncLinearAxisWithViewPort | Synchronizes a linear Axis with the part of the data scale in view port.
WebChartViewer.syncLogAxisWithViewPort | Synchronizes a logarithmic Axis with the part of the data scale in view port.
WebChartViewer.syncDateAxisWithViewPort | Synchronizes a date/time Axis with the part of the data scale in view port.

In typical usage, WebChartViewer.setFullRange is used to define the full data ranges for the axes in the chart. WebChartViewer.getValueAtViewPort and WebChartViewer.getViewPortAtValue can then be used to map between data values and view port positions. WebChartViewer.syncLinearAxisWithViewPort, WebChartViewer.syncLogAxisWithViewPort and WebChartViewer.syncDateAxisWithViewPort can be used to synchronize the axis scale with the view port position.

If WebChartViewer.syncLinearAxisWithViewPort, WebChartViewer.syncLogAxisWithViewPort or WebChartViewer.syncDateAxisWithViewPort is called without first defining the full data range, ChartDirector will automatically configure the axis scale based on the data in the chart, and assume it to be the full data range. This is useful if the full data range is not known but must be inferred from the data.

Server Side Code Structure

The server side code needs to handle both the initial page request and subsequent AJAX chart updates. The first thing it needs to do is to distinguish which type of requests it is handling, so that it can execute the appropriate code. WebChartViewer.isPartialUpdateRequest can be used to detect if the current HTTP request is an AJAX chart update request.

Initial Page Request

In the initial page request, the chart image created can 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. In addition, the chart metrics (which contains the plot area position and size) should be obtained using BaseChart.getChartMetrics and set to the WebChartViewer using WebChartViewer.setChartMetrics. If an image map is available for the chart, it should be set to the WebChartViewer using WebChartViewer.setImageMap.

After setting up the WebChartViewer, WebChartViewer.renderHTML should be used to generate the HTML tags that represent the chart. These tags may then be inserted into the HTML web page to be sent to the browser.

AJAX Chart Updates

In an AJAX chart update, only the chart needs to be updated. Instead of using WebChartViewer.renderHTML to generate the HTML tags for the chart, the server should use WebChartViewer.partialUpdateChart to return an AJAX response to the browser.

Note that HTTP GET or POST parameters in the initial page request would no longer exist in subsequent AJAX chart updates. If these parameters are necessary in AJAX chart updates, they should be stored as custom attributes using WebChartViewer.setCustomAttr during initial page request. As custom attributes are persistent (they are transferred from the server to the browser and then transferred back to the server in AJAX chart updates), they can be retrieved using WebChartViewer.getCustomAttr and used in charting code.

Browser Side Code Structure

On the browser side, the typical code structure is:

  • 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 performing the initialization function in the onload event handler of the window object or the <BODY> tag. A typical example is:

    //
// Execute the following initialization code after the web page is loaded
//
JsChartViewer.addEventListener(window, 'load', function() {

    // Get the Javascript ChartViewer object (please replace idOfChartViewer below with
    // the real id used in your code)
    var viewer = JsChartViewer.get('idOfChartViewer');

    // Update the chart when the view port has changed (eg. when the user zooms in using the mouse)
    viewer.attachHandler("ViewPortChanged", viewer.partialUpdate);

    // Set the zoom and scroll mode to horizontal
    viewer.setScrollDirection(JsChartViewer.Horizontal);
    viewer.setZoomDirection(JsChartViewer.Horizontal);

    // Set the initial mouse usage to "scroll"
    viewer.setMouseUsage(JsChartViewer.Scroll);
    document.getElementById("scrollChart").checked = true;
});

  • If there are JsChartViewer.PreUpdate and JsChartViewer.PostUpdate event handlers, they can also be set up during initialization.

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.jsp | The standard utility script used in the <IMG> tag URL for retrieving the chart image from
cdjcv.js zoomin.cur zoomout.cur nozoom.cur wait.gif spacer.gif | The script file for JsChartViewer and the supporting cursor and image files. They must be in the same directory.

Zooming and Scrolling Examples

Sample Code | Description
Simple Zooming and Scrolling (Web) | A simple zoomable and scrollable chart with tooltips, using mouse click and drag to control zooming and scrolling.
Zooming and Scrolling with Track Line (Web) | Besides using mouse click and drag for zooming and scrolling, this example has buttons for jumping immediately to display data for the last 30 days, last 90 days, last year or all time. There are check boxes to select the data series to plot, and an update button to immediately update the chart. In addition, the chart includes a track cursor that updates the legend dynamically to display the data values as the mouse cursor moves over the chart.
XY Zooming and Scrolling (Web) | This example demonstrates zooming and scrolling in both horizontal and vertical directions. In addition to using mouse click and drag, this example has a "navigation pad" which can be thought as a representation of the view port. You can drag the pad to move the view port around (that is, to perform 2D scrolling).


Simple Zooming and Scrolling (Web)

Simple Zooming and Scrolling (Web)

NOTE: This section describes Simple Zooming and Scrolling for web applications only. For Windows applications, please refer to Simple Zooming and Scrolling (Windows).

This sample program demonstrates simple zoomable and scrollable chart with tooltips, using mouse click and drag to control zooming and scrolling.

The main source code listing of this sample program is included at the end of this section. The code consists of the following main parts:

  • initViewer: This function is for initializing the WebChartViewer during initial page request. It sets up the full data range of the view port, the initial visible range, as well as the maximum zoom in ratio allowed.

  • drawChart: This is the main charting code. It first gets the visible data range from the view port using WebChartViewer.getValueAtViewPort. Then it gets the data in that data range. After that it plots the chart as usual, with the x-axis configured to synchronize with the view port using WebChartViewer.syncDateAxisWithViewPort.

  • HTML: The HTML part of the code implements the web page. WebChartViewer.renderHTML is used to generate the tags for the chart image. Javascript code is used in the onclick handler of the radio buttons to allow them to control the mouse usage.

  • window onload event handler: The event handler, set up using JsChartViewer.addEventListener, is used to initialize the browser side user interface. It configures the JsChartViewer.ViewPortChanged event to trigger an AJAX chart update. The the mouse usage is initialized to JsChartViewer.Scroll for drag to scroll.

When the script starts to run , the first thing it does is to use WebChartViewer.isPartialUpdateRequest to detect if it is handling an AJAX chart update or an initial page request. If it is an AJAX chart update, it just draws the chart and sends back an AJAX response using WebChartViewer.partialUpdateChart, then terminates the request. If it is an initial page request, it initializes the WebChartViewer, draws the chart, and sends the HTML contents to the browser as usual.

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
simplezoomscroll.jsp | Main source code for this demo.
getchart.jsp | The standard utility script used in the image url for retrieving the chart image from
cdjcv.js zoomin.cur zoomout.cur nozoom.cur wait.gif spacer.gif | The script file for JsChartViewer, and the supporting cursor and image files. They must be in the same directory.

Source Code Listing

[JSP Version] jspdemo/simplezoomscroll.jsp
<%@page import="ChartDirector.*, java.util.*"%>
<%!
//
// Initialize the WebChartViewer when the page is first loaded
//
private void initViewer(WebChartViewer viewer)
{
    // The full x-axis range is from Jan 1, 2007 to Jan 1, 2012
    Date startDate = new GregorianCalendar(2007, 0, 1).getTime();
    Date endDate = new GregorianCalendar(2012, 0, 1).getTime();
    viewer.setFullRange("x", startDate, endDate);

    // Initialize the view port to show the last 366 days (out of 1826 days)
    viewer.setViewPortWidth(366.0 / 1826);
    viewer.setViewPortLeft(1 - viewer.getViewPortWidth());

    // Set the maximum zoom to 10 days (out of 1826 days)
    viewer.setZoomInWidthLimit(10.0 / 1826);
}

//
// Draw the chart
//
private void drawChart(WebChartViewer viewer)
{
    // Determine the visible x-axis range
    Date viewPortStartDate = Chart.NTime(viewer.getValueAtViewPort("x", viewer.getViewPortLeft()));
    Date viewPortEndDate = Chart.NTime(viewer.getValueAtViewPort("x", viewer.getViewPortLeft() +
        viewer.getViewPortWidth()));

    // We need to get the data within the visible x-axis range. In real code, this can be by using a
    // database query or some other means as specific to the application. In this demo, we just
    // generate a random data table, and then select the data within the table.

    // Generate the random data table
    RanTable r = new RanTable(127, 4, 1828);
    r.setDateCol(0, new GregorianCalendar(2007, 0, 1).getTime(), 86400);
    r.setCol(1, 150, -10, 10);
    r.setCol(2, 200, -10, 10);
    r.setCol(3, 250, -8, 8);

    // Select the data for the visible date range viewPortStartDate to viewPortEndDate. It is
    // possible there is no data point at exactly viewPortStartDate or viewPortEndDate. In this
    // case, we also need the data points that are just outside the visible date range to "overdraw"
    // the line a little bit (the "overdrawn" part will be clipped to the plot area) In this demo,
    // we do this by adding a one day margin to the date range when selecting the data.
    r.selectDate(0, new Date(viewPortStartDate.getTime() - 86400000), new Date(
        viewPortEndDate.getTime() + 86400000));

    // The selected data from the random data table
    Date[] timeStamps = Chart.NTime(r.getCol(0));
    double[] dataSeriesA = r.getCol(1);
    double[] dataSeriesB = r.getCol(2);
    double[] dataSeriesC = r.getCol(3);

    //
    // Now we have obtained the data, we can plot the chart.
    //

    //================================================================================
    // Configure overall chart appearance.
    //================================================================================

    // Create an XYChart object 600 x 300 pixels in size, with pale blue (f0f0ff) background, black
    // (000000) rounded border, 1 pixel raised effect.
    XYChart c = new XYChart(600, 300, 0xf0f0ff, 0x000000);
    c.setRoundedFrame();

    // Set the plotarea at (52, 60) and of size 520 x 205 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, 205, 0xffffff, -1, -1, 0xcccccc, 0xcccccc);

    // As the data can lie outside the plotarea in a zoomed chart, we need to enable clipping.
    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("Product Line International Market Price", "Times New Roman Bold Italic", 15
        ).setBackground(0xccccff, 0x000000, Chart.glassEffect());

    // 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(Chart.Transparent, Chart.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);

    //================================================================================
    // Add data to chart
    //================================================================================

    //
    // In this example, we represent the data by lines. You may modify the code below to use other
    // representations (areas, scatter plot, etc).
    //

    // Add a line layer for the lines, using a line width of 2 pixels
    LineLayer layer = c.addLineLayer2();
    layer.setLineWidth(2);

    // In this demo, we do not have too many data points. In real code, the chart may contain a lot
    // of data points when fully zoomed out - much more than the number of horizontal pixels in this
    // plot area. So it is a good idea to use fast line mode.
    layer.setFastLineMode();

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

    //================================================================================
    // Configure axis scale and labelling
    //================================================================================

    // Set the x-axis as a date/time axis with the scale according to the view port x range.
    viewer.syncDateAxisWithViewPort("x", c.xAxis());

    // In this demo, we rely on ChartDirector to auto-label the axis. We ask ChartDirector to ensure
    // the x-axis labels are at least 75 pixels apart to avoid too many labels.
    c.xAxis().setTickDensity(75);

    //================================================================================
    // Output the chart
    //================================================================================

    // Output the chart
    String chartQuery = c.makeSession(viewer.getRequest(), viewer.getId());

    // Include tool tip for the chart
    String imageMap = c.getHTMLImageMap("", "",
        "title='[{dataSetName}] {x|mmm dd, yyyy}: USD {value|2}'");

    // Set the chart URL, image map and chart metrics to the viewer
    viewer.setImageUrl("getchart.jsp?" + chartQuery);
    viewer.setImageMap(imageMap);
    viewer.setChartMetrics(c.getChartMetrics());
}
%>
<%

//
// This script handles both the full page request, as well as the subsequent partial updates (AJAX
// chart updates). We need to determine the type of request first before we processing it.
//

// Create the WebChartViewer object
WebChartViewer viewer = new WebChartViewer(request, "chart1");

if (viewer.isPartialUpdateRequest()) {
    // Is a partial update request. Draw the chart and perform a partial response.
    drawChart(viewer);
    out.clear();
    viewer.partialUpdateChart(response);
    return;
}

//
// If the code reaches here, it is a full page request.
//

// In this exapmle, we just need to initialize the WebChartViewer and draw the chart.
initViewer(viewer);
drawChart(viewer);
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <title>Simple Zooming and Scrolling</title>
    <script type="text/javascript" src="cdjcv.js"></script>
</head>
<body style="margin:0px;">
<script type="text/javascript">

//
// Execute the following initialization code after the web page is loaded
//
JsChartViewer.addEventListener(window, 'load', function() {
    // Update the chart when the view port has changed (eg. when the user zooms in using the mouse)
    var viewer = JsChartViewer.get('<%=viewer.getId()%>');
    viewer.attachHandler("ViewPortChanged", viewer.partialUpdate);

    // Set the initial mouse usage to "scroll"
    viewer.setMouseUsage(JsChartViewer.Scroll);
    document.getElementById("scrollChart").checked = true;
});

</script>
<form method="post">
<table cellspacing="0" cellpadding="0" border="0">
    <tr>
        <td align="right" colspan="2" style="background:#000088">
            <div style="padding:0px 3px 2px 0px; font:italic bold 10pt 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:127px; background:#c0c0ff; border-right:black 1px solid; border-bottom:black 1px solid;">
        <div style="font:9pt Verdana; padding:10px 0px 0px 3px; line-height:1.5; width:127px">
            <!-- The onclick handler of the following radio buttons sets the mouse usage mode. -->
            <input name="mouseUsage" id="scrollChart" type="radio"
                onclick="JsChartViewer.get('<%=viewer.getId()%>').setMouseUsage(JsChartViewer.Scroll)" />
            Drag To Scroll<br />
            <input name="mouseUsage" id="zoomInChart" type="radio"
                onclick="JsChartViewer.get('<%=viewer.getId()%>').setMouseUsage(JsChartViewer.ZoomIn)" />
            Zoom In<br />
            <input name="mouseUsage" id="zoomOutChart" type="radio"
                onclick="JsChartViewer.get('<%=viewer.getId()%>').setMouseUsage(JsChartViewer.ZoomOut)" />
            Zoom Out<br />
        </div>
        </td>
        <td>
            <div style="font-weight:bold; font-size:20pt; margin:5px 0px 0px 5px; font-family:Arial">
                Simple Zooming and Scrolling
            </div>
            <hr style="border:solid 1px #000080" />
            <div style="padding:0px 5px 5px 10px">
                <!-- ****** Here is the chart image ****** -->
                <%=viewer.renderHTML(response)%>
            </div>
        </td>
    </tr>
</table>
</form>
</body>
</html>


Zooming and Scrolling with Track Line (Web)

Zooming and Scrolling with Track Line (Web)

NOTE: This section describes Zooming and Scrolling with Track Line for web applications only. For Windows applications, please refer to Zooming and Scrolling with Track Line (1) (Windows).

Besides using mouse click and drag for zooming and scrolling, this example has buttons for jumping immediately to display data for the last 30 days, last 90 days, last year or all time. There are check boxes to select the data series to plot, and an update button to immediately update the chart. In addition, the chart includes a track cursor that updates the legend dynamically to display the data values as the mouse cursor moves over the chart.

The main source code listing of this sample program is included at the end of this section. The code consists of the following main parts:

  • initViewer: This function is for initializing the WebChartViewer during initial page request. It sets up the full data range of the view port, the initial visible range, as well as the maximum zoom in ratio allowed.

  • drawChart: This is the main charting code. It first gets the visible data range from the view port using WebChartViewer.getValueAtViewPort. Then it gets the data in that data range. After that it plots the chart as usual. Up to 3 data series are added to the chart depending on user selection. The x-axis is configured to synchronize with the view port using WebChartViewer.syncDateAxisWithViewPort. In this sample program, Axis.setFormatCondition, Axis.setMultiFormat and Axis.setMultiFormat2 are used to choose select different x-axis label format depending on the axis scale. The code outputs both the image and the Javascript Chart Model of the chart for track cursor support.

  • HTML: The HTML part of the code implements the web page. WebChartViewer.renderHTML is used to generate the tags for the chart image. Javascript is used in the onclick event handler of the push buttons to set the mouse usage mode and the display time range.

  • window onload event handler: The event handler, set up using JsChartViewer.addEventListener, is used to initialize the browser side user interface. It configures the JsChartViewer.ViewPortChanged event as well as the "Update Chart" button to trigger an AJAX chart update. It sets up a JsChartViewer.PreUpdate event handler to copy the state of the check boxes to custom attributes, so that the server can receive them and draw the chart based on these attributes. The mouse usage is initialized to JsChartViewer.Scroll for drag to scroll. Finally, a JsChartViewer.MouseMovePlotArea event handler is set up to call trackLineLegend to draw the track cursor. The code also directly calls trackLineLegend to initialize the track cursor to the right side of the plot area. This is to ensure the chart initially has a legend that reflects the latest data values.

  • trackLineLegend: This function implements the track cursor, and is essentially the same as the track cursor drawing code in Track Line with Legend (Web). Please refer to that example for the explanation of the code.

  • setMouseUsage: This function is called by the onclick event handler of the Pointer, Zoom In and Zoom Out push buttons to set the mouse usage mode.

  • setTimeRange: This function is called by the Last N days push buttons to update the view port to reflect the chosen date range. After updating the view port, it uses JsChartViewer.raiseViewPortChangedEvent to raise a JsChartViewer.ViewPortChanged event, which should lead to an AJAX chart update.

When the script starts to run , the first thing it does is to use WebChartViewer.isPartialUpdateRequest to detect if it is handling an AJAX chart update or an initial page request. If it is an AJAX chart update, it just draws the chart and sends back an AJAX response using WebChartViewer.partialUpdateChart, then terminates the request. If it is an initial page request, it initializes the WebChartViewer, draws the chart, and sends the HTML contents to the browser as usual.

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
zoomscrolltrack.jsp | Main source code for this demo.
pointer.gif zoomInIcon.gif zoomOutIcon.gif goto.gif | The images used in the push buttons in this demo.
getchart.jsp | The standard utility script used in the image url for retrieving the chart image from
cdjcv.js zoomin.cur zoomout.cur nozoom.cur wait.gif spacer.gif | The script file for JsChartViewer, and the supporting cursor and image files. They must be in the same directory.

Source Code Listing

[JSP Version] jspdemo/zoomscrolltrack.jsp
<%@page import="ChartDirector.*, java.util.*"%>
<%!
//
// Initialize the WebChartViewer when the page is first loaded
//
private void initViewer(WebChartViewer viewer)
{
    // The full x-axis range is from Jan 1, 2007 to Jan 1, 2012
    Date startDate = new GregorianCalendar(2007, 0, 1).getTime();
    Date endDate = new GregorianCalendar(2012, 0, 1).getTime();
    viewer.setFullRange("x", startDate, endDate);

    // Initialize the view port to show the last 366 days (out of 1826 days)
    viewer.setViewPortWidth(366.0 / 1826);
    viewer.setViewPortLeft(1 - viewer.getViewPortWidth());

    // Set the maximum zoom to 10 days (out of 1826 days)
    viewer.setZoomInWidthLimit(10.0 / 1826);
}

//
// Draw the chart
//
private void drawChart(WebChartViewer viewer)
{
    // Determine the visible x-axis range
    Date viewPortStartDate = Chart.NTime(viewer.getValueAtViewPort("x", viewer.getViewPortLeft()));
    Date viewPortEndDate = Chart.NTime(viewer.getValueAtViewPort("x", viewer.getViewPortLeft() +
        viewer.getViewPortWidth()));

    // We need to get the data within the visible x-axis range. In real code, this can be by using a
    // database query or some other means as specific to the application. In this demo, we just
    // generate a random data table, and then select the data within the table.

    // Generate the random data table
    RanTable r = new RanTable(127, 4, 1828);
    r.setDateCol(0, new GregorianCalendar(2007, 0, 1).getTime(), 86400);
    r.setCol(1, 150, -10, 10);
    r.setCol(2, 200, -10, 10);
    r.setCol(3, 250, -8, 8);

    // Select the data for the visible date range viewPortStartDate to viewPortEndDate. It is
    // possible there is no data point at exactly viewPortStartDate or viewPortEndDate. In this
    // case, we also need the data points that are just outside the visible date range to "overdraw"
    // the line a little bit (the "overdrawn" part will be clipped to the plot area) In this demo,
    // we do this by adding a one day margin to the date range when selecting the data.
    r.selectDate(0, new Date(viewPortStartDate.getTime() - 86400000), new Date(
        viewPortEndDate.getTime() + 86400000));

    // The selected data from the random data table
    Date[] timeStamps = Chart.NTime(r.getCol(0));
    double[] dataSeriesA = r.getCol(1);
    double[] dataSeriesB = r.getCol(2);
    double[] dataSeriesC = r.getCol(3);

    //
    // Now we have obtained the data, we can plot the chart.
    //

    //================================================================================
    // Configure overall chart appearance.
    //================================================================================

    // Create an XYChart object of size 640 x 350 pixels
    XYChart c = new XYChart(640, 350);

    // Set the plotarea at (55, 55) with width 80 pixels less than chart width, and height 90 pixels
    // less than chart height. Use a vertical gradient from light blue (f0f6ff) to sky blue (a0c0ff)
    // as background. Set border to transparent and grid lines to white (ffffff).
    c.setPlotArea(55, 55, c.getWidth() - 80, c.getHeight() - 90, c.linearGradientColor(0, 55, 0,
        c.getHeight() - 35, 0xf0f6ff, 0xa0c0ff), -1, Chart.Transparent, 0xffffff, 0xffffff);

    // As the data can lie outside the plotarea in a zoomed chart, we need to enable clipping.
    c.setClipping();

    // Add a title to the chart using 18 pts Times New Roman Bold Italic font
    c.addTitle("    Zooming and Scrolling with Track Line", "Times New Roman Bold Italic", 18);

    // Set the axis stem to transparent
    c.xAxis().setColors(Chart.Transparent);
    c.yAxis().setColors(Chart.Transparent);

    // Add axis title using 10pts Arial Bold Italic font
    c.yAxis().setTitle("Ionic Temperature (C)", "Arial Bold Italic", 10);

    //================================================================================
    // Add data to chart
    //================================================================================

    //
    // In this example, we represent the data by lines. You may modify the code below to use other
    // layer types (areas, scatter plot, etc).
    //

    // Add a line layer for the lines, using a line width of 2 pixels
    LineLayer layer = c.addLineLayer2();
    layer.setLineWidth(2);

    // In this demo, we do not have too many data points. In real code, the chart may contain a lot
    // of data points when fully zoomed out - much more than the number of horizontal pixels in this
    // plot area. So it is a good idea to use fast line mode.
    layer.setFastLineMode();

    // Add up to 3 data series to a line layer, depending on whether the user has selected the data
    // series.
    layer.setXData(timeStamps);
    if (!"F".equals(viewer.getCustomAttr("data0CheckBox"))) {
        layer.addDataSet(dataSeriesA, 0xff3333, "Alpha Series");
    }
    if (!"F".equals(viewer.getCustomAttr("data1CheckBox"))) {
        layer.addDataSet(dataSeriesB, 0x008800, "Beta Series");
    }
    if (!"F".equals(viewer.getCustomAttr("data2CheckBox"))) {
        layer.addDataSet(dataSeriesC, 0x3333cc, "Gamma Series");
    }

    //================================================================================
    // Configure axis scale and labelling
    //================================================================================

    // Set the x-axis as a date/time axis with the scale according to the view port x range.
    viewer.syncDateAxisWithViewPort("x", c.xAxis());

    //
    // In this demo, the time range can be from a few years to a few days. We demonstrate how to set
    // up different date/time format based on the time range.
    //

    // If all ticks are yearly aligned, then we use "yyyy" as the label format.
    c.xAxis().setFormatCondition("align", 360 * 86400);
    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", 30 * 86400);
    c.xAxis().setMultiFormat(Chart.StartOfYearFilter(), "<*font=bold*>{value|mmm yyyy}",
        Chart.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(Chart.StartOfYearFilter(),
        "<*block,halign=left*><*font=bold*>{value|mmm dd<*br*>yyyy}", Chart.StartOfMonthFilter(),
        "<*font=bold*>{value|mmm dd}");
    c.xAxis().setMultiFormat2(Chart.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(Chart.StartOfDayFilter(), "<*font=bold*>{value|hh:nn<*br*>mmm dd}",
        Chart.AllPassFilter(), "{value|hh:nn}");

    //================================================================================
    // Step 5 - Output the chart
    //================================================================================

    // Output the chart
    String chartQuery = c.makeSession(viewer.getRequest(), viewer.getId());

    // Set the chart URL to the viewer
    viewer.setImageUrl("getchart.jsp?" + chartQuery);

    // Output Javascript chart model to the browser to support tracking cursor
    viewer.setChartModel(c.getJsChartModel());
}
%>
<%

//
// This script handles both the full page request, as well as the subsequent partial updates (AJAX
// chart updates). We need to determine the type of request first before we processing it.
//

// Create the WebChartViewer object
WebChartViewer viewer = new WebChartViewer(request, "chart1");

if (viewer.isPartialUpdateRequest()) {
    // Is a partial update request. Draw the chart and perform a partial response.
    drawChart(viewer);
    out.clear();
    viewer.partialUpdateChart(response);
    return;
}

//
// If the code reaches here, it is a full page request.
//

// In this exapmle, we just need to initialize the WebChartViewer and draw the chart.
initViewer(viewer);
drawChart(viewer);
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <title>Zooming and Scrolling with Track Line</title>
    <script type="text/javascript" src="cdjcv.js"></script>
    <style type="text/css">
        div.chartPushButton { padding:5px; cursor:hand; }
        div.chartPushButton:hover { background-color: #EEEEFF; }
        div.chartPushButtonPressed { padding:5px; cursor:hand; background-color: #CCFFCC; }
        td.chartPushButton { font:12px Verdana; border-bottom:#000000 1px solid; }
    </style>
</head>
<body style="margin:0px;">
<script type="text/javascript">

//
// Execute the following initialization code after the web page is loaded
//
JsChartViewer.addEventListener(window, 'load', function() {
    // Update the chart when the view port has changed (eg. when the user zooms in using the mouse)
    var viewer = JsChartViewer.get('<%=viewer.getId()%>');
    viewer.attachHandler("ViewPortChanged", viewer.partialUpdate);

    // The Update Chart can also trigger a view port changed event to update the chart.
    document.getElementById("SubmitButton").onclick = function() { viewer.raiseViewPortChangedEvent(); return false; };

    // Before sending the update request to the server, we include the state of the check boxes as custom
    // attributes. The server side charting code will use these attributes to decide the data sets to draw.
    viewer.attachHandler("PreUpdate", function() {
        var checkBoxes = ["data0CheckBox", "data1CheckBox", "data2CheckBox"];
        for (var i = 0; i < checkBoxes.length; ++i)
            viewer.setCustomAttr(checkBoxes[i], document.getElementById(checkBoxes[i]).checked ? "T" : "F");
    });

    // Set the initial mouse usage to "scroll"
    setMouseMode(JsChartViewer.Scroll);

    // Draw track cursor when mouse is moving over plotarea or if the chart updates
    viewer.attachHandler(["MouseMovePlotArea", "PostUpdate"], function(e) {
        trackLineLegend(viewer, viewer.getPlotAreaMouseX());
    });

    // Initialize the track legend to show the rightmost data point
    trackLineLegend(viewer, viewer.getPlotAreaMouseX());
});

//
// Draw track line with legend
//
function trackLineLegend(viewer, mouseX)
{
    // Remove all previously drawn tracking object
    viewer.hideObj("all");

    // The chart and its plot area
    var c = viewer.getChart();
    var plotArea = c.getPlotArea();

    // Get the data x-value that is nearest to the mouse, and find its pixel coordinate.
    var xValue = c.getNearestXValue(mouseX);
    var xCoor = c.getXCoor(xValue);
    if (xCoor == null)
        return;

    // Draw a vertical track line at the x-position
    viewer.drawVLine("trackLine", xCoor, plotArea.getTopY(), plotArea.getBottomY(), "black 1px dotted");

    // Array to hold the legend entries
    var legendEntries = [];

    // Iterate through all layers to build the legend array
    for (var i = 0; i < c.getLayerCount(); ++i)
    {
        var layer = c.getLayerByZ(i);

        // The data array index of the x-value
        var xIndex = layer.getXIndexOf(xValue);

        // Iterate through all the data sets in the layer
        for (var j = 0; j < layer.getDataSetCount(); ++j)
        {
            var dataSet = layer.getDataSetByZ(j);

            // We are only interested in visible data sets with names, as they are required for legend entries.
            var dataName = dataSet.getDataName();
            var color = dataSet.getDataColor();
            if ((!dataName) || (color == null))
                continue;

            // Build the legend entry, consist of a colored square box, the name and the data value.
            var dataValue = dataSet.getValue(xIndex);
            legendEntries.push("<nobr>" + viewer.htmlRect(7, 7, color) + " " + dataName + ": " +
                ((dataValue == null) ? "N/A" : dataValue.toPrecision(4)) + viewer.htmlRect(20, 0) + "</nobr> ");

            // Draw a track dot for data points within the plot area
            var yCoor = c.getYCoor(dataSet.getPosition(xIndex), dataSet.getUseYAxis());
            if ((yCoor != null) && (yCoor >= plotArea.getTopY()) && (yCoor <= plotArea.getBottomY()))
            {
                viewer.showTextBox("dataPoint" + i + "_" + j, xCoor, yCoor, JsChartViewer.Center,
                    viewer.htmlRect(7, 7, color));
            }
        }
    }

    // Create the legend by joining the legend entries.
    var legend = "<nobr>[" + c.xAxis().getFormattedLabel(xValue, "mm/dd/yyyy") + "]" + viewer.htmlRect(20, 0) +
        "</nobr> " + legendEntries.reverse().join("");

    // Display the legend on the top of the plot area
    viewer.showTextBox("legend", plotArea.getLeftX(), plotArea.getTopY(), JsChartViewer.BottomLeft, legend,
        "width:" + (plotArea.getWidth() - 1) + "px;font:bold 11px Arial;padding:3px;");
}

//
// This method is called when the user clicks on the Pointer, Zoom In or Zoom Out buttons
//
function setMouseMode(mode)
{
    // Set the button color based on the selected mouse mode
    document.getElementById("scrollButton").className =
        (mode  == JsChartViewer.Scroll) ? "chartPushButtonPressed" : "chartPushButton";
    document.getElementById("zoomInButton").className =
        (mode  == JsChartViewer.ZoomIn) ? "chartPushButtonPressed" : "chartPushButton";
    document.getElementById("zoomOutButton").className =
        (mode  == JsChartViewer.ZoomOut) ? "chartPushButtonPressed" : "chartPushButton";

    // Set the mouse mode
    JsChartViewer.get('<%=viewer.getId()%>').setMouseUsage(mode);
}

//
// This method is called when the user clicks on the buttons that selects the last NN days
//
function setTimeRange(duration)
{
    var viewer = JsChartViewer.get('<%=viewer.getId()%>');

    // Set the view port width to represent the required duration (as a ratio to the total x-range)
    viewer.setViewPortWidth(Math.min(1, duration / (viewer.getValueAtViewPort("x", 1) - viewer.getValueAtViewPort("x", 0))));

    // Set the view port left so that the view port is moved to show the latest data
    viewer.setViewPortLeft(1 - viewer.getViewPortWidth());

    // Trigger a view port change event
    viewer.raiseViewPortChangedEvent();
}

</script>
<form method="post">
<table cellspacing="0" cellpadding="0" style="border:black 1px solid;">
    <tr>
        <td align="right" colspan="2" style="background:#000088; color:#ffff00; padding:0px 4px 2px 0px;">
            <a style="color:#FFFF00; font:italic bold 10pt Arial; text-decoration:none" href="http://www.advsofteng.com/">
                Advanced Software Engineering
            </a>
        </td>
    </tr>
    <tr valign="top">
        <td style="width:130px; background:#c0c0ff;">
           <div style="width:130px">
            <!-- The following table is to create 3 cells for 3 buttons to control the mouse usage mode. -->
            <table cellspacing="0" cellpadding="0" width="100%" border="0">
                <tr>
                    <td class="chartPushButton">
                        <div class="chartPushButton" id="scrollButton" onclick="setMouseMode(JsChartViewer.Scroll)">
                            <img src="pointer.gif" style="vertical-align:middle" alt="Pointer" />&nbsp;&nbsp;Pointer
                        </div>
                    </td>
                </tr>
                <tr>
                    <td class="chartPushButton">
                        <div class="chartPushButton" id="zoomInButton" onclick="setMouseMode(JsChartViewer.ZoomIn)">
                            <img src="zoomInIcon.gif" style="vertical-align:middle" alt="Zoom In" />&nbsp;&nbsp;Zoom In
                        </div>
                    </td>
                </tr>
                <tr>
                    <td class="chartPushButton">
                        <div class="chartPushButton" id="zoomOutButton" onclick="setMouseMode(JsChartViewer.ZoomOut)">
                            <img src="zoomOutIcon.gif" style="vertical-align:middle" alt="Zoom Out" />&nbsp;&nbsp;Zoom Out
                        </div>
                    </td>
                </tr>
                <tr>
                    <td class="chartPushButton">
                        <div style="padding:6px;">
                            &nbsp;&nbsp;
                        </div>
                    </td>
                </tr>
                <tr>
                    <td class="chartPushButton">
                        <div class="chartPushButton" onclick='setTimeRange(30 * 86400);'>
                            <img src="goto.gif" style="vertical-align:middle" alt="Last 30 days" />&nbsp;&nbsp;Last 30 days
                        </div>
                    </td>
                </tr>
                <tr>
                    <td class="chartPushButton">
                        <div class="chartPushButton" onclick='setTimeRange(90 * 86400);'>
                            <img src="goto.gif" style="vertical-align:middle" alt="Last 90 days" />&nbsp;&nbsp;Last 90 days
                        </div>
                    </td>
                </tr>
                <tr>
                    <td class="chartPushButton">
                        <div class="chartPushButton" onclick='setTimeRange(366 * 86400);'>
                            <img src="goto.gif" style="vertical-align:middle" alt="Last Year" />&nbsp;&nbsp;Last Year
                        </div>
                    </td>
                </tr>
                <tr>
                    <td class="chartPushButton">
                        <div class="chartPushButton" onclick='setTimeRange(1E15);'>
                            <img src="goto.gif" style="vertical-align:middle" alt="All Time" />&nbsp;&nbsp;All Time
                        </div>
                    </td>
                </tr>
            </table>
            <div style="font:9pt Verdana; line-height:1.5; padding-top:25px">
            <input id="data0CheckBox" type="checkbox" checked="checked" /> Alpha Series<br />
            <input id="data1CheckBox" type="checkbox" checked="checked" /> Beta Series<br />
            <input id="data2CheckBox" type="checkbox" checked="checked" /> Gamma Series<br />
            </div>
            <div style="font:9pt Verdana; margin-top:15px; text-align:center">
                <input type="submit" id="SubmitButton" name="SubmitButton" value="Update Chart"></input>
            </div>
        </div>
        </td>
        <td style="border-left:black 1px solid; padding:10px 5px 0px 5px;">
            <!-- ****** Here is the chart image ****** -->
            <%=viewer.renderHTML(response)%>
        </td>
    </tr>
</table>
</form>
</body>
</html>


XY Zooming and Scrolling (Web)

XY Zooming and Scrolling (Web)

NOTE: This section describes XY Zooming and Scrolling for web applications only. For Windows applications, please refer to XY Zooming and Scrolling (Windows).

This example demonstrates zooming and scrolling in both horizontal and vertical directions. In addition to using mouse click and drag, this example has a "navigation pad" which can be thought as a representation of the view port. You can drag the pad to move the view port around (that is, to perform 2D scrolling).

The main source code listing of this sample program is included at the end of this section. The code consists of the following main parts:

  • initViewer: This function is for initializing the WebChartViewer during initial page request. In this example, we just use default values, so there is nothing to initialize.

  • drawChart: This is the main charting code. It plots the chart as usual, with the x-axis and y-axis configured to synchronize with the view port using WebChartViewer.syncDateAxisWithViewPort.

  • HTML: The HTML part of the code implements the web page. WebChartViewer.renderHTML is used to generate the tags for the chart image. Javascript is used in the onclick event handler of the push buttons to set the mouse usage mode.

  • window onload event handler: The event handler, set up using JsChartViewer.addEventListener, is used to initialize the browser side user interface. It configures the JsChartViewer.ViewPortChanged event to trigger an AJAX chart update. The mouse usage is initialized to JsChartViewer.ZoomIn. Finally, it binds the "navigation pad" to the JsChartViewer, so that the "navigator pad" can be used to visualize and control the view port.

  • setMouseUsage: This function is called by the onclick event handler of the Pointer, Zoom In and Zoom Out push buttons to set the mouse usage mode.

  • Navigation Pad Implementation: The navigation pad is represented in HTML as two <DIV> blocks, with one as the container and the other as the draggable rectangle inside. The Javascript method initNavigationPad sets up the event handlers for the navigation pad, so that it can be dragged, and be updated when the view port changes. The updateNavigationPad updates the position and size of the navigation pad to reflect the view port. The NavigationPad_mouseDown and NavigationPad_mouseMove event handlers allow the user to click and drag the navigation pad. The NavigationPad_mouseUp event handler completes the drag by updating the view port to reflect the final navigation pad position and raise a view port changed event.

When the script starts to run , the first thing it does is to use WebChartViewer.isPartialUpdateRequest to detect if it is handling an AJAX chart update or an initial page request. If it is an AJAX chart update, it just draws the chart and sends back an AJAX response using WebChartViewer.partialUpdateChart, then terminates the request. If it is an initial page request, it initializes the WebChartViewer, draws the chart, and sends the HTML contents to the browser as usual.

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
xyzoomscroll.jsp | Main source code for this demo.
pointer.gif zoomInIcon.gif zoomOutIcon.gif | The images used in the push buttons in this demo.
getchart.jsp | The standard utility script used in the image url for retrieving the chart image from
cdjcv.js zoomin.cur zoomout.cur nozoom.cur wait.gif spacer.gif | The script file for JsChartViewer, and the supporting cursor and image files. They must be in the same directory.

Source Code Listing

[JSP Version] jspdemo/xyzoomscroll.jsp
<%@page import="ChartDirector.*, java.util.*"%>
<%!
//
// Initialize the WebChartViewer when the page is first loaded
//
private void initViewer(WebChartViewer viewer)
{
    //
    // In this example, we just use default values, so there is nothing to initialize.
    //
}

//
// Draw the chart
//
private void drawChart(WebChartViewer viewer)
{
    //
    // For simplicity, in this demo, the data arrays are filled with hard coded data. In a real
    // application, you may use a database or other data source to load up the arrays.
    //
    double[] dataX0 = {10, 15, 6, -12, 14, -8, 13, -3, 16, 12, 10.5, -7, 3, -10, -5, 2, 5};
    double[] dataY0 = {130, 150, 80, 110, -110, -105, -130, -15, -170, 125, 125, 60, 25, 150, 150,
        15, 120};
    double[] dataX1 = {6, 7, -4, 3.5, 7, 8, -9, -10, -12, 11, 8, -3, -2, 8, 4, -15, 15};
    double[] dataY1 = {65, -40, -40, 45, -70, -80, 80, 10, -100, 105, 60, 50, 20, 170, -25, 50, 75};
    double[] dataX2 = {-10, -12, 11, 8, 6, 12, -4, 3.5, 7, 8, -9, 3, -13, 16, -7.5, -10, -15};
    double[] dataY2 = {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
    XYChart c = new 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);

    // As the data can lie outside the plotarea in a zoomed chart, we need enable clipping
    c.setClipping();

    // Set 4 quadrant mode, with both x and y axes symetrical around the origin
    c.setAxisAtOrigin(Chart.XYAxisAtOrigin, Chart.XAxisSymmetric + Chart.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 legendBox = c.addLegend(450, 40, true, "Arial Bold", 8);
    legendBox.setAlignment(Chart.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. You may modify the code below to
    // use other layer types (lines, areas, etc).
    //

    // Add scatter layer, using 11 pixels red (ff33333) X shape symbols
    c.addScatterLayer(dataX0, dataY0, "Group A", Chart.Cross2Shape(), 11, 0xff3333);

    // Add scatter layer, using 11 pixels green (33ff33) circle symbols
    c.addScatterLayer(dataX1, dataY1, "Group B", Chart.CircleShape, 11, 0x33ff33);

    // Add scatter layer, using 11 pixels blue (3333ff) triangle symbols
    c.addScatterLayer(dataX2, dataY2, "Group C", Chart.TriangleSymbol, 11, 0x3333ff);

    //
    // In this example, we have not explicitly configured the full x and y range. In this case, the
    // first time syncLinearAxisWithViewPort is called, ChartDirector will auto-scale the axis and
    // assume the resulting range is the full range. In subsequent calls, ChartDirector will set the
    // axis range based on the view port and the full range.
    //
    viewer.syncLinearAxisWithViewPort("x", c.xAxis());
    viewer.syncLinearAxisWithViewPort("y", c.yAxis());

    // Output the chart
    String chartQuery = c.makeSession(viewer.getRequest(), viewer.getId());

    // Include tool tip for the chart
    String 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.jsp?" + chartQuery);
    viewer.setImageMap(imageMap);
    viewer.setChartMetrics(c.getChartMetrics());
}
%>
<%

//
// This script handles both the full page request, as well as the subsequent partial updates (AJAX
// chart updates). We need to determine the type of request first before we processing it.
//

// Create the WebChartViewer object
WebChartViewer viewer = new WebChartViewer(request, "chart1");

if (viewer.isPartialUpdateRequest()) {
    // Is a partial update request. Draw the chart and perform a partial response.
    drawChart(viewer);
    out.clear();
    viewer.partialUpdateChart(response);
    return;
}

//
// If the code reaches here, it is a full page request.
//

// In this exapmle, we just need to initialize the WebChartViewer and draw the chart.
initViewer(viewer);
drawChart(viewer);
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <title>XY Zooming and Scrolling</title>
    <script type="text/javascript" src="cdjcv.js"></script>
    <style type="text/css">
        div.chartPushButton { padding:5px; cursor:hand; }
        div.chartPushButton:hover { background-color: #EEEEFF; }
        div.chartPushButtonPressed { padding:5px; cursor:hand; background-color: #CCFFCC; }
        td.chartPushButton { font:12px Verdana; border-bottom:#000000 1px solid; }
    </style>
</head>
<body style="margin:0px">
<script type="text/javascript">

//
// Execute the following initialization code after the web page is loaded
//
JsChartViewer.addEventListener(window, 'load', function() {
    // Update the chart when the view port has changed (eg. when the user zooms in using the mouse)
    var viewer = JsChartViewer.get('<%=viewer.getId()%>');
    viewer.attachHandler("ViewPortChanged", viewer.partialUpdate);

    // Set the zoom and scroll mode to bi-directional
    viewer.setScrollDirection(JsChartViewer.HorizontalVertical);
    viewer.setZoomDirection(JsChartViewer.HorizontalVertical);

    // Set the initial mouse usage to "zoom in"
    setMouseMode(JsChartViewer.ZoomIn);

    // Initialize the navigation pad
    initNavigationPad('NavigationPad', viewer.getId());
});

//
// This method is called when the user clicks on the Pointer, Zoom In or Zoom Out buttons
//
function setMouseMode(mode)
{
    // Set the button color based on the selected mouse mode
    document.getElementById("scrollButton").className =
        (mode  == JsChartViewer.Scroll) ? "chartPushButtonPressed" : "chartPushButton";
    document.getElementById("zoomInButton").className =
        (mode  == JsChartViewer.ZoomIn) ? "chartPushButtonPressed" : "chartPushButton";
    document.getElementById("zoomOutButton").className =
        (mode  == JsChartViewer.ZoomOut) ? "chartPushButtonPressed" : "chartPushButton";

    // Set the mouse mode
    JsChartViewer.get('<%=viewer.getId()%>').setMouseUsage(mode);
}

//
// The following functions implements the Navigation Pad user interface
//

// Initialize the Navigation Pad user interface
function initNavigationPad(controlId, viewerId)
{
    // Get the draggable rectangle of the Navigation Pad and the Javascript ChartViewer
    var handle = document.getElementById(controlId);
    var viewer = JsChartViewer.get(viewerId);

    // Set up the mouse down event handler to initiate dragging
    handle.onmousedown = NavigationPad_mouseDown;

    // Remember the width and height of the outer container and the id of the associated Javascript ChartViewer
    var parent = handle.parentElement || handle.parentNode;
    handle.parentW = parent.clientWidth;
    handle.parentH = parent.clientHeight;
    handle.viewerId = viewerId;

    // Set up the Navigation Pad to reflect the current view port
    updateNavigationPad(controlId);

    // When the chart is updated (eg. when zoomed in), the Navigation Pad needs to be updated too.
    viewer.attachHandler("PostUpdate", function() { updateNavigationPad(controlId); });

    // The Navigation Pad has been set up, so can display it now.
    handle.style.visibility = "visible";
}

// Update the Navigation Pad to reflect the view port
function updateNavigationPad(controlId)
{
    // Get the draggable rectangle of the Navigation Pad and the Javascript ChartViewer
    var handle = document.getElementById(controlId);
    var viewer = JsChartViewer.get(handle.viewerId);

    // Set the size and position of the handle based on Javascript ChartViewer view port
    handle.currentWidth = Math.round(handle.parentW * viewer.getViewPortWidth());
    handle.currentHeight = Math.round(handle.parentH * viewer.getViewPortHeight());
    handle.currentX = Math.round(handle.parentW * viewer.getViewPortLeft());
    handle.currentY = Math.round(handle.parentH * viewer.getViewPortTop());

    handle.style.width = Math.max(0, (handle.currentWidth - handle.offsetWidth + parseInt(handle.style.width))) + "px";
    handle.style.height = Math.max(0, (handle.currentHeight - handle.offsetHeight + parseInt(handle.style.height))) + "px";
    handle.style.left = handle.currentX + "px";
    handle.style.top = handle.currentY + "px";
}

// The Navigation Pad mouse down event handler
function NavigationPad_mouseDown(e)
{
    // Prevent browser default action, if any.
    if (e && e.preventDefault) e.preventDefault();

    // To initiate drag and drop, we need to capture the mouse and handle the mouse move and mouse up
    if (document.onmousemove != NavigationPad_mouseMove)
    {
        if (this.setCapture) this.setCapture();

        // Remember the current onmousemove and onmouseup event handlers and replace them with our own handlers
        document.NavigationPad_onmousemovesave = document.onmousemove;
        document.NavigationPad_onmouseupsave = document.onmouseup;
        document.onmousemove = NavigationPad_mouseMove;
        document.onmouseup = NavigationPad_mouseUp;
    }

    // Remember the mouse down position
    document.activeNavigationPad = this;
    this.refX = this.currentX - (window.event || e).clientX;
    this.refY = this.currentY - (window.event || e).clientY;
}

// The Navigation Pad mouse move event handler
function NavigationPad_mouseMove(e)
{
    // Set the position of the navigation pad depending on how far the mouse has been dragged
    e = e || window.event;
    var handle = document.activeNavigationPad;
    handle.currentX = Math.max(0, Math.min(handle.refX + e.clientX, handle.parentW - handle.currentWidth));
    handle.currentY = Math.max(0, Math.min(handle.refY + e.clientY, handle.parentH - handle.currentHeight));
    handle.style.left = handle.currentX + "px";
    handle.style.top = handle.currentY + "px";
    return false;
}

// The Navigation Pad mouse up event handler
function NavigationPad_mouseUp(e)
{
    // Release the mouse and restore the original nmousemove and onmouseup event handlers
    if (this.releaseCapture) this.releaseCapture();
    document.onmousemove = document.NavigationPad_onmousemovesave;
    document.onmouseup = document.NavigationPad_onmouseupsave;

    // Get the draggable rectangle of the Navigation Pad and the Javascript ChartViewer
    var handle = document.activeNavigationPad;
    var viewer = JsChartViewer.get(handle.viewerId);

    // Compute the new view port position based on the handle position
    var newVpLeft = 0;
    var newVpTop = 0;
    if (viewer.getViewPortWidth() < 1)
        newVpLeft = handle.currentX / (handle.parentW - handle.currentWidth) * (1 - viewer.getViewPortWidth());
    if (viewer.getViewPortHeight() < 1)
        newVpTop = handle.currentY / (handle.parentH - handle.currentHeight) * (1 - viewer.getViewPortHeight());

    // Update the view port if the new view port position is different from the old position
    if ((Math.abs(viewer.getViewPortLeft() - newVpLeft) > 0.0000001) ||
        (Math.abs(viewer.getViewPortTop() - newVpTop) > 0.0000001))
    {
        viewer.setViewPortLeft(newVpLeft);
        viewer.setViewPortTop(newVpTop);
        viewer.raiseViewPortChangedEvent();
    }
}

</script>
<form method="post">
<table cellspacing="0" cellpadding="0" style="border:black 1px solid;">
    <tr>
        <td align="right" colspan="2" style="background:#000088; color:#ffff00; padding:0px 4px 2px 0px;">
            <a style="color:#FFFF00; font:italic bold 10pt Arial; text-decoration:none" href="http://www.advsofteng.com/">
                Advanced Software Engineering
            </a>
        </td>
    </tr>
    <tr valign="top">
        <td style="width:130px; background:#e0e0e0;">
            <!-- The following table is to create 3 cells for 3 buttons to control the mouse usage mode. -->
            <table cellspacing="0" cellpadding="0" width="100%" border="0">
                <tr>
                    <td class="chartPushButton">
                        <div class="chartPushButton" id="scrollButton" onclick="setMouseMode(JsChartViewer.Scroll)">
                            <img src="pointer.gif" style="vertical-align:middle" alt="Pointer" />&nbsp;&nbsp;Pointer
                        </div>
                    </td>
                </tr>
                <tr>
                    <td class="chartPushButton">
                        <div class="chartPushButton" id="zoomInButton" onclick="setMouseMode(JsChartViewer.ZoomIn)">
                            <img src="zoomInIcon.gif" style="vertical-align:middle" alt="Zoom In" />&nbsp;&nbsp;Zoom In
                        </div>
                    </td>
                </tr>
                <tr>
                    <td class="chartPushButton">
                        <div class="chartPushButton" id="zoomOutButton" onclick="setMouseMode(JsChartViewer.ZoomOut)">
                            <img src="zoomOutIcon.gif" style="vertical-align:middle" alt="Zoom Out" />&nbsp;&nbsp;Zoom Out
                        </div>
                    </td>
                </tr>
            </table>
            <br /><br /><br /><br />
            <div style="margin:10px 4px; text-align:center">
                <!-- The following two DIV blocks constitute the Navigation Pad and its container. -->
                <div style="border:black 1px solid; width:120px; height:120px; background-color:#c0c0ff; text-align:left">
                    <div id="NavigationPad" style="border:black 1px solid; visibility:hidden; width:60px; height:60px;
                        position:relative; background-color:#c0c0c0">
                        <img src="" style="display:none" height="1" width="1" alt="" />
                    </div>
                </div>
            </div>
        </td>
        <td style="border-left: black 1px solid; background-color: #c0c0ff; padding:5px">
            <!-- ****** Here is the chart image ****** -->
            <%=viewer.renderHTML(response)%>
        </td>
    </tr>
</table>
</form>
</body>
</html>


Realtime Charts

Realtime Charts

This section describes how to use ChartDirector to create realtime charts.

For Windows Applications

Realtime Charts (Windows)
Description of the general approach of creating realtime charts in ChartDirector for Windows applications.

Simple Realtime Chart (Windows)
This sample program demonstrates a Windows based realtime chart with configurable chart update rate.

Realtime Chart with Track Line (Windows)
In addition to using mouse click and drag, this example demonstrates using a scroll bar for scrolling, and mouse wheel for zooming. It also includes a track cursor that updates the legend dynamically to display the data values as the mouse cursor moves over the chart.

For Web Applications

Realtime Charts (Web)
Description of the general approach of creating realtime charts in ChartDirector for web applications.

Simple Realtime Chart (Web)
This sample program demonstrates a web based realtime chart with configurable chart update rate, in which the chart image is being updated via streaming.

Realtime Chart with Track Line (Web)
This sample program demonstrates a realtime chart with configurable chart update rate, in which the chart image is being updated via AJAX means. It includes a track cursor that updates the legend dynamically to display the data values as the mouse cursor moves over the chart. When the mouse is not over the chart, the track cursor will display the latest data values.


Realtime Charts (Windows)

Realtime Charts (Windows)

NOTE: This section describes Realtime Charts for Windows applications only. For web applications, please refer to Realtime Charts (Web).

For Windows applications, a realtime chart may be achieved by simply redrawing the chart periodically.

Typically, a data buffer is used to store the data to be displayed in the chart. A data update routine updates the values in the buffer in realtime. A charting routine uses the data in the buffer to create the chart.

If the data update rate is not very fast (eg. once per second), one can simply redraw the chart immediately when the data buffer is updated.

If the data update rate is very fast (eg. 1000 times per second), a better design is to update the data buffer and the chart asynchronously. In this case, the data update routine can still update the data buffer as fast as it needs to. The charting routine updates the chart at a slower rate, such as a few times per second. Essentially, the charting routine is taking a "snapshot" of the data buffer a few times per second and displays them on screen.

To facilitate creation of realtime charts with fast update rate (faster than several times per second), the ChartViewer control contains built-in rate control features. It ensures there is at least 20ms (configurable using ChartViewer.setUpdateInterval) between two consecutive chart updates. This allows the GUI to remain smooth and responsive even with extremely fast chart update rate.

To use the rate control features of ChartDirector, instead of updating the chart directly, ChartViewer.updateViewPort may be used to trigger the ViewPortChanged event, and the chart is updated in the event handler. ChartViewer will ensure there is at least 20ms between two ViewPortChanged events, and will delay the event and merge multiple events into one event if necessary.


Simple Realtime Chart (Windows)

Simple Realtime Chart (Windows)

NOTE: This section describes Simple Realtime Chart for Windows applications only. For web applications, please refer to Simple Realtime Chart (Web).

This sample program demonstrates a realtime chart with configurable chart update rate.

In this sample program, new values are generated by a random number generator driven by a timer. The values are "shifted" into data arrays, which are used for creating the chart.

The chart is updated by a second timer. This allows the chart update rate to be configurable independently from the data rate. Also, the chart can be "frozen" for easy reading, while the data can continue to update on the background.

To demonstrate the code structure for update rate control (even though for the update rate in this demo it is not necessary to have any rate control), instead of directly updating the chart, the chart update timer calls ChartViewer.updateViewPort to trigger the ViewPortListener.viewPortChanged event , and the chart is updated in its handler.

Source Code Listing

[Java Version] javademo/realtimedemo.java
import ChartDirector.*;
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class realtimedemo extends JFrame implements DemoModule
{
    //
    // Data to draw the chart. In this demo, the data buffer will be filled by a data generator,
    // triggered to run by a timer every 250ms. We plot the last 240 samples.
    //
    private final int dataInterval = 250;
    private final int sampleSize = 240;
    private Date[] timeStamps = new Date[sampleSize];
    private double[] dataSeriesA = new double[sampleSize];
    private double[] dataSeriesB = new double[sampleSize];
    private double[] dataSeriesC = new double[sampleSize];

    // This is an internal variable used by the real time random number generator so it knows what
    // timestamp should be used for the next data point.
    private Date nextDataTime;

    // Will set to true at the end of initialization
    private boolean hasFinishedInitialization;

    //
    // Controls in the JFrame
    //
    private JButton runPB;
    private JButton freezePB;
    private JComboBox samplePeriod;
    private ChartViewer chartViewer1;
    private javax.swing.Timer dataRateTimer;
    private javax.swing.Timer chartUpdateTimer;
    private JTextField valueA;
    private JTextField valueB;
    private JTextField valueC;

    //
    // The main method to allow this demo to run as a standalone program.
    //
    public static void main(String args[])
    {
        realtimedemo demo = new realtimedemo();
        demo.setDefaultCloseOperation(EXIT_ON_CLOSE);
        demo.setupFrame();
        demo.setVisible(true);
    }

    //
    // Set up the JFrame
    //
    private void setupFrame()
    {
        if (hasFinishedInitialization)
        {
            // Just restart the chart update if already initialized
            runPB.doClick();
            return;
        }

        // Set JFrame title to name of this demo program
        setTitle(toString());
        setResizable(false);

        if (getDefaultCloseOperation() != EXIT_ON_CLOSE)
        {
            // Stop chart updating when window is being closed
            addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) { freezePB.doClick(); }});
        }

        // Initialize the internal variable used by our random real time data generator.
        nextDataTime = new Date();

        // Font to use for user interface elements
        Font uiFont = new Font("Dialog", Font.PLAIN, 11);

        // Top label bar
        JLabel topLabel = new JLabel("Advanced Software Engineering");
        topLabel.setForeground(new Color(255, 255, 51));
        topLabel.setBackground(new Color(0, 0, 128));
        topLabel.setBorder(new javax.swing.border.EmptyBorder(2, 0, 2, 5));
        topLabel.setHorizontalAlignment(SwingConstants.RIGHT);
        topLabel.setOpaque(true);
        getContentPane().add(topLabel, BorderLayout.NORTH);

        // Left panel
        JPanel leftPanel = new JPanel(null);
        leftPanel.setBorder(BorderFactory.createRaisedBevelBorder());

        // Run push button
        runPB = new JButton("Run", new ImageIcon(getClass().getResource("play.gif")));
        runPB.setHorizontalAlignment(SwingConstants.LEFT);
        runPB.setMargin(new Insets(5, 5, 5, 5));
        runPB.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt)    {
                runPB_Clicked();
            }});
        leftPanel.add(runPB).setBounds(1, 0, 138, 24);

        // Freeze push button
        freezePB = new JButton("Freeze", new ImageIcon(getClass().getResource("pause.gif")));
        freezePB.setHorizontalAlignment(SwingConstants.LEFT);
        freezePB.setMargin(new Insets(5, 5, 5, 5));
        freezePB.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt)    {
                freezePB_Clicked();
            }});
        leftPanel.add(freezePB).setBounds(1, 24, 138, 24);

        // Update Period label
        leftPanel.add(new JLabel("Update Period (ms)")).setBounds(5, 60, 130, 20);

        // Update Period drop down list box
        samplePeriod = new JComboBox(new Object[] { "250", "500", "750", "1000", "1250", "1500",
            "1750", "2000" });
        samplePeriod.setSelectedItem("1000");
        samplePeriod.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                samplePeriod_ValueChanged(evt);
            }});
        leftPanel.add(samplePeriod).setBounds(5, 80, 130, 20);

        // Simulated Machine label
        leftPanel.add(new JLabel("Simulated Machine")).setBounds(5, 180, 130, 20);

        // Alpha Label
        JLabel alphaLabel = new JLabel("Alpha");
        alphaLabel.setFont(uiFont);
        leftPanel.add(alphaLabel).setBounds(5, 200, 60, 20);

        // Alpha value
        valueA = new JTextField();
        valueA.setEditable(false);
        leftPanel.add(valueA).setBounds(65, 200, 70, 20);

        // Beta label
        JLabel betaLabel = new JLabel("Beta");
        betaLabel.setFont(uiFont);
        leftPanel.add(betaLabel).setBounds(5, 220, 60, 20);

        // Beta value
        valueB = new JTextField();
        valueB.setEditable(false);
        leftPanel.add(valueB).setBounds(65, 220, 70, 20);

        // Gamma label
        JLabel gammaLabel = new JLabel("Gamma");
        gammaLabel.setFont(uiFont);
        leftPanel.add(gammaLabel).setBounds(5, 240, 60, 20);

        // Gamma value
        valueC = new JTextField();
        valueC.setEditable(false);
        leftPanel.add(valueC).setBounds(65, 240, 70, 20);

        // Total expected panel size
        leftPanel.setPreferredSize(new Dimension(140, 270));

        // Chart Viewer
        chartViewer1 = new ChartViewer();
        chartViewer1.setBackground(new Color(255, 255, 255));
        chartViewer1.setOpaque(true);
        chartViewer1.setPreferredSize(new Dimension(616, 286));
        chartViewer1.setHorizontalAlignment(SwingConstants.CENTER);
        chartViewer1.addViewPortListener(new ViewPortAdapter() {
            public void viewPortChanged(ViewPortChangedEvent e) {
                chartViewer1_viewPortChanged(e);
            }
        });

        // Put the leftPanel on the left and chartViewer1 on the right
        getContentPane().add(leftPanel, BorderLayout.WEST);
        getContentPane().add(chartViewer1, BorderLayout.CENTER);

        // Set all UI fonts (except labels) to uiFont
        for (int i = 0; i < leftPanel.getComponentCount(); ++i)
        {
            Component c = leftPanel.getComponent(i);
            if (!(c instanceof JLabel))
                c.setFont(uiFont);
        }

        // The data generation timer for our random number generator
        dataRateTimer = new javax.swing.Timer(dataInterval, new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                dataRateTimer_Tick();
            }
        });

        // The chart update timer
        chartUpdateTimer = new javax.swing.Timer(
            Integer.parseInt((String)samplePeriod.getSelectedItem()), new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                chartUpdateTimer_Tick();
            }
        });

        // Layout the JFrame
        pack();
        hasFinishedInitialization = true;

        // Start collecting and plotting data
        dataRateTimer.start();
        runPB.doClick();
    }

    //
    // The data update routine. In this demo, it is invoked every 250ms to get new data.
    //
    private void dataRateTimer_Tick()
    {
        Date now = new Date();
        do
        {
            //
            // In this demo, we use some formulas to generate new values. In real applications,
            // it may be replaced by some data acquisition code.
            //
            double p = nextDataTime.getTime() / 1000.0 * 4;
            double dataA = 20 + Math.cos(p * 2.2) * 10 + 1 / (Math.cos(p) * Math.cos(p) + 0.01);
            double dataB = 150 + 100 * Math.sin(p / 27.7) * Math.sin(p / 10.1);
            double dataC = 150 + 100 * Math.cos(p / 6.7) * Math.cos(p / 11.9);

            // Now we shift the data into the array
            shiftData(dataSeriesA, dataA);
            shiftData(dataSeriesB, dataB);
            shiftData(dataSeriesC, dataC);
            shiftData(timeStamps, nextDataTime);

            // Update nextDataTime
            nextDataTime = new Date(nextDataTime.getTime() + dataInterval);;
        }
        while (nextDataTime.before(now));

        // We provide some visual feedback to the numbers generated, so you can see the
        // data being updated.
        valueA.setText("" + Math.round(dataSeriesA[dataSeriesA.length - 1] * 100) / 100.0);
        valueB.setText("" + Math.round(dataSeriesB[dataSeriesB.length - 1] * 100) / 100.0);
        valueC.setText("" + Math.round(dataSeriesC[dataSeriesC.length - 1] * 100) / 100.0);
    }

    //
    // Utility to shift a double value into an array
    //
    private void shiftData(double[] data, double newValue)
    {
        for (int i = 1; i < data.length; ++i)
            data[i - 1] = data[i];
        data[data.length - 1] = newValue;
    }

    //
    // Utility to shift a Data object into an array
    //
    private void shiftData(Date[] data, Date newValue)
    {
        for (int i = 1; i < data.length; ++i)
            data[i - 1] = data[i];
        data[data.length - 1] = newValue;
    }

    //
    // Run button is pressed - start chart update timer
    //
    private void runPB_Clicked()
    {
        runPB.setBackground(new Color(0x80, 0xff, 0x80));
        freezePB.setBackground(null);
        chartUpdateTimer.start();
    }

    //
    // Freeze button is pressed - stop chart update timer
    //
    private void freezePB_Clicked()
    {
        freezePB.setBackground(new Color(0x80, 0xff, 0x80));
        runPB.setBackground(null);
        chartUpdateTimer.stop();
    }

    //
    // Updates the chartUpdateTimer interval if the user selects another interval.
    //
    private void samplePeriod_ValueChanged(ActionEvent evt)
    {
        int period = Integer.parseInt(samplePeriod.getSelectedItem().toString());
        chartUpdateTimer.setDelay(period);
        chartUpdateTimer.setInitialDelay(period);
    }

    //
    // The chartUpdateTimer Tick event - this updates the chart periodicially by raising
    // viewPortChanged events.
    //
    private void chartUpdateTimer_Tick()
    {
        chartViewer1.updateViewPort(true, false);
    }

    //
    // The viewPortChanged event handler. In this example, it just updates the chart. If you
    // have other controls to update, you may also put the update code here.
    //
    private void chartViewer1_viewPortChanged(ViewPortChangedEvent e)
    {
        drawChart(chartViewer1);
    }

    //
    // Draw the chart and display it in the given viewer.
    //
    private void drawChart(ChartViewer viewer)
    {
        // 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.
        XYChart c = new XYChart(600, 270, 0xf4f4f4, 0x000000, 1);
        c.setRoundedFrame();

        // Re-cycle the resources of the existing chart, if any. This can improve performance
        // by reducing the frequency of garbage collections.
        c.recycle(chartViewer1.getChart());

        // 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("Field Intensity at Observation Satellite", "Times New Roman Bold Italic", 15
            ).setBackground(0xdddddd, 0x000000, Chart.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.
        LegendBox b = c.addLegend2(55, 33, 3, "Arial Bold", 9);
        b.setBackground(Chart.Transparent, Chart.Transparent);
        b.setWidth(520);

        // Configure the y-axis with a 10pts Arial Bold axis title
        c.yAxis().setTitle("Intensity (V/m)", "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);

        // Now we add the data to the chart
        Date lastTime = timeStamps[timeStamps.length - 1];
        if (lastTime != null)
        {
            // Set up the x-axis to show the time range in the data buffer
            c.xAxis().setDateScale(
                new Date(lastTime.getTime() - dataInterval * timeStamps.length), lastTime);

            // Set the x-axis label format
            c.xAxis().setLabelFormat("{value|hh:nn:ss}");

            // Create a line layer to plot the lines
            LineLayer 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(dataSeriesA, 0xff0000, "Alpha: <*bgColor=FFCCCC*>" +
                c.formatValue(dataSeriesA[dataSeriesA.length - 1], " {value|2} "));
            layer.addDataSet(dataSeriesB, 0x00cc00, "Beta: <*bgColor=CCFFCC*>" +
                c.formatValue(dataSeriesB[dataSeriesB.length - 1], " {value|2} "));
            layer.addDataSet(dataSeriesC, 0x0000ff, "Gamma: <*bgColor=CCCCFF*>" +
                c.formatValue(dataSeriesC[dataSeriesC.length - 1], " {value|2} "));
        }

        // Set the chart image to the ChartViewer
        chartViewer1.setChart(c);
    }

    //
    // Implementation of the DemoModule interface to allow this demo to run inside the
    // ChartDirectorDemo browser
    //

    // Name of demo program
    public String toString()
    {
        return "Simple Realtime Chart";
    }

    // Number of charts produced in this demo
    public int getNoOfCharts()
    {
        // This demo open its own frame instead of using the right pane of the ChartDirectorDemo
        // browser for display, so we just load the frame, then returns 0.
        setupFrame();
        setVisible(true);
        return 0;
    }

    // Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // Do nothing, as the ChartDirectorDemo browser right pane is not used.
    }
}


Realtime Chart with Track Line (Windows)

Realtime Chart with Track Line (Windows)

NOTE: This section describes Realtime Chart with Track Line for Windows applications only. For web applications, please refer to Realtime Chart with Track Line (Web).

This sample program demonstrates a realtime chart with configurable chart update rate. It includes a track cursor that updates the legend dynamically to display the data values as the mouse cursor moves over the chart. When the mouse is not over the chart, the track cursor will display the latest data values.

In this sample program, new values are generated by a random number generator driven by a timer. The values are initially appended to data arrays which are used for creating the chart. When the number of values exceeds the array size, new values will be "shifted" into the array.

The chart is updated by a second timer. This allows the chart update rate to be configurable independently from the data rate. Also, the chart can be "frozen" for easy reading, while the data can continue to update on the background.

To demonstrate the code structure for update rate control (even though for the update rate in this demo it is not necessary to have any rate control), instead of directly updating the chart, the chart update timer calls ChartViewer.updateViewPort to trigger the ViewPortListener.viewPortChanged event , and the chart is updated in its handler.

The track cursor drawing code is essentially the same as that in Track Line with Legend (Windows). Please refer to that example for the explanation of the code.

Source Code Listing

[Java Version] javademo/realtimetrack.java
import ChartDirector.*;
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class realtimetrack extends JFrame implements DemoModule
{
    //
    // Data to draw the chart. In this demo, the data buffer will be filled by a data generator,
    // triggered to run by a timer every 250ms. We plot the last 240 samples.
    //
    private final int dataInterval = 250;
    private final int sampleSize = 240;
    private Date[] timeStamps = new Date[sampleSize];
    private double[] dataSeriesA = new double[sampleSize];
    private double[] dataSeriesB = new double[sampleSize];
    private double[] dataSeriesC = new double[sampleSize];

    // The index of the array position to which new data values are added.
    private int currentIndex = 0;

    // This is an internal variable used by the real time random number generator so it knows what
    // timestamp should be used for the next data point.
    private Date nextDataTime;

    // Will set to true at the end of initialization
    private boolean hasFinishedInitialization;

    //
    // Controls in the JFrame
    //
    private JButton runPB;
    private JButton freezePB;
    private JComboBox samplePeriod;
    private ChartViewer chartViewer1;
    private javax.swing.Timer dataRateTimer;
    private javax.swing.Timer chartUpdateTimer;
    private JTextField valueA;
    private JTextField valueB;
    private JTextField valueC;

    //
    // The main method to allow this demo to run as a standalone program.
    //
    public static void main(String args[])
    {
        realtimetrack demo = new realtimetrack();
        demo.setDefaultCloseOperation(EXIT_ON_CLOSE);
        demo.setupFrame();
        demo.setVisible(true);
    }

    //
    // Set up the JFrame
    //
    private void setupFrame()
    {
        if (hasFinishedInitialization)
        {
            // Just restart the chart update if already initialized
            runPB.doClick();
            return;
        }

        // Set JFrame title to name of this demo program
        setTitle(toString());
        setResizable(false);

        if (getDefaultCloseOperation() != EXIT_ON_CLOSE)
        {
            // Stop chart updating when window is being closed
            addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) { freezePB.doClick(); }});
        }

        // Initialize the internal variable used by our random real time data generator.
        nextDataTime = new Date((new Date().getTime()) / 1000 * 1000);

       // Font to use for user interface elements
        Font uiFont = new Font("Dialog", Font.PLAIN, 11);

        // Top label bar
        JLabel topLabel = new JLabel("Advanced Software Engineering");
        topLabel.setForeground(new Color(255, 255, 51));
        topLabel.setBackground(new Color(0, 0, 128));
        topLabel.setBorder(new javax.swing.border.EmptyBorder(2, 0, 2, 5));
        topLabel.setHorizontalAlignment(SwingConstants.RIGHT);
        topLabel.setOpaque(true);
        getContentPane().add(topLabel, BorderLayout.NORTH);

        // Left panel
        JPanel leftPanel = new JPanel(null);
        leftPanel.setBorder(BorderFactory.createRaisedBevelBorder());

        // Run push button
        runPB = new JButton("Run", new ImageIcon(getClass().getResource("play.gif")));
        runPB.setHorizontalAlignment(SwingConstants.LEFT);
        runPB.setMargin(new Insets(5, 5, 5, 5));
        runPB.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt)    {
                runPB_Clicked();
            }});
        leftPanel.add(runPB).setBounds(1, 0, 138, 24);

        // Freeze push button
        freezePB = new JButton("Freeze", new ImageIcon(getClass().getResource("pause.gif")));
        freezePB.setHorizontalAlignment(SwingConstants.LEFT);
        freezePB.setMargin(new Insets(5, 5, 5, 5));
        freezePB.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt)    {
                freezePB_Clicked();
            }});
        leftPanel.add(freezePB).setBounds(1, 24, 138, 24);

        // Update Period label
        leftPanel.add(new JLabel("Update Period (ms)")).setBounds(5, 60, 130, 20);

        // Update Period drop down list box
        samplePeriod = new JComboBox(new Object[] { "250", "500", "750", "1000", "1250", "1500",
            "1750", "2000" });
        samplePeriod.setSelectedItem("1000");
        samplePeriod.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                samplePeriod_ValueChanged(evt);
            }});
        leftPanel.add(samplePeriod).setBounds(5, 80, 130, 20);

        // Simulated Machine label
        leftPanel.add(new JLabel("Simulated Machine")).setBounds(5, 180, 130, 20);

        // Alpha Label
        JLabel alphaLabel = new JLabel("Alpha");
        alphaLabel.setFont(uiFont);
        leftPanel.add(alphaLabel).setBounds(5, 200, 60, 20);

        // Alpha value
        valueA = new JTextField();
        valueA.setEditable(false);
        leftPanel.add(valueA).setBounds(65, 200, 70, 20);

        // Beta label
        JLabel betaLabel = new JLabel("Beta");
        betaLabel.setFont(uiFont);
        leftPanel.add(betaLabel).setBounds(5, 220, 60, 20);

        // Beta value
        valueB = new JTextField();
        valueB.setEditable(false);
        leftPanel.add(valueB).setBounds(65, 220, 70, 20);

        // Gamma label
        JLabel gammaLabel = new JLabel("Gamma");
        gammaLabel.setFont(uiFont);
        leftPanel.add(gammaLabel).setBounds(5, 240, 60, 20);

        // Gamma value
        valueC = new JTextField();
        valueC.setEditable(false);
        leftPanel.add(valueC).setBounds(65, 240, 70, 20);

        // Total expected panel size
        leftPanel.setPreferredSize(new Dimension(140, 270));

        // Chart Viewer
        chartViewer1 = new ChartViewer();
        chartViewer1.setBackground(new Color(255, 255, 255));
        chartViewer1.setOpaque(true);
        chartViewer1.setPreferredSize(new Dimension(616, 286));
        chartViewer1.setHorizontalAlignment(SwingConstants.CENTER);
        chartViewer1.addViewPortListener(new ViewPortAdapter() {
            public void viewPortChanged(ViewPortChangedEvent e) {
                chartViewer1_viewPortChanged(e);
            }
        });

        // Add a movedMovedPlotArea event listener to draw the track cursor
        chartViewer1.addTrackCursorListener(new TrackCursorAdapter() {
            public void mouseMovedPlotArea(MouseEvent e) {
                chartViewer1_MouseMovedPlotArea(e);
            }
        });

        // Put the leftPanel on the left and chartViewer1 on the right
        getContentPane().add(leftPanel, BorderLayout.WEST);
        getContentPane().add(chartViewer1, BorderLayout.CENTER);

        // Set all UI fonts (except labels) to uiFont
        for (int i = 0; i < leftPanel.getComponentCount(); ++i)
        {
            Component c = leftPanel.getComponent(i);
            if (!(c instanceof JLabel))
                c.setFont(uiFont);
        }

        // The data generation timer for our random number generator
        dataRateTimer = new javax.swing.Timer(dataInterval, new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                dataRateTimer_Tick();
            }
        });

        // The chart update timer
        chartUpdateTimer = new javax.swing.Timer(
            Integer.parseInt((String)samplePeriod.getSelectedItem()), new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                chartUpdateTimer_Tick();
            }
        });

        // Layout the JFrame
        pack();
        hasFinishedInitialization = true;

        // Start collecting and plotting data
        dataRateTimer.start();
        runPB.doClick();
    }

    //
    // The data update routine. In this demo, it is invoked every 250ms to get new data.
    //
    private void dataRateTimer_Tick()
    {
        Date now = new Date();
        do
        {
            //
            // In this demo, we use some formulas to generate new values. In real applications,
            // it may be replaced by some data acquisition code.
            //
            double p = nextDataTime.getTime() / 1000.0 * 4;
            double dataA = 20 + Math.cos(p * 2.2) * 10 + 1 / (Math.cos(p) * Math.cos(p) + 0.01);
            double dataB = 150 + 100 * Math.sin(p / 27.7) * Math.sin(p / 10.1);
            double dataC = 150 + 100 * Math.cos(p / 6.7) * Math.cos(p / 11.9);

            // After obtaining the new values, we need to update the data arrays.
            if (currentIndex < timeStamps.length)
            {
                // Store the new values in the current index position, and increment the index.
                dataSeriesA[currentIndex] = dataA;
                dataSeriesB[currentIndex] = dataB;
                dataSeriesC[currentIndex] = dataC;
                timeStamps[currentIndex] = nextDataTime;
                ++currentIndex;
            }
            else
            {
                // The data arrays are full. Shift the arrays and store the values at the end.
                shiftData(dataSeriesA, dataA);
                shiftData(dataSeriesB, dataB);
                shiftData(dataSeriesC, dataC);
                shiftData(timeStamps, nextDataTime);
            }

            // Update nextDataTime
            nextDataTime = new Date(nextDataTime.getTime() + dataInterval);;
        }
        while (nextDataTime.before(now));

        // We provide some visual feedback to the numbers generated, so you can see the
        // data being updated.
        valueA.setText("" + Math.round(dataSeriesA[currentIndex - 1] * 100) / 100.0);
        valueB.setText("" + Math.round(dataSeriesB[currentIndex - 1] * 100) / 100.0);
        valueC.setText("" + Math.round(dataSeriesC[currentIndex - 1] * 100) / 100.0);
    }

    //
    // Utility to shift a double value into an array
    //
    private void shiftData(double[] data, double newValue)
    {
        for (int i = 1; i < data.length; ++i)
            data[i - 1] = data[i];
        data[data.length - 1] = newValue;
    }

    //
    // Utility to shift a Data object into an array
    //
    private void shiftData(Date[] data, Date newValue)
    {
        for (int i = 1; i < data.length; ++i)
            data[i - 1] = data[i];
        data[data.length - 1] = newValue;
    }

    //
    // Run button is pressed - start chart update timer
    //
    private void runPB_Clicked()
    {
        runPB.setBackground(new Color(0x80, 0xff, 0x80));
        freezePB.setBackground(null);
        chartUpdateTimer.start();
    }

    //
    // Freeze button is pressed - stop chart update timer
    //
    private void freezePB_Clicked()
    {
        freezePB.setBackground(new Color(0x80, 0xff, 0x80));
        runPB.setBackground(null);
        chartUpdateTimer.stop();
    }

    //
    // Updates the chartUpdateTimer interval if the user selects another interval.
    //
    private void samplePeriod_ValueChanged(ActionEvent evt)
    {
        int period = Integer.parseInt(samplePeriod.getSelectedItem().toString());
        chartUpdateTimer.setDelay(period);
        chartUpdateTimer.setInitialDelay(period);
    }

    //
    // The chartUpdateTimer Tick event - this updates the chart periodicially by raising
    // viewPortChanged events.
    //
    private void chartUpdateTimer_Tick()
    {
        chartViewer1.updateViewPort(true, false);
    }

    //
    // The viewPortChanged event handler. In this example, it just updates the chart. If you
    // have other controls to update, you may also put the update code here.
    //
    private void chartViewer1_viewPortChanged(ViewPortChangedEvent e)
    {
        drawChart(chartViewer1);
    }

    //
    // Draw the chart and display it in the given viewer.
    //
    private void drawChart(ChartViewer viewer)
    {
        // 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.
        XYChart c = new XYChart(600, 270, 0xf4f4f4, 0x000000, 1);
        c.setRoundedFrame();

        // Re-cycle the resources of the existing chart, if any. This can improve performance
        // by reducing the frequency of garbage collections.
        c.recycle(chartViewer1.getChart());

        // Set the plotarea at (55, 55) and of size 520 x 185 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, 55, 520, 185, 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("Field Intensity at Observation Satellite", "Times New Roman Bold Italic", 15
            ).setBackground(0xdddddd, 0x000000, Chart.glassEffect());

        // Set the reference font size of the legend box
        c.getLegend().setFontSize(8);

        // Configure the y-axis with a 10pts Arial Bold axis title
        c.yAxis().setTitle("Intensity (V/m)", "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);

        // Now we add the data to the chart
        Date firstTime = timeStamps[0];
        if (firstTime != null)
        {
            // Set up the x-axis scale. In this demo, we set the x-axis to show the 240 samples,
            // with 250ms per sample.
            c.xAxis().setDateScale(firstTime,
                new Date(firstTime.getTime() + dataInterval * timeStamps.length));

            // Set the x-axis label format
            c.xAxis().setLabelFormat("{value|hh:nn:ss}");

            // Create a line layer to plot the lines
            LineLayer 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(dataSeriesA, 0xff0000, "Alpha");
            layer.addDataSet(dataSeriesB, 0x00cc00, "Beta");
            layer.addDataSet(dataSeriesC, 0x0000ff, "Gamma");
        }

        // Include track line with legend. If the mouse is on the plot area, show the track line
        // with legend at the mouse position; otherwise, show them for the latest data values (that
        // is, at the rightmost position).
        trackLineLegend(c, viewer.isMouseOnPlotArea() ? viewer.getPlotAreaMouseX() :
            c.getPlotArea().getRightX());

        // Set the chart image to the ChartViewer
        chartViewer1.setChart(c);
    }

    //
    // Draw track cursor when mouse is moving over plotarea
    //
    private void chartViewer1_MouseMovedPlotArea(MouseEvent e)
    {
        ChartViewer viewer = (ChartViewer)e.getSource();
        trackLineLegend((XYChart)viewer.getChart(), viewer.getPlotAreaMouseX());
        viewer.updateDisplay();
    }

    //
    // Draw the track line with legend
    //
    private void trackLineLegend(XYChart c, int mouseX)
    {
        // Clear the current dynamic layer and get the DrawArea object to draw on it.
        DrawArea d = c.initDynamicLayer();

        // The plot area object
        PlotArea plotArea = c.getPlotArea();

        // Get the data x-value that is nearest to the mouse, and find its pixel coordinate.
        double xValue = c.getNearestXValue(mouseX);
        int xCoor = c.getXCoor(xValue);

        // Draw a vertical track line at the x-position
        d.vline(plotArea.getTopY(), plotArea.getBottomY(), xCoor, d.dashLineColor(0x000000, 0x0101));

        // Container to hold the legend entries
        ArrayList legendEntries = new ArrayList();

        // Iterate through all layers to build the legend array
        for (int i = 0; i < c.getLayerCount(); ++i) {
            Layer layer = c.getLayerByZ(i);

            // The data array index of the x-value
            int xIndex = layer.getXIndexOf(xValue);

            // Iterate through all the data sets in the layer
            for (int j = 0; j < layer.getDataSetCount(); ++j) {
                ChartDirector.DataSet dataSet = layer.getDataSetByZ(j);

                // We are only interested in visible data sets with names
                String dataName = dataSet.getDataName();
                int color = dataSet.getDataColor();
                if ((!(dataName == null || dataName.length() == 0)) && (color != Chart.Transparent)) {
                    // Build the legend entry, consist of the legend icon, name and data value.
                    double dataValue = dataSet.getValue(xIndex);
                    legendEntries.add("<*block*>" + dataSet.getLegendIcon() + " " + dataName + ": " + ((
                        dataValue == Chart.NoValue) ? "N/A" : c.formatValue(dataValue, "{value|P4}")) +
                        "<*/*>");

                    // Draw a track dot for data points within the plot area
                    int yCoor = c.getYCoor(dataSet.getPosition(xIndex), dataSet.getUseYAxis());
                    if ((yCoor >= plotArea.getTopY()) && (yCoor <= plotArea.getBottomY())) {
                        d.circle(xCoor, yCoor, 4, 4, color, color);
                    }
                }
            }
        }

        // Create the legend by joining the legend entries
        Collections.reverse(legendEntries);
        String legendText = "<*block,maxWidth=" + plotArea.getWidth() + "*><*block*><*font=Arial Bold*>[" +
            c.xAxis().getFormattedLabel(xValue, "hh:nn:ss.ff") + "]<*/*>        " + Chart.stringJoin(
            legendEntries, "        ") + "<*/*>";

        // Display the legend on the top of the plot area
        TTFText t = d.text(legendText, "Arial", 8);
        t.draw(plotArea.getLeftX() + 5, plotArea.getTopY() - 3, 0x000000, Chart.BottomLeft);
    }

    //
    // Implementation of the DemoModule interface to allow this demo to run inside the
    // ChartDirectorDemo browser
    //

    // Name of demo program
    public String toString()
    {
        return "Realtime Chart with Track Line";
    }

    // Number of charts produced in this demo
    public int getNoOfCharts()
    {
        // This demo open its own frame instead of using the right pane of the ChartDirectorDemo
        // browser for display, so we just load the frame, then returns 0.
        setupFrame();
        setVisible(true);
        return 0;
    }

    // Main code for creating charts
    public void createChart(ChartViewer viewer, int index)
    {
        // Do nothing, as the ChartDirectorDemo browser right pane is not used.
    }
}


Realtime Charts (Web)

Realtime Charts (Web)

NOTE: This section describes Realtime Charts for web applications only. For Windows applications, please refer to Realtime Charts (Windows).

For web applications, a realtime chart may be achieved by using browser side Javascript using one of the following methods:

  • Periodically reloads the <IMG> tag that displays the chart, using JsChartViewer.streamUpdate. This method sends a "stream update request" to the server to update the chart image without refreshing the web page. The charting code in the server always draws the chart using the most up-to-date data. By using a timer to call JsChartViewer.streamUpdate periodically, we can get a real time chart.

    The example Simple Realtime Chart (Web) demonstrates using the JsChartViewer.streamUpdate method.

  • Periodically sends AJAX chart update requests to the server using JsChartViewer.partialUpdate. The charting code in the server always draws the chart using the most up-to-date data. By using a timer to call JsChartViewer.partialUpdate periodically, we can get a real time chart.

    On the server side, when the script starts to run , the first thing it does is to use WebChartViewer.isPartialUpdateRequest to detect if it is handling an AJAX chart update or an initial page request. If it is an AJAX chart update, it just draws the chart and sends back an AJAX response using WebChartViewer.partialUpdateChart, then terminates the request. If it is an initial page request, it processes the request as usual.

    The example Realtime Chart with Track Line (Web) demonstrates using the JsChartViewer.partialUpdate method.


Simple Realtime Chart (Web)

Simple Realtime Chart (Web)

NOTE: This section describes Simple Realtime Chart for web applications only. For Windows applications, please refer to Simple Realtime Chart (Windows).

This sample program demonstrates a realtime chart with configurable chart update rate, in which the chart image is being updated via streaming.

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. The chart is updated by calling JsChartViewer.streamUpdate on the browser side. This method sends a "stream update request" to the server to update the chart image without refreshing the web page. The charting code in the server always draws the chart using the most up-to-date data. By using a timer to call JsChartViewer.streamUpdate periodically, we can get a real time chart.

Note that the streaming method used in this example can only update the chart image, but not the image map or the Javascript Chart Model, so the chart would not have image map or track cursor features. An alternative is to use AJAX chart update, which has higher overhead but can support image maps and track cursors. Please refer to Realtime Chart with Track Line (Web) for an example.

NOTE: This sample script uses "cdjcv.js". When developing your own script using this sample script as a template, please ensure you copy "cdjcv.js" to the proper directory and reference it using the proper path.

Source Code Listing

[JSP Version] jspdemo/realtimedemo.jsp
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <title>Simple Realtime Chart</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="font:italic bold 10pt Arial; padding:1px 3px 2px 0px;">
                <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-right:black 1px solid; border-bottom:black 1px solid;">
            <br />
            <br />
            <div style="font: 9pt Verdana; padding:10px;">
                <b>Update Period</b><br />
                <select id="UpdatePeriod" style="width:130px">
                    <option value="5">5</option>
                    <option value="10" selected="selected">10</option>
                    <option value="20">20</option>
                    <option value="30">30</option>
                    <option value="60">60</option>
                </select>
            </div>
            <div style="font:9pt Verdana; padding:10px;">
                <b>Time Remaining</b><br />
                <div style="width:128px; border:#888888 1px inset;">
                    <div style="margin:3px" id="TimeRemaining">0</div>
                </div>
            </div>
        </td>
        <td>
            <div style="font: bold 20pt Arial; margin:5px 0px 0px 5px;">
                Simple Realtime Chart
            </div>
            <hr style="border:solid 1px #000080" />
            <div style="padding:0px 5px 5px 10px">
                <!-- ****** Here is the image tag for the chart image ****** -->
                <img id="ChartImage1" src="realtimechart.jsp?chartId=demoChart1">
            </div>
        </td>
    </tr>
</table>
<script type="text/javascript">

//
// Executes once every second to update the countdown display. Updates the chart when the countdown reaches 0.
//
function timerTick()
{
    // Get the update period and the time left
    var updatePeriod = parseInt(document.getElementById("UpdatePeriod").value);
    var timeLeft = Math.min(parseInt(document.getElementById("TimeRemaining").innerHTML), updatePeriod) - 1;

    if (timeLeft == 0)
        // Can update the chart now
        JsChartViewer.get('ChartImage1').streamUpdate();
    else if (timeLeft < 0)
        // Reset the update period
        timeLeft += updatePeriod;

    // Update the countdown display
    document.getElementById("TimeRemaining").innerHTML = timeLeft;
}
window.setInterval("timerTick()", 1000);

</script>
</body>
</html>

[JSP Version] jspdemo/realtimechart.jsp
<%@page import="ChartDirector.*" %>
<%@page import="java.util.*" %>
<%
//
// 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.
int sampleSize = 240;
double[] dataSeries1 = new double[sampleSize];
double[] dataSeries2 = new double[sampleSize];
double[] dataSeries3 = new double[sampleSize];
Date[] timeStamps = new Date[sampleSize];

// Our pseudo random number generator
double firstDate = new Date().getTime() / 1000 - timeStamps.length;
for (int i = 0; i < timeStamps.length; ++i) {
    double p = firstDate + i;
    timeStamps[i] = new Date((long)p * 1000);
    dataSeries1[i] = Math.cos(p * 2.1) * 10 + 1 / (Math.cos(p) * Math.cos(p) + 0.01)
         + 20;
    dataSeries2[i] = 100 * Math.sin(p / 27.7) * Math.sin(p / 10.1) + 150;
    dataSeries3[i] = 100 * Math.cos(p / 6.7) * Math.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.
XYChart c = new 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("Field Intensity at Observation Satellite", "Times New Roman Bold Italic",
    15).setBackground(0xdddddd, 0x000000, Chart.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.
LegendBox b = c.addLegend2(55, 33, 3, "Arial Bold", 9);
b.setBackground(Chart.Transparent, Chart.Transparent);
b.setWidth(520);

// Configure the y-axis with a 10pts Arial Bold axis title
c.yAxis().setTitle("Intensity (V/m)", "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
LineLayer 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[dataSeries1.length
     - 1], "Alpha: <*bgColor=FFCCCC*> {value|2} "));
layer.addDataSet(dataSeries2, 0x00cc00, c.formatValue(dataSeries2[dataSeries2.length
     - 1], "Beta: <*bgColor=CCFFCC*> {value|2} "));
layer.addDataSet(dataSeries3, 0x0000ff, c.formatValue(dataSeries3[dataSeries3.length
     - 1], "Gamma: <*bgColor=CCCCFF*> {value|2} "));

try
{
    // stream the chart to the browser and terminate immediately
    out.clear();
    if (WebChartViewer.streamChart(response, c.makeChart2(Chart.PNG)))
        return;
}
catch (IllegalStateException e)
{
    // Some very old servers may not support streaming. So we are forced to redirect
    // to the browser to use the traditional method.
    response.sendRedirect(response.encodeRedirectURL("getchart.jsp?" +
        c.makeSession(request, "chart1")));
    return;
}
%>


Realtime Chart with Track Line (Web)

Realtime Chart with Track Line (Web)

NOTE: This section describes Realtime Chart with Track Line for web applications only. For Windows applications, please refer to Realtime Chart with Track Line (Windows).

This sample program demonstrates a realtime chart with configurable chart update rate, in which the chart image is being updated via AJAX means. It includes a track cursor that updates the legend dynamically to display the data values as the mouse cursor moves over the chart. When the mouse is not over the chart, the track cursor will display the latest data values.

When the script starts to run , the first thing it does is to use WebChartViewer.isPartialUpdateRequest to detect if it is handling an AJAX chart update or an initial page request. If it is an AJAX chart update, it just draws the chart and sends back an AJAX response using WebChartViewer.partialUpdateChart, then terminates the request. If it is an initial page request, it processes the request as usual.

The chart is updated by calling JsChartViewer.partialUpdate on the browser side. This method sends an AJAX chart update request to the server to update the chart without refreshing the web page. The charting code in the server always draws the chart using the most up-to-date data. By using a timer to call JsChartViewer.partialUpdate periodically, we can get a real time chart.

The track cursor drawing code is essentially the same as that in Track Line with Legend (Web). Please refer to that example for the explanation of the code.

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
realtimetrack.jsp | Main source code for this demo.
getchart.jsp | The standard utility script used in the image url for retrieving the chart image from
cdjcv.js wait.gif spacer.gif | The script file for JsChartViewer, and the supporting cursor and image files. They must be in the same directory.

Source Code Listing

[JSP Version] jspdemo/realtimetrack.jsp
<%@page import="ChartDirector.*, java.util.*"%>
<%!
//
// Draw the chart
//
private void drawChart(WebChartViewer viewer)
{
    //
    // 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.
    int sampleSize = 240;
    double[] dataSeries1 = new double[sampleSize];
    double[] dataSeries2 = new double[sampleSize];
    double[] dataSeries3 = new double[sampleSize];
    Date[] timeStamps = new Date[sampleSize];

    // Our pseudo random number generator
    double firstDate = new Date().getTime() / 1000 - timeStamps.length;
    for (int i = 0; i < timeStamps.length; ++i) {
        double p = firstDate + i;
        timeStamps[i] = new Date((long)p * 1000);
        dataSeries1[i] = Math.cos(p * 2.1) * 10 + 1 / (Math.cos(p) * Math.cos(p) + 0.01) + 20;
        dataSeries2[i] = 100 * Math.sin(p / 27.7) * Math.sin(p / 10.1) + 150;
        dataSeries3[i] = 100 * Math.cos(p / 6.7) * Math.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.
    XYChart c = new XYChart(600, 270, 0xf4f4f4, 0x000000, 0);
    c.setRoundedFrame();

    // Set the plotarea at (55, 57) and of size 520 x 185 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, 57, 520, 185, 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("Field Intensity at Observation Satellite", "Times New Roman Bold Italic", 15
        ).setBackground(0xdddddd, 0x000000, Chart.glassEffect());

    // Configure the y-axis with a 10pts Arial Bold axis title
    c.yAxis().setTitle("Intensity (V/m)", "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
    LineLayer 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, "Alpha");
    layer.addDataSet(dataSeries2, 0x00cc00, "Beta");
    layer.addDataSet(dataSeries3, 0x0000ff, "Gamma");

    // Output the chart
    String chartQuery = c.makeSession(viewer.getRequest(), viewer.getId());

    // Set the chart URL to the viewer
    viewer.setImageUrl("getchart.jsp?" + chartQuery);

    // Output Javascript chart model to the browser to support tracking cursor
    viewer.setChartModel(c.getJsChartModel());
}
%>
<%

//
// This script handles both the full page request, as well as the subsequent partial updates (AJAX
// chart updates). We need to determine the type of request first before we processing it.
//

// Create the WebChartViewer object
WebChartViewer viewer = new WebChartViewer(request, "chart1");

if (viewer.isPartialUpdateRequest()) {
    // Is a partial update request. Draw the chart and perform a partial response.
    drawChart(viewer);
    out.clear();
    viewer.partialUpdateChart(response);
    return;
}

//
// If the code reaches here, it is a full page request.
//

drawChart(viewer);
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <title>Realtime Chart with Track Line</title>
    <script type="text/javascript" src="cdjcv.js"></script>
</head>
<body style="margin:0px">
<script type="text/javascript">

//
// Execute the following initialization code after the web page is loaded
//
JsChartViewer.addEventListener(window, 'load', function() {
    var viewer = JsChartViewer.get('<%=viewer.getId()%>');

    // Draw track cursor when mouse is moving over plotarea or if the chart is updated. In the latter case,
    // if the mouse is not on the plot area, we will update the legend to show the latest data values.
    viewer.attachHandler(["MouseMovePlotArea", "PostUpdate"], function(e) {
        if (viewer.isMouseOnPlotArea())
            trackLineLegend(viewer, viewer.getPlotAreaMouseX())
        else
            trackLineLegend(viewer, viewer.getChart().getPlotArea().getRightX());
    });

    // Initialize the track line legend to show the latest data values
    trackLineLegend(viewer, viewer.getChart().getPlotArea().getRightX());

    // When the chart is being updated, by default, an "Updating" box will pop up. In this example, we
    // will disable this box.
    viewer.updatingMsg = "";
});

//
// Draw track line with legend
//
function trackLineLegend(viewer, mouseX)
{
    // Remove all previously drawn tracking object
    viewer.hideObj("all");

    // The chart and its plot area
    var c = viewer.getChart();
    var plotArea = c.getPlotArea();

    // Get the data x-value that is nearest to the mouse, and find its pixel coordinate.
    var xValue = c.getNearestXValue(mouseX);
    var xCoor = c.getXCoor(xValue);
    if (xCoor == null)
        return;

    // Draw a vertical track line at the x-position
    viewer.drawVLine("trackLine", xCoor, plotArea.getTopY(), plotArea.getBottomY(), "black 1px dotted");

    // Array to hold the legend entries
    var legendEntries = [];

    // Iterate through all layers to build the legend array
    for (var i = 0; i < c.getLayerCount(); ++i)
    {
        var layer = c.getLayerByZ(i);

        // The data array index of the x-value
        var xIndex = layer.getXIndexOf(xValue);

        // Iterate through all the data sets in the layer
        for (var j = 0; j < layer.getDataSetCount(); ++j)
        {
            var dataSet = layer.getDataSetByZ(j);

            // We are only interested in visible data sets with names, as they are required for legend entries.
            var dataName = dataSet.getDataName();
            var color = dataSet.getDataColor();
            if ((!dataName) || (color == null))
                continue;

            // Build the legend entry, consist of a colored square box, the name and the data value.
            var dataValue = dataSet.getValue(xIndex);
            legendEntries.push("<nobr>" + viewer.htmlRect(7, 7, color) + " " + dataName + ": " +
                ((dataValue == null) ? "N/A" : dataValue.toPrecision(4)) + viewer.htmlRect(20, 0) + "</nobr> ");

            // Draw a track dot for data points within the plot area
            var yCoor = c.getYCoor(dataSet.getPosition(xIndex), dataSet.getUseYAxis());
            if ((yCoor != null) && (yCoor >= plotArea.getTopY()) && (yCoor <= plotArea.getBottomY()))
            {
                viewer.showTextBox("dataPoint" + i + "_" + j, xCoor, yCoor, JsChartViewer.Center,
                    viewer.htmlRect(7, 7, color));
            }
        }
    }

    // Create the legend by joining the legend entries.
    var legend = "<nobr>[" + c.xAxis().getFormattedLabel(xValue, "hh:nn:ss") + "]" + viewer.htmlRect(20, 0) +
        "</nobr> " + legendEntries.reverse().join("");

    // Display the legend on the top of the plot area
    viewer.showTextBox("legend", plotArea.getLeftX(), plotArea.getTopY(), JsChartViewer.BottomLeft, legend,
        "width:" + (plotArea.getWidth() - 1) + "px;font:bold 11px Arial;padding:3px;");
}

//
// Executes once every second to update the countdown display. Updates the chart when the countdown reaches 0.
//
function timerTick()
{
    // Get the update period and the time left
    var updatePeriod = parseInt(document.getElementById("UpdatePeriod").value);
    var timeLeft = Math.min(parseInt(document.getElementById("TimeRemaining").innerHTML), updatePeriod) - 1;

    if (timeLeft == 0)
        // Can update the chart now
        JsChartViewer.get('<%=viewer.getId()%>').partialUpdate();
    else if (timeLeft < 0)
        // Reset the update period
        timeLeft += updatePeriod;

    // Update the countdown display
    document.getElementById("TimeRemaining").innerHTML = timeLeft;
}
window.setInterval("timerTick()", 1000);

</script>
<table cellspacing="0" cellpadding="0" border="0">
    <tr>
        <td align="right" colspan="2" style="background:#000088">
            <div style="font:italic bold 10pt Arial; padding:1px 3px 2px 0px;">
                <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-right:black 1px solid; border-bottom:black 1px solid;">
            <br />
            <br />
            <div style="font: 9pt Verdana; padding:10px;">
                <b>Update Period</b><br />
                <select id="UpdatePeriod" style="width:130px">
                    <option value="5">5</option>
                    <option value="10" selected="selected">10</option>
                    <option value="20">20</option>
                    <option value="30">30</option>
                    <option value="60">60</option>
                </select>
            </div>
            <div style="font:9pt Verdana; padding:10px;">
                <b>Time Remaining</b><br />
                <div style="width:128px; border:#888888 1px inset;">
                    <div style="margin:3px" id="TimeRemaining">0</div>
                </div>
            </div>
        </td>
        <td>
            <div style="font: bold 20pt Arial; margin:5px 0px 0px 5px;">
                Realtime Chart with Track Line
            </div>
            <hr style="border:solid 1px #000080" />
            <div style="padding:0px 5px 5px 10px">
                <!-- ****** Here is the chart image ****** -->
                <%=viewer.renderHTML(response)%>
            </div>
        </td>
    </tr>
</table>
</body>
</html>


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.

Chart

Chart is a class used to contain the all static functions and predefined constants used in ChartDirector, including general informational functions and data conversion functions.

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. TextBox 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.
ThreeDChart | The ThreeDChart class is an abstract class containing methods that are common to all true 3D chart types. ThreeDChart is a subclass of BaseChart.
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. LegendBox is a subclass of TextBox.

Pie Charts Related

Class | Description
PieChart | The PieChart class represents pie charts. PieChart is a subclass of BaseChart.
Sector | The Sector class represents sectors.

XY Charts Related

Class | Description
XYChart | The XYChart class represents XY charts. It 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
ColorAxis | The ColorAxis class represents the color axis in contour layers and surface charts. ColorAxis is a subclass of Axis.
Mark | The Mark class represents mark lines. Mark 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. The BaseBoxLayer class 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.
ContourLayer | The ContourLayer class represents contour layers. ContourLayer is a subclass of Layer.
DataSet | The DataSet class represents data sets.

Surface Charts Related

Class | Description
SurfaceChart | The SurfaceChart class represents surface charts. SurfaceChart is a subclass of ThreeDChart.

3D Scatter Charts Related

Class | Description
ThreeDScatterChart | The ThreeDScatterChart class represents 3D scatter charts. ThreeDScatterChart is a subclass of ThreeDChart.
ThreeDScatterGroup | The ThreeDSCatterGroup class represents a group of scatter symbols in a ThreeDScatterChart object.

Polar Charts Related

Class | Description
PolarChart | The PolarChart class represents polar charts (including radar charts). PolarChart is a subclass of BaseChart.
RadialAxis | The RadialAxis class represents radial axes in polar charts. RadialAxis is a subclass of Axis.
AngularAxis | The AngularAxis class represents angular axes in polar charts.
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.

Pyramid Charts Related

Class | Description
PyramidChart | The PyramidChart class represents pyramid charts (including cone charts and funnel charts). PyramidChart is a subclass of BaseChart.
PyramidLayer | The PyramidLayer class represents a layer in a pyramid

Meters and Gauges

Class | Description
BaseMeter | The BaseMeter class is the base class of all meters in ChartDirector. BaseMeter is a subclass of BaseChart.
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.
DBTable | The DBTable class represents data tables read from java.sql.ResultSet objects. It allows the columns of a table to be retrieved as arrays, so the data can be used in ChartDirector easily.
RanSeries | RanSeries is a utility class to produce random series.
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.


Chart

Chart

ChartDirector.Chart is a class used to contain static ChartDirector functions and constants. Because it is only used for static functions and constants, it is never needed to create any ChartDirector.Chart object. Just use Chart.{function_name} or Chart.{constant_name} to access the static functions and constants.

For example, to access the NoValue predefined constant, simply use Chart.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.
BottomCenter | A constant equals to 2 to represent the bottom center position.
BottomRight | A constant equals to 3 to represent the 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.
TopCenter | A constant equals to 8 to represent the top center position.
TopRight | A constant equals to 9 to represent the 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.
TopLeft2 | A constant equals to 10 to represent the alternative exterior top left position.
TopRight2 | A constant equals to 11 to represent the alternative exterior top right position.
BottomLeft2 | A constant equals to 12 to represent the alternative exterior bottom left position.
BottomRight2 | A constant equals to 13 to represent the alternative exterior bottom right 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 Chart.glassEffect shading style.
ReducedGlare | A constant equals to 2 to represent using reduced glare strength in Chart.glassEffect shading style.
NoGlare | A constant equals to 1 to represent disabling the glare in Chart.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.
GlassSphereShape | A constant equals to 15 to represent a glass sphere.
GlassSphere2Shape | A constant equals to 16 to represent a bright glass sphere.
SolidSphereShape | A constant equals to 17 to represent a solid sphere.
DefaultShading | A constant equals to 0 to represent default sector shading style.
FlatShading | A constant equals to 1 to represent flat sector shading style.
LocalGradientShading | A constant equals to 2 to represent local gradient sector shading style.
GlobalGradientShading | A constant equals to 3 to represent global gradient sector shading style.
ConcaveShading | A constant equals to 4 to represent concave sector shading style.
RoundedEdgeShading | A constant equals to 6 to represent rounded edge sector shading style.
RadialShading | A constant equals to 7 to represent radial sector shading style.
RingShading | A constant equals to 8 to represent ring sector shading style.
SmoothShading | A constant equals to 0 to represent smooth surface shading style.
TriangularShading | A constant equals to 1 to represent triangular surface shading style.
RectangularShading | A constant equals to 2 to represent rectangular surface shading style.
TriangularFrame | A constant equals to 3 to represent triangular frame only surface shading style.
RectangularFrame | A constant equals to 4 to represent rectangular frame only surface shading style.
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.
SVG | A constant equals to 5 to represent the SVG image format.
SVGZ | A constant equals to 5 to represent the compressed SVG 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 classical anti-alias.
AutoAntiAlias | A constant equals to 2 to represent that text should be drawn with an automatically determined anti-alias method.
CompatAntiAlias | A constant equals to 6 to represent that text should be drawn with an automatically determined anti-alias method that behaves the same way as in ChartDirector 5.0.x or earlier versions.
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.
MonotonicNone | A constant equals to 0 to represent that a spline curve is not constraint to flow in any direction.
MonotonicX | A constant equals to 1 to represent that a spline curve is constrained to not overshooting or undershooting in the x-axis direction.
MonotonicY | A constant equals to 2 to represent that a spline curve is constrained to not overshooting or undershooting in the y-axis direction.
MonotonicXY | A constant equals to 3 to represent that a spline curve is constrained to not overshooting or undershooting in both the x-axis direction and the y-axis direction.
MonotonicAuto | A constant equals to 3 to represent that the system will automatically determine whether to constrained a spline curve to not overshooting or undershooting in the x-axis direction and/or the y-axis direction.
LinearRegression | A constant equals to 1 to represent that linear regression be used to draw a trend line.
ConstrainedLinearRegression | A constant equals to 0 to represent that constrained linear regression be used to draw a trend line.
ExponentialRegression | A constant equals to -1 to represent that exponential regression be used to draw a trend line.
LogarithmicRegression | A constant equals to -2 to represent that logarithmic regression be used to draw a trend line.
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.
LinearTick | A constant equals to +1.5E+308 to represent that the ticks in a log scale axis should be 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10 style increments.
TickInc | A constant equals to +1E+200 to represent the distance between major ticks.
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.
EndPoints | A constant equals to 3 to represent that the vector lengths and directions are measured by specifying the end points.
DataBound | A constant equals to -1.7E-100 to represent that the interpolated z values should not exceed the minimum or maximum values of the original data.
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.
MouseUsageScrollOnDrag | A constant equals to 1 to represent using the mouse for drag scrolling.
MouseUsageScrollOnDrop | A constant equals to 2 to represent using the mouse for drag scrolling.
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
ClearTypeColor | Gets a value to represent that standard ClearType or a similar technology be used for font rendering.
ClearTypeMono | Gets a value to represent that hardware independent ClearType or a similar technology be used for font rendering.
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 java.util.Date to ChartDirector's date/time format.
CTime2 | Converts an array of java.util.Date objects to ChartDirector's date/time format.
NTime | Converts a date/time in ChartDirector's date/time format to a java.util.Date object.
NTime2 | Converts an array of dates/times in ChartDirector's date/time format to java.util.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.
brushedGoldColor | Creates a brushed golden color, most commonly used as a background color.
brushedSilverColor | Creates a brushed silver color, most commonly used as a background color.
brushedMetalColor | Creates a color by modulates the brightness of another color to create brushed metallic shiny effects.
CColor | Converts a java.awt.Color object to a ChartDirector color.
CColor2 | Converts an array of java.awt.Color objects to an array of ChartDirector colors.
NColor | Converts a ChartDirector color to a java.awt.Color object.
NColor2 | Converts an array of ChartDirector colors to an array of java.awt.Color objects.
glassEffect | A complex shading effect that emulates tinted glass or semi-transparent plastic material.
softLighting | A special shading effect that looks like gradient coloring.
barLighting | A special shading effect for rectangular and polygonal bars on a BarLayer. It shades all surfaces of a 2D or 3D bar with gradient colors.
cylinderEffect | A special shading effect that emulates the lighting of a cylinder surface.
phongLighting | Sets the parameters for the phong lighting effect.
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.
PolynomialRegression | Sets the degree of the polynomial regression to be used in a trend layer.
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.
bSearch | Uses binary search to search for a value in an array.
arraySlice | Creates a new array with the elements copied from a part of a given array.
stringJoin | Concatenates all elements of a string array or collection using the specified delimiter.
getUniqueId | Returns an incrementing number. The method for compatibility with previous version of ChartDirector only.


Chart.NoValue

Chart.NoValue

Declaration

public const double NoValue

Description

A constant equals to 1.7E+308 to represent missing values in ChartDirector.

Please refer to No Value Specification for more details.


Chart.BottomLeft

Chart.BottomLeft

Declaration

public const int BottomLeft

Description

A constant equals to 1 to represent the bottom left position.

See Alignment Specification for supported alignment types.


Chart.BottomCenter

Chart.BottomCenter

Declaration

public const int BottomCenter

Description

A constant equals to 2 to represent the bottom center position.

See Alignment Specification for supported alignment types.


Chart.BottomRight

Chart.BottomRight

Declaration

public const int BottomRight

Description

A constant equals to 3 to represent the bottom right position.

See Alignment Specification for supported alignment types.


Chart.Left

Chart.Left

Declaration

public const int Left

Description

A constant equals to 4 to represent the left position.

See Alignment Specification for supported alignment types.


Chart.Center

Chart.Center

Declaration

public const int Center

Description

A constant equals to 5 to represent the center position.

See Alignment Specification for supported alignment types.


Chart.Right

Chart.Right

Declaration

public const int Right

Description

A constant equals to 6 to represent the right position.

See Alignment Specification for supported alignment types.


Chart.TopLeft

Chart.TopLeft

Declaration

public const int TopLeft

Description

A constant equals to 7 to represent the top left position.

See Alignment Specification for supported alignment types.


Chart.TopCenter

Chart.TopCenter

Declaration

public const int TopCenter

Description

A constant equals to 8 to represent the top center position.

See Alignment Specification for supported alignment types.


Chart.TopRight

Chart.TopRight

Declaration

public const int TopRight

Description

A constant equals to 9 to represent the top right position.

See Alignment Specification for supported alignment types.


Chart.Bottom

Chart.Bottom

Declaration

public const int Bottom

Description

A constant equals to 2 to represent the bottom position.

See Alignment Specification for supported alignment types.


Chart.Top

Chart.Top

Declaration

public const int Top

Description

A constant equals to 8 to represent the top position.

See Alignment Specification for supported alignment types.


Chart.TopLeft2

Chart.TopLeft2

Declaration

public const int TopLeft2

Description

A constant equals to 10 to represent the alternative exterior top left position.

See Alignment Specification for supported alignment types.


Chart.TopRight2

Chart.TopRight2

Declaration

public const int TopRight2

Description

A constant equals to 11 to represent the alternative exterior top right position.

See Alignment Specification for supported alignment types.


Chart.BottomLeft2

Chart.BottomLeft2

Declaration

public const int BottomLeft2

Description

A constant equals to 12 to represent the alternative exterior bottom left position.

See Alignment Specification for supported alignment types.


Chart.BottomRight2

Chart.BottomRight2

Declaration

public const int BottomRight2

Description

A constant equals to 13 to represent the alternative exterior bottom right position.

See Alignment Specification for supported alignment types.


Chart.Transparent

Chart.Transparent

Declaration

public const int Transparent

Description

A constant equals to FF000000 (in hex) to represent the transparent color.

See Color Specification on how colors are represented in ChartDirector.


Chart.BackgroundColor

Chart.BackgroundColor

Declaration

public const int BackgroundColor

Description

A constant equals to FFFF0000 (in hex) to represent the background color.

See Color Specification on how colors are represented in ChartDirector.


Chart.LineColor

Chart.LineColor

Declaration

public const int 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.


Chart.TextColor

Chart.TextColor

Declaration

public const int 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.


Chart.SameAsMainColor

Chart.SameAsMainColor

Declaration

public const int 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.


Chart.Palette

Chart.Palette

Declaration

public const int 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.


Chart.DataColor

Chart.DataColor

Declaration

public const int 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.


Chart.defaultPalette

Chart.defaultPalette

Declaration

public static readonly int[] 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.


Chart.whiteOnBlackPalette

Chart.whiteOnBlackPalette

Declaration

public static readonly int[] 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.


Chart.transparentPalette

Chart.transparentPalette

Declaration

public static readonly int[] 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.


Chart.NormalGlare

Chart.NormalGlare

Declaration

public const int NormalGlare

Description

A constant equals to 3 to represent using normal glare strength in Chart.glassEffect shading style.


Chart.ReducedGlare

Chart.ReducedGlare

Declaration

public const int ReducedGlare

Description

A constant equals to 2 to represent using reduced glare strength in Chart.glassEffect shading style.


Chart.NoGlare

Chart.NoGlare

Declaration

public const int NoGlare

Description

A constant equals to 1 to represent disabling the glare in Chart.glassEffect shading style.


Chart.DashLine

Chart.DashLine

Declaration

public const int 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.


Chart.DotLine

Chart.DotLine

Declaration

public const int 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.


Chart.DotDashLine

Chart.DotDashLine

Declaration

public const int 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.


Chart.AltDashLine

Chart.AltDashLine

Declaration

public const int 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.


Chart.goldGradient

Chart.goldGradient

Declaration

public static readonly int[] 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.


Chart.silverGradient

Chart.silverGradient

Declaration

public static readonly int[] 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.


Chart.redMetalGradient

Chart.redMetalGradient

Declaration

public static readonly int[] 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.


Chart.blueMetalGradient

Chart.blueMetalGradient

Declaration

public static readonly int[] 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.


Chart.greenMetalGradient

Chart.greenMetalGradient

Declaration

public static readonly int[] 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.


Chart.SquareShape

Chart.SquareShape

Declaration

public const int 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.


Chart.DiamondShape

Chart.DiamondShape

Declaration

public const int 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.


Chart.TriangleShape

Chart.TriangleShape

Declaration

public const int 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.


Chart.RightTriangleShape

Chart.RightTriangleShape

Declaration

public const int 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.


Chart.LeftTriangleShape

Chart.LeftTriangleShape

Declaration

public const int 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.


Chart.InvertedTriangleShape

Chart.InvertedTriangleShape

Declaration

public const int 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.


Chart.CircleShape

Chart.CircleShape

Declaration

public const int 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.


Chart.GlassSphereShape

Chart.GlassSphereShape

Declaration

public const int GlassSphereShape

Description

A constant equals to 15 to represent a glass sphere.

Please refer to Shape Specification for samples and more information on using shapes in ChartDirector.


Chart.GlassSphere2Shape

Chart.GlassSphere2Shape

Declaration

public const int GlassSphere2Shape

Description

A constant equals to 16 to represent a bright glass sphere.

Please refer to Shape Specification for samples and more information on using shapes in ChartDirector.


Chart.SolidSphereShape

Chart.SolidSphereShape

Declaration

public const int SolidSphereShape

Description

A constant equals to 17 to represent a solid sphere.

Please refer to Shape Specification for samples and more information on using shapes in ChartDirector.


Chart.DefaultShading

Chart.DefaultShading

Declaration

public const int DefaultShading

Description

A constant equals to 0 to represent default sector shading style.

This constant is used in PieChart.setSectorStyle and Sector.setStyle.


Chart.FlatShading

Chart.FlatShading

Declaration

public const int FlatShading

Description

A constant equals to 1 to represent flat sector shading style.

This constant is used in PieChart.setSectorStyle and Sector.setStyle.


Chart.LocalGradientShading

Chart.LocalGradientShading

Declaration

public const int LocalGradientShading

Description

A constant equals to 2 to represent local gradient sector shading style.

This constant is used in PieChart.setSectorStyle and Sector.setStyle.


Chart.GlobalGradientShading

Chart.GlobalGradientShading

Declaration

public const int GlobalGradientShading

Description

A constant equals to 3 to represent global gradient sector shading style.

This constant is used in PieChart.setSectorStyle and Sector.setStyle.


Chart.ConcaveShading

Chart.ConcaveShading

Declaration

public const int ConcaveShading

Description

A constant equals to 4 to represent concave sector shading style.

This constant is used in PieChart.setSectorStyle and Sector.setStyle.


Chart.RoundedEdgeShading

Chart.RoundedEdgeShading

Declaration

public const int RoundedEdgeShading

Description

A constant equals to 6 to represent rounded edge sector shading style.

This constant is used in PieChart.setSectorStyle and Sector.setStyle.


Chart.RadialShading

Chart.RadialShading

Declaration

public const int RadialShading

Description

A constant equals to 7 to represent radial sector shading style.

This constant is used in PieChart.setSectorStyle and Sector.setStyle.


Chart.RingShading

Chart.RingShading

Declaration

public const int RingShading

Description

A constant equals to 8 to represent ring sector shading style.

This constant is used in PieChart.setSectorStyle and Sector.setStyle.


Chart.SmoothShading

Chart.SmoothShading

Declaration

public const int SmoothShading

Description

A constant equals to 0 to represent smooth surface shading style.

This constant is used in SurfaceChart.setShadingMode.


Chart.TriangularShading

Chart.TriangularShading

Declaration

public const int TriangularShading

Description

A constant equals to 1 to represent triangular surface shading style.

This constant is used in SurfaceChart.setShadingMode.


Chart.RectangularShading

Chart.RectangularShading

Declaration

public const int RectangularShading

Description

A constant equals to 2 to represent rectangular surface shading style.

This constant is used in SurfaceChart.setShadingMode.


Chart.TriangularFrame

Chart.TriangularFrame

Declaration

public const int TriangularFrame

Description

A constant equals to 3 to represent triangular frame only surface shading style.

This constant is used in SurfaceChart.setShadingMode.


Chart.RectangularFrame

Chart.RectangularFrame

Declaration

public const int RectangularFrame

Description

A constant equals to 4 to represent rectangular frame only surface shading style.

This constant is used in SurfaceChart.setShadingMode.


Chart.DiamondPointer

Chart.DiamondPointer

Declaration

public const int DiamondPointer

Description

A constant equals to 0 to represent the diamond style meter pointer.

This constant is used in MeterPointer.setShape.


Chart.TriangularPointer

Chart.TriangularPointer

Declaration

public const int TriangularPointer

Description

A constant equals to 1 to represent the triangular style meter pointer.

This constant is used in MeterPointer.setShape.


Chart.ArrowPointer

Chart.ArrowPointer

Declaration

public const int ArrowPointer

Description

A constant equals to 2 to represent the arrow style meter pointer.

This constant is used in MeterPointer.setShape.


Chart.ArrowPointer2

Chart.ArrowPointer2

Declaration

public const int ArrowPointer2

Description

A constant equals to 3 to represent the alternative arrow style meter pointer.

This constant is used in MeterPointer.setShape.


Chart.LinePointer

Chart.LinePointer

Declaration

public const int LinePointer

Description

A constant equals to 4 to represent the line style meter pointer.

This constant is used in MeterPointer.setShape.


Chart.PencilPointer

Chart.PencilPointer

Declaration

public const int PencilPointer

Description

A constant equals to 5 to represent the pencil style meter pointer.

This constant is used in MeterPointer.setShape.


Chart.PNG

Chart.PNG

Declaration

public const int PNG

Description

A constant equals to 0 to represent the PNG image format.

This constant is used in BaseChart.makeChart2, BaseChart.makeSession and BaseChart.makeTmpFile.


Chart.GIF

Chart.GIF

Declaration

public const int GIF

Description

A constant equals to 1 to represent the GIF image format.

This constant is used in BaseChart.makeChart2, BaseChart.makeSession and BaseChart.makeTmpFile.


Chart.JPG

Chart.JPG

Declaration

public const int JPG

Description

A constant equals to 2 to represent the JPG image format.

This constant is used in BaseChart.makeChart2, BaseChart.makeSession and BaseChart.makeTmpFile.


Chart.BMP

Chart.BMP

Declaration

public const int BMP

Description

A constant equals to 4 to represent the BMP image format.

This constant is used in BaseChart.makeChart2, BaseChart.makeSession and BaseChart.makeTmpFile.


Chart.WMP

Chart.WMP

Declaration

public const int WMP

Description

A constant equals to 3 to represent the WAP bitmap image format.

This constant is used in BaseChart.makeChart2, BaseChart.makeSession and BaseChart.makeTmpFile.


Chart.SVG

Chart.SVG

Declaration

public const int SVG

Description

A constant equals to 5 to represent the SVG image format.

This constant is used in BaseChart.makeChart2, BaseChart.makeSession and BaseChart.makeTmpFile.


Chart.SVGZ

Chart.SVGZ

Declaration

public const int SVGZ

Description

A constant equals to 5 to represent the compressed SVG image format.

This constant is used in BaseChart.makeChart2, BaseChart.makeSession and BaseChart.makeTmpFile.


Chart.NoAntiAlias

Chart.NoAntiAlias

Declaration

public const int 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.


Chart.AntiAlias

Chart.AntiAlias

Declaration

public const int AntiAlias

Description

A constant equals to 1 to represent that text should be drawn with classical anti-alias.

This constant is used in BaseChart.setAntiAlias and DrawArea.setAntiAlias.


Chart.ClearTypeColor

Chart.ClearTypeColor

Usage

public static int ClearTypeColor([ double gamma ])

Description

Gets a value to represent that standard ClearType or a similar technology be used for font rendering.

This constant is used in BaseChart.setAntiAlias and DrawArea.setAntiAlias.

ClearType is a Microsoft font rendering technology that renders text more accurately with subpixel rendering. Similar technologies include Quartz in Mac OS X, Adobe CoolType and other unnamed algorithms. Although this API uses ClearType in its name, ChartDirector may use ClearType or a similar technology depending on the operating system and programming language.

In most modern flat panel displays, a pixel is consisted of 3 sub-pixels R, G and B for the red, green and blue colors, typically arranged horizontally. So a row of pixels is actually a sequence of subpixels like RGBRGBRGBRGB... To display a white pixel, the display hardware turns on the RGB subpixels.

It happens a white dot can also be made by turning on the GB subpixels of one pixel, and the R subpixel of the next pixel to the right. This will result in 3 consecutive subpixels GBR, which is also white. This white dot will be in between the two pixels, with 2/3 on the left pixel, and 1/3 on the right pixel. In other words, it is possible to position a white dot in between two pixels without blurring it. ClearType uses this effect to render text with subpixel accuracy.

Apart from subpixel rendering, ClearType may adjust the glyph shapes to fit the pixel grid (technically called hinting) differently from classical rendering. As a result, the glyph shapes and sizes in ClearType may be different from classical rendering.

One issue with ClearType is that it is hardware dependent. To work perfectly, it needs to know the subpixels ordering of the display. In many applications, the charts are rendered on one computer, but viewed using another computer. For example, in a web application, the charts can be rendered on the server but displayed on the browser computer. The chart generating computer may not know the subpixel configuration of the viewing computer. If ClearType is used, there is a risk that the text may look suboptimal on the viewing computer.

To address the above issues, ChartDirector supports a hardware independent ClearType method, represented by ClearTypeMono. This is basically ClearType with subpixel rendering disabled. The resulting text has no color distortion. Black and white text will not be as sharp as standard ClearType, but is still better than classical anti-alias. The charts rendered can be viewed equally well with different types of displays. This is especially useful for applications in which the charts are rendered and viewed by different computers.

Arguments

Argument | Default | Description
gamma | 0 | Specifies the level of gamma correction used for ClearType font rendering. This is usually a number between 1 to 2.5. A value of 0 means the default gamma level.

Return Value

An integer representing that standard ClearType or a similar technology be used for font rendering.


Chart.ClearTypeMono

Chart.ClearTypeMono

Usage

public static int ClearTypeMono([ double gamma ])

Description

Gets a value to represent that hardware independent ClearType or a similar technology be used for font rendering.

This constant is used in BaseChart.setAntiAlias and DrawArea.setAntiAlias.

Please refer to ClearTypeColor on the detail explanation of what is standard ClearType and hardware independent ClearType.

Arguments

Argument | Default | Description
gamma | 0 | Specifies the level of gamma correction used for ClearType font rendering. This is usually a number between 1 to 2.5. A value of 0 means the default gamma level.

Return Value

An integer representing that hardware independent ClearType or a similar technology be used for font rendering..


Chart.AutoAntiAlias

Chart.AutoAntiAlias

Declaration

public const int AutoAntiAlias

Description

A constant equals to 2 to represent that text should be drawn with an automatically determined anti-alias method.

This constant is used in BaseChart.setAntiAlias and DrawArea.setAntiAlias.


Chart.CompatAntiAlias

Chart.CompatAntiAlias

Declaration

public const int CompatAntiAlias

Description

A constant equals to 6 to represent that text should be drawn with an automatically determined anti-alias method that behaves the same way as in ChartDirector 5.0.x or earlier versions.

This constant is used in BaseChart.setAntiAlias and DrawArea.setAntiAlias.


Chart.TryPalette

Chart.TryPalette

Declaration

public const int 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.


Chart.ForcePalette

Chart.ForcePalette

Declaration

public const int 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.


Chart.NoPalette

Chart.NoPalette

Declaration

public const int 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.


Chart.Quantize

Chart.Quantize

Declaration

public const int 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.


Chart.OrderedDither

Chart.OrderedDither

Declaration

public const int 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.


Chart.ErrorDiffusion

Chart.ErrorDiffusion

Declaration

public const int 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.


Chart.SideLayout

Chart.SideLayout

Declaration

public const int 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.


Chart.CircleLayout

Chart.CircleLayout

Declaration

public const int 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.


Chart.Side

Chart.Side

Declaration

public const int 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.


Chart.Stack

Chart.Stack

Declaration

public const int 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.


Chart.Overlay

Chart.Overlay

Declaration

public const int 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.


Chart.Percentage

Chart.Percentage

Declaration

public const int 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.


Chart.MonotonicNone

Chart.MonotonicNone

Declaration

public const int MonotonicNone

Description

A constant equals to 0 to represent that a spline curve is not constraint to flow in any direction.

This constant is used in SplineLayer.setMonotonicity.


Chart.MonotonicX

Chart.MonotonicX

Declaration

public const int MonotonicX

Description

A constant equals to 1 to represent that a spline curve is constrained to not overshooting or undershooting in the x-axis direction.

This constant is used in SplineLayer.setMonotonicity.


Chart.MonotonicY

Chart.MonotonicY

Declaration

public const int MonotonicY

Description

A constant equals to 2 to represent that a spline curve is constrained to not overshooting or undershooting in the y-axis direction.

This constant is used in SplineLayer.setMonotonicity.


Chart.MonotonicXY

Chart.MonotonicXY

Declaration

public const int MonotonicXY

Description

A constant equals to 3 to represent that a spline curve is constrained to not overshooting or undershooting in both the x-axis direction and the y-axis direction.

This constant is used in SplineLayer.setMonotonicity.


Chart.MonotonicAuto

Chart.MonotonicAuto

Declaration

public const int MonotonicAuto

Description

A constant equals to 3 to represent that the system will automatically determine whether to constrained a spline curve to not overshooting or undershooting in the x-axis direction and/or the y-axis direction.

This constant is used in SplineLayer.setMonotonicity.


Chart.LinearRegression

Chart.LinearRegression

Declaration

public const int LinearRegression

Description

A constant equals to 1 to represent that linear regression be used to draw a trend line.

This constant is used in TrendLayer.setRegressionType.


Chart.ConstrainedLinearRegression

Chart.ConstrainedLinearRegression

Declaration

public const int ConstrainedLinearRegression

Description

A constant equals to 0 to represent that constrained linear regression be used to draw a trend line.

This constant is used in TrendLayer.setRegressionType.


Chart.ExponentialRegression

Chart.ExponentialRegression

Declaration

public const int ExponentialRegression

Description

A constant equals to -1 to represent that exponential regression be used to draw a trend line.

This constant is used in TrendLayer.setRegressionType.


Chart.LogarithmicRegression

Chart.LogarithmicRegression

Declaration

public const int LogarithmicRegression

Description

A constant equals to -2 to represent that logarithmic regression be used to draw a trend line.

This constant is used in TrendLayer.setRegressionType.


Chart.LogTick

Chart.LogTick

Declaration

public const double 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.

For example, a log scale axis using LogTick may have labels like 1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, .... The 1 - 2 - 5 - 10 labels are chosen because they are approximately equally spaced visually in log scale.

This constant is used in Axis.setLogScale.


Chart.LinearTick

Chart.LinearTick

Declaration

public const double LinearTick

Description

A constant equals to +1.5E+308 to represent that the ticks in a log scale axis should be 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10 style increments.

For example, a log scale axis using LinearTick may have labels like 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 300, .....

This constant is used in Axis.setLogScale.


Chart.TickInc

Chart.TickInc

Declaration

public const double TickInc

Description

A constant equals to +1E+200 to represent the distance between major ticks.

This constant is used in Axis.setLabelOffset and Axis.setTickOffset.


Chart.MinorTickOnly

Chart.MinorTickOnly

Declaration

public const double 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.


Chart.MicroTickOnly

Chart.MicroTickOnly

Declaration

public const double 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 BaseMeter.setScale3.


Chart.PixelScale

Chart.PixelScale

Declaration

public const int 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.


Chart.XAxisScale

Chart.XAxisScale

Declaration

public const int 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.


Chart.YAxisScale

Chart.YAxisScale

Declaration

public const int 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.


Chart.AngularAxisScale

Chart.AngularAxisScale

Declaration

public const int 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.


Chart.RadialAxisScale

Chart.RadialAxisScale

Declaration

public const int 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.


Chart.EndPoints

Chart.EndPoints

Declaration

public const int EndPoints

Description

A constant equals to 3 to represent that the vector lengths and directions are measured by specifying the end points.

This constant is used in XYChart.addVectorLayer, VectorLayer.setVector, PolarChart.addVectorLayer and PolarVectorLayer.setVector.


Chart.DataBound

Chart.DataBound

Declaration

public const int DataBound

Description

A constant equals to -1.7E-100 to represent that the interpolated z values should not exceed the minimum or maximum values of the original data.

This constant is used in ContourLayer.setZBounds.


Chart.XAxisAtOrigin

Chart.XAxisAtOrigin

Declaration

public const int 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.


Chart.YAxisAtOrigin

Chart.YAxisAtOrigin

Declaration

public const int 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.


Chart.XYAxisAtOrigin

Chart.XYAxisAtOrigin

Declaration

public const int 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.


Chart.XAxisSymmetric

Chart.XAxisSymmetric

Declaration

public const int 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.


Chart.XAxisSymmetricIfNeeded

Chart.XAxisSymmetricIfNeeded

Declaration

public const int 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.


Chart.YAxisSymmetric

Chart.YAxisSymmetric

Declaration

public const int 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.


Chart.YAxisSymmetricIfNeeded

Chart.YAxisSymmetricIfNeeded

Declaration

public const int 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.


Chart.XYAxisSymmetric

Chart.XYAxisSymmetric

Declaration

public const int 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.


Chart.XYAxisSymmetricIfNeeded

Chart.XYAxisSymmetricIfNeeded

Declaration

public const int 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.


Chart.NormalLegend

Chart.NormalLegend

Declaration

public const int 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.


Chart.ReverseLegend

Chart.ReverseLegend

Declaration

public const int 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.


Chart.NoLegend

Chart.NoLegend

Declaration

public const int 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.


Chart.AutoGrid

Chart.AutoGrid

Declaration

public const int 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.


Chart.ChartBackZ

Chart.ChartBackZ

Declaration

public const int 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.


Chart.ChartFrontZ

Chart.ChartFrontZ

Declaration

public const int 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.


Chart.PlotAreaZ

Chart.PlotAreaZ

Declaration

public const int 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.


Chart.GridLinesZ

Chart.GridLinesZ

Declaration

public const int 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.


Chart.TouchBar

Chart.TouchBar

Declaration

public const int 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.


Chart.HLOCDefault

Chart.HLOCDefault

Declaration

public const int 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.


Chart.HLOCOpenClose

Chart.HLOCOpenClose

Declaration

public const int 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.


Chart.HLOCUpDown

Chart.HLOCUpDown

Declaration

public const int 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.


Chart.AggregateSum

Chart.AggregateSum

Declaration

public const int AggregateSum

Description

A constant equals to 0 to represent using the sum as the aggregated value in ArrayMath.aggregate.


Chart.AggregateAvg

Chart.AggregateAvg

Declaration

public const int AggregateAvg

Description

A constant equals to 1 to represent using the average as the aggregated value in ArrayMath.aggregate.


Chart.AggregateStdDev

Chart.AggregateStdDev

Declaration

public const int AggregateStdDev

Description

A constant equals to 2 to represent using the standard deviation as the aggregated value in ArrayMath.aggregate.


Chart.AggregateMin

Chart.AggregateMin

Declaration

public const int AggregateMin

Description

A constant equals to 3 to represent using the minimum value as the aggregated value in ArrayMath.aggregate.


Chart.AggregateMed

Chart.AggregateMed

Declaration

public const int AggregateMed

Description

A constant equals to 4 to represent using the median value as the aggregated value in ArrayMath.aggregate.


Chart.AggregateMax

Chart.AggregateMax

Declaration

public const int AggregateMax

Description

A constant equals to 5 to represent using the maximum value as the aggregated value in ArrayMath.aggregate.


Chart.AggregatePercentile

Chart.AggregatePercentile

Declaration

public const int AggregatePercentile

Description

A constant equals to 6 to represent using the percentile value as the aggregated value in ArrayMath.aggregate.


Chart.AggregateFirst

Chart.AggregateFirst

Declaration

public const int AggregateFirst

Description

A constant equals to 7 to represent using the first value as the aggregated value in ArrayMath.aggregate.


Chart.AggregateLast

Chart.AggregateLast

Declaration

public const int AggregateLast

Description

A constant equals to 8 to represent using the last value as the aggregated value in ArrayMath.aggregate.


Chart.AggregateCount

Chart.AggregateCount

Declaration

public const int AggregateCount

Description

A constant equals to 9 to represent using the item count as the aggregated value in ArrayMath.aggregate.


Chart.BoxFilter

Chart.BoxFilter

Declaration

public const int 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.


Chart.LinearFilter

Chart.LinearFilter

Declaration

public const int 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.


Chart.QuadraticFilter

Chart.QuadraticFilter

Declaration

public const int 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.


Chart.BSplineFilter

Chart.BSplineFilter

Declaration

public const int 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.


Chart.HermiteFilter

Chart.HermiteFilter

Declaration

public const int 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.


Chart.CatromFilter

Chart.CatromFilter

Declaration

public const int 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.


Chart.MitchellFilter

Chart.MitchellFilter

Declaration

public const int 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.


Chart.SincFilter

Chart.SincFilter

Declaration

public const int 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.


Chart.LanczosFilter

Chart.LanczosFilter

Declaration

public const int 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.


Chart.GaussianFilter

Chart.GaussianFilter

Declaration

public const int 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.


Chart.HanningFilter

Chart.HanningFilter

Declaration

public const int 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.


Chart.HammingFilter

Chart.HammingFilter

Declaration

public const int 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.


Chart.BlackmanFilter

Chart.BlackmanFilter

Declaration

public const int 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.


Chart.BesselFilter

Chart.BesselFilter

Declaration

public const int 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.


Chart.MouseUsageDefault

Chart.MouseUsageDefault

Declaration

public const int MouseUsageDefault

Description

A constant equals to 0 to represent using the default mouse behaviour.

This constant is used in ChartViewer.setMouseUsage and WebChartViewer.setMouseUsage .


Chart.MouseUsageScrollOnDrag

Chart.MouseUsageScrollOnDrag

Declaration

public const int MouseUsageScrollOnDrag

Description

A constant equals to 1 to represent using the mouse for drag scrolling.

This constant is used in ChartViewer.setMouseUsage and WebChartViewer.setMouseUsage .


Chart.MouseUsageScrollOnDrop

Chart.MouseUsageScrollOnDrop

Declaration

public const int MouseUsageScrollOnDrop

Description

A constant equals to 2 to represent using the mouse for drag scrolling.

This constant is used in ChartViewer.setMouseUsage and WebChartViewer.setMouseUsage .


Chart.MouseUsageScroll

Chart.MouseUsageScroll

Declaration

public const int MouseUsageScroll

Description

A constant equals to 2 to represent using the mouse for drag scrolling.

This constant is used in ChartViewer.setMouseUsage and WebChartViewer.setMouseUsage .


Chart.MouseUsageZoomIn

Chart.MouseUsageZoomIn

Declaration

public const int MouseUsageZoomIn

Description

A constant equals to 3 to represent using the mouse for zoom in actions.

This constant is used in ChartViewer.setMouseUsage and WebChartViewer.setMouseUsage .


Chart.MouseUsageZoomOut

Chart.MouseUsageZoomOut

Declaration

public const int MouseUsageZoomOut

Description

A constant equals to 4 to represent using the mouse for zoom out actions.

This constant is used in ChartViewer.setMouseUsage and WebChartViewer.setMouseUsage .


Chart.DirectionHorizontal

Chart.DirectionHorizontal

Declaration

public const int DirectionHorizontal

Description

A constant equals to 0 to represent that the zoom and/or scroll orientation is horizontal.

This constant is used in ChartViewer.setZoomDirection, ChartViewer.setScrollDirection, WebChartViewer.setZoomDirection and WebChartViewer.setScrollDirection .


Chart.DirectionVertical

Chart.DirectionVertical

Declaration

public const int DirectionVertical

Description

A constant equals to 1 to represent that the zoom and/or scroll orientation is vertical.

This constant is used in ChartViewer.setZoomDirection, ChartViewer.setScrollDirection, WebChartViewer.setZoomDirection and WebChartViewer.setScrollDirection .


Chart.DirectionHorizontalVertical

Chart.DirectionHorizontalVertical

Declaration

public const int 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 ChartViewer.setZoomDirection, ChartViewer.setScrollDirection, WebChartViewer.setZoomDirection and WebChartViewer.setScrollDirection .


Chart.setLicenseCode

Chart.setLicenseCode

Usage

public static String setLicenseCode(String 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.


Chart.getVersion

Chart.getVersion

Usage

public static int 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.


Chart.getBootLog

Chart.getBootLog

Usage

public static String 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.


Chart.testFont

Chart.testFont

Usage

public static String testFont(String font, int fontIndex, double fontHeight, double fontWidth, double 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 is ignored in the Java edition of ChartDirector and should be set to 0. It is solely for consistency and compatibility with other editions of ChartDirector.
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.


Chart.chartTime

Chart.chartTime

Usage

public static double chartTime(int y, int m, int d [, int h [, int n [, int 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.


Chart.chartTime2

Chart.chartTime2

Usage

public static double chartTime2(int 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.


Chart.getChartYMD

Chart.getChartYMD

Usage

public static int getChartYMD(double 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).


Chart.getChartWeekDay

Chart.getChartWeekDay

Usage

public static int getChartWeekDay(double 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.


Chart.CTime

Chart.CTime

Usage

public static double CTime(java.util.Date time)

Description

Converts a java.util.Date to ChartDirector's date/time format.

In common date/time charts, the x-axis represents dates/times, while the y-axis represents numeric data. For these cases, ChartDirector provides overloaded methods that supports both numeric values and java.util.Date values as inputs.

However, it is possible in some special applications, both x and y-axes can represent dates/times. ChartDirector supports this type of usage, but its API only allows "double precision numbers" as y-value inputs. In these cases, CTime can be used to convert java.util.Date to ChartDirector's date/time format, which uses double precision numbers to represent dates/times.

Arguments

Argument | Default | Description
time | (Mandatory) | A java.util.Date object.

Return Value

A number representing dates/time in ChartDirector's date/time format.


Chart.CTime2

Chart.CTime2

Usage

public static double[] CTime2(java.util.Date[] times)

Description

Converts an array of java.util.Date objects to ChartDirector's date/time format.

This function is similar to Chart.CTime, but operate on an array of java.util.Date objects instead of a single java.util.Date object.

Arguments

Argument | Default | Description
times | (Mandatory) | An array of java.util.Date objects.

Return Value

An array of numbers representing dates/times in ChartDirector's date/time format.


Chart.NTime

Chart.NTime

Usage

public static java.util.Date NTime(double time)

Description

Converts a date/time in ChartDirector's date/time format to a java.util.Date object.

This method is the reverse of Chart.CTime.

Arguments

Argument | Default | Description
time | (Mandatory) | A number representing date/time using ChartDirector's date/time format.

Return Value

A java.util.Date object.


Chart.NTime2

Chart.NTime2

Usage

public static java.util.Date[] NTime2(double[] times)

Description

Converts an array of dates/times in ChartDirector's date/time format to java.util.Date objects.

This method is the reverse of Chart.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 java.util.Date objects.


Chart.goldColor

Chart.goldColor

Usage

public static int goldColor([ int angle ])

Description

Creates a golden color, most commonly used as a background color.

This method is a short cut to the Chart.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.


Chart.silverColor

Chart.silverColor

Usage

public static int silverColor([ int angle ])

Description

Creates a silver color, most commonly used as a background color.

This method is a short cut to the Chart.metalColor method, using grey (DDDDDD 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.


Chart.metalColor

Chart.metalColor

Usage

public static int metalColor(int c [, int 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.


Chart.brushedGoldColor

Chart.brushedGoldColor

Usage

public static int brushedGoldColor([ int texture [, int angle ]])

Description

Creates a brushed golden color, most commonly used as a background color.

This method is a short cut to the Chart.brushedMetalColor method, using yellow (FFEE44 in hex) as the base color.

Arguments

Argument | Default | Description
texture | 2 | The strength of the brushed texture. Must be 0, 1, 2 or 3 for no texture, light texture, medium texture and strong texture.
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 brushed golden color.


Chart.brushedSilverColor

Chart.brushedSilverColor

Usage

public static int brushedSilverColor([ int texture [, int angle ]])

Description

Creates a brushed silver color, most commonly used as a background color.

This method is a short cut to the Chart.brushedMetalColor method, using grey (DDDDDD in hex) as the base color.

Arguments

Argument | Default | Description
texture | 2 | The strength of the brushed texture. Must be 0, 1, 2 or 3 for no texture, light texture, medium texture and strong texture.
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 brushed silver color.


Chart.brushedMetalColor

Chart.brushedMetalColor

Usage

public static int brushedMetalColor(int c [, int texture [, int angle ]])

Description

Creates a color by modulates the brightness of another color to create brushed 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 color will then be modulated with a horizontal texture to create the brushed 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.
texture | 2 | The strength of the brushed texture. Must be 0, 1, 2 or 3 for no texture, light texture, medium texture and strong texture.
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 brushed metallic color.


Chart.CColor

Chart.CColor

Usage

public static int CColor(java.awt.Color color)

Description

Converts a java.awt.Color object to a ChartDirector color.

ChartDirector represents ARGB colors using a web and HTML compatible format. For example, red is represented as FF0000, the same as used in HTML.

On the other hand, in Java, colors are sometimes represented as java.awt.Color objects. This method converts a java.awt.Color object to ChartDirector's color format.

Arguments

Argument | Default | Description
color | (Mandatory) | A java.awt.Color object.

Return Value

A ChartDirector color.


Chart.CColor2

Chart.CColor2

Usage

public static int[] CColor2(java.awt.Color[] colors)

Description

Converts an array of java.awt.Color objects to an array of ChartDirector colors.

This function is similar to Chart.CColor, but operate on an array of java.awt.Color objects instead of a single java.awt.Color object.

Arguments

Argument | Default | Description
colors | (Mandatory) | An array of java.awt.Color objects.

Return Value

An array of ChartDirector colors.


Chart.NColor

Chart.NColor

Usage

public static java.awt.Color NColor(int color)

Description

Converts a ChartDirector color to a java.awt.Color object.

This method is the reverse of Chart.CColor.

Arguments

Argument | Default | Description
color | (Mandatory) | A ChartDirector color.

Return Value

An java.awt.Color object.


Chart.NColor2

Chart.NColor2

Usage

public static java.awt.Color[] NColor2(int[] colors)

Description

Converts an array of ChartDirector colors to an array of java.awt.Color objects.

This method is the reverse of Chart.CColor2.

Arguments

Argument | Default | Description
colors | (Mandatory) | An array of ChartDirector colors.

Return Value

An array of java.awt.Color objects.


Chart.glassEffect

Chart.glassEffect

Usage

public static int glassEffect([ int glareSize [, int glareDirection [, int 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 | Description
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 to Box objects (including derived objects such as TextBox objects). 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 Chart.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.


Chart.softLighting

Chart.softLighting

Usage

public static int softLighting([ int direction [, int raisedEffect ]])

Description

A special shading effect that looks like gradient coloring.

This effect is best explained by viewing the examples.

Example | Description
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 to Box objects (including derived objects such as TextBox objects). 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.


Chart.barLighting

Chart.barLighting

Usage

public static int barLighting([ double startBrightness, double endBrightness ])

Description

A special shading effect for rectangular and polygonal bars on a BarLayer. It shades all surfaces of a 2D or 3D bar with gradient colors.

For the front surface of a bar, the gradient is from base line of the bar to the end of the bar. For example, for a vertical bar pointing upwards, the gradient is from bottom to the top. Similarly, for a horizontal bar pointing rightwards, the gradient is from left to right.

For a 3D bar, the gradient for the top surface of a vertical bar or the right surface of a horizontal bar is from front to back. The gradients for the side surfaces are the same as for the front surface.

The gradient is specified with two brightness values at the gradient end points. A brightness less than 1 means the color is darkened, while a brightness greater than 1 means the color is brightened. For example, a brightness of 0.5 means the color is half as bright as the original color. If the original color is red, the color will become dark red. Conversely, a brightness of 2 means the color is twice as bright as the original color. If the original color is red, the color will become light red.

The followings are some examples demonstrating this effect.

Example | Description
Gradient Bar Chart | A 2D horizontal bar chart using the barLighting effect, with the brightness at the end points being 0.75 and 2.0.
Gradient Multi-Bar Chart | A 3D vertical bar chart using the barLighting effect, with the brightness at the end points being 0.75 and 1.75.

The barLighting method returns an integer representing this effect. The integer can be used as the second argument to Layer.setBorderColor for BarLayer objects to apply the effect to bars.

Arguments

Argument | Default | Description
startBrightness | 0.75 | The brightness at the starting point.
endBrightness | 1.5 | The brightness at the ending point.

Return Value

An integer representing the bar lighting effect.


Chart.cylinderEffect

Chart.cylinderEffect

Usage

public static int cylinderEffect([ int orientation [, double ambientIntensity, double diffuseIntensity, double specularIntensity, int shininess ]])

Description

A special shading effect that emulates the lighting of a cylinder surface.

This effect adjusts the brightness of the color of a rectangular box to make it look like cylindrical. The brightness is adjusted as according to the Phong lighting model, in which the light source is from the viewer direction and is far away.

The cylinderEffect method returns an integer representing this effect. The integer can be used as the third argument to Box.setBackground to apply the effect to Box objects (including derived objects such as TextBox objects).

This effect is automatically used for cylindrical bars in a BarLayer. You may use this method to adjust the lighting parameters by using its return value as the second argument to Layer.setBorderColor.

Arguments

Argument | Default | Description
orientation | Center | The orientation of the cylinder. A value of Top or Bottom means the cylinder is vertical. A value of Left or Right means the cylinder is horizontal. A value of Center means the orientation is automatically determined. For a BarLayer, the orientation will be the same as the orientation of the bars. For other objects (eg. TextBox objects), if the object height is bigger than its width, the cylinder will be treated as vertical, otherwise it will be treated as horizontal.
ambientIntensity | 0.5 | The ambient reflection coefficient of the Phong lighting model.
diffuseIntensity | 0.5 | The diffuse reflection coefficient of the Phong lighting model.
specularIntensity | 0.75 | The specular reflection coefficient of the Phong lighting model.
shininess | 8 | The shininess coefficient of the Phong lighting model.

Return Value

An integer representing the cylinder effect.


Chart.phongLighting

Chart.phongLighting

Usage

public static int phongLighting([ double ambientIntensity, double diffuseIntensity, double specularIntensity, int shininess ])

Description

Sets the parameters for the phong lighting effect.

The return value of this method can be used as the second argument to Layer.setBorderColor to configure phong lighting effect for the layer.

Arguments

Argument | Default | Description
ambientIntensity | 0.5 | The ambient reflection coefficient of the Phong lighting model.
diffuseIntensity | 0.5 | The diffuse reflection coefficient of the Phong lighting model.
specularIntensity | 0.75 | The specular reflection coefficient of the Phong lighting model.
shininess | 8 | The shininess coefficient of the Phong lighting model.

Return Value

An integer representing the phong lighting effect.


Chart.PolygonShape

Chart.PolygonShape

Usage

public static int PolygonShape(int 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.


Chart.Polygon2Shape

Chart.Polygon2Shape

Usage

public static int Polygon2Shape(int 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.


Chart.StarShape

Chart.StarShape

Usage

public static int StarShape(int 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.


Chart.CrossShape

Chart.CrossShape

Usage

public static int CrossShape(double 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.


Chart.Cross2Shape

Chart.Cross2Shape

Usage

public static int Cross2Shape(double 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.


Chart.PolynomialRegression

Chart.PolynomialRegression

Usage

public static int PolynomialRegression(int n)

Description

Sets the degree of the polynomial regression to be used in a trend layer.

This method is used to specify the polynomial regression type in TrendLayer.setRegressionType.

Arguments

Argument | Default | Description
n | (Mandatory) | The degree of the polynomial.

Return Value

An integer representing a polynomial regression of degree n to be used as an argument to TrendLayer.setRegressionType.


Chart.StartOfHourFilter

Chart.StartOfHourFilter

Usage

public static int StartOfHourFilter([ int labelStep [, double 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.


Chart.StartOfDayFilter

Chart.StartOfDayFilter

Usage

public static int StartOfDayFilter([ int labelStep [, double 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.


Chart.StartOfWeekFilter

Chart.StartOfWeekFilter

Usage

public static int StartOfWeekFilter([ int labelStep [, double 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.


Chart.StartOfMonthFilter

Chart.StartOfMonthFilter

Usage

public static int StartOfMonthFilter([ int labelStep [, double 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.


Chart.StartOfYearFilter

Chart.StartOfYearFilter

Usage

public static int StartOfYearFilter([ int labelStep [, double 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.


Chart.RegularSpacingFilter

Chart.RegularSpacingFilter

Usage

public static int RegularSpacingFilter([ int labelStep [, double 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.


Chart.AllPassFilter

Chart.AllPassFilter

Usage

public static int 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.


Chart.NonePassFilter

Chart.NonePassFilter

Usage

public static int 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.


Chart.SelectItemFilter

Chart.SelectItemFilter

Usage

public static int SelectItemFilter(int 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.


Chart.bSearch

Chart.bSearch

Usage

public double bSearch({Date[] | double[] | String[]} a, {Date[] | double[] | String[]} v)

Description

Uses binary search to search for a value in an array.

This method returns the array index of the value in the array, which must be sorted in ascending order.

If the value is in between two elements of the array, this method returns a non-integer that interpolates the indexes of the two elements. For example, suppose the array consists of 3 elements [4, 6, 10]. If this method is used to search for the value 7, it will return 1.25.

If the value is smaller or larger than all the elements in the array, this method returns the nearest index, which must be either 0 or the index of the last element of the array.

Arguments

Argument | Default | Description
a | (Mandatory) | The array to be searched.
v | (Mandatory) | The value to search for.

Return Value

The index of the value within the array. If the value is in between two elements of the array, this method returns a non-integer that interpolates the indexes of the two elements. If the value is smaller or larger than all the elements in the array, thie method returns the nearest index.


Chart.arraySlice

Chart.arraySlice

Usage

public static Object arraySlice(Object a, int startIndex, int len)

Description

Creates a new array with the elements copied from a part of a given array.

Arguments

Argument | Default | Description
a | (Mandatory) | The array to be copied.
startIndex | (Mandatory) | The array index to start copying from.
len | (Mandatory) | The number of elements to copy.

Return Value

A new array with the elements copied from a part of a given array.


Chart.stringJoin

Chart.stringJoin

Usage

public static String stringJoin({String[] | Collection | Iterator} a, String delimiter)

Description

Concatenates all elements of a string array or collection using the specified delimiter.

Arguments

Argument | Default | Description
a | (Mandatory) | The string array, collection or an iterator for a container that contains the strings to be concatenated.
delimiter | (Mandatory) | The delimiter that separates the strings to be concatenated.

Return Value

A string formed by concatenating all input strings with the specified delimiter.


Chart.getUniqueId

Chart.getUniqueId

Usage

public static synchronized int getUniqueId()

Description

Returns an incrementing number. The method for compatibility with previous version of ChartDirector only.

The returned number initialized to 1 when the class is first loaded. Each time this method is called, the returned number will increment by 1.

Arguments

None

Return Value

An integer representing the current value of the incrementing counter.


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 reference point of the box, which by default is 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.
getLeftX | (Self) | Gets the left x pixel coordinate of the box.
getTopY | (Self) | Gets the top y pixel coordinate of the box.
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

public void setPos(int x, int y)

Description

Sets the coordinates of the reference point of the box, which by default is the top-left corner of the box.

For TextBox with the width and height automatically determined, the TextBox.setAlignment method can be used to modify the anchor position of the reference point. For example, an alignment of Center means the reference point is the center of the box.

For TextBox objects with positions set by ChartDirector (such as the TextBox returned from Axis.addMark or Layer.setDataLabelStyle), the setPos method can be used to set the offsets relative to the default positions of the objects.

Arguments

Argument | Default | Description
x | (Mandatory) | The x coordinate of the reference point of the box.
y | (Mandatory) | The y coordinate of the reference point of the box.

Return Value

None


Box.setSize

Box.setSize

Usage

public void setSize(int w, int 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

public void setBackground(int color [, int edgeColor [, int 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 Chart.glassEffect, Chart.softLighting and Chart.cylinderEffect effects.

Return Value

None


Box.setRoundedCorners

Box.setRoundedCorners

Usage

public void setRoundedCorners([ int r1 [, int r2 [, int r3 [, int 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. -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. -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. -1 means it is the same as the radius of the top-left corner.

Return Value

None


Box.getLeftX

Box.getLeftX

Usage

public int getLeftX()

Description

Gets the left x pixel coordinate of the box.

In some cases, the left x coordinate of a box may be dynamically determined. An example is the left x coordinate of an LegendBox with alignment set to Center. To determine the left x coordinate, the size of the box must be known first. For these cases, the left x coordinate is undefined until the legend box or the entire chart 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 the left x pixel coordinate of the box.


Box.getTopY

Box.getTopY

Usage

public int getTopY()

Description

Gets the top y pixel coordinate of the box.

In some cases, the top y coordinate of a box may be dynamically determined. An example is the top y coordinate of an LegendBox with alignment set to Center. To determine the top y coordinate, the size of the box must be known first. For these cases, the top y coordinate is undefined until the legend box or the entire chart 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 top y pixel coordinate of the box.


Box.getWidth

Box.getWidth

Usage

public int getWidth()

Description

Gets the width of the box.

In some cases, the width of a box may be dynamically determined. An example is the width of an LegendBox. For these cases, the width is undefined until the legend box or the entire chart 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

public int getHeight()

Description

Gets the height of the box.

In some cases, the height of a box may be dynamically determined. An example is the height of an LegendBox. For these cases, the height is undefined until the legend box or the entire chart 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

public String getImageCoor([ int offsetX, int 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

public void setZOrder(int 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.
setPos | Box | Sets the coordinates of the reference point of the box, which by default is 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.
getLeftX | Box | Gets the left x pixel coordinate of the box.
getTopY | Box | Gets the top y pixel coordinate of the box.
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

public void setText(String 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

public void setFontStyle(String font)

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.

Return Value

None


TextBox.setFontSize

TextBox.setFontSize

Usage

public void setFontSize(double fontHeight [, double 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

public void setFontAngle(double angle [, boolean 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 | 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 value means vertical layout. A false value means horizontal layout.

Return Value

None


TextBox.setFontColor

TextBox.setFontColor

Usage

public void setFontColor(int 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

public void setAlignment(int 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

public void setWidth(int 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

public void setHeight(int 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

public void setMaxWidth(int 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

public void void setTruncate(int maxWidth [, int 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

public void setMargin(int 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

public void setMargin2(int leftMargin, int rightMargin, int topMargin, int bottomMargin)

Description

Sets the margins of the text box.

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


CDMLTable

CDMLTable

The CDMLTable class represents tables for CDML contents.

A CDMLTable consists of rows and columns. The rows are numbered from top to bottom, with the top row being 0. The columns are numbered from left to right, with the leftmost column being 0.

By default, the intersection of a row and a column is a cell. You may create cells that span multiple rows and/or columns with CDMLTable.setCell.

The styles of a cell, such as its background color, font, etc., are determined using the following order.

For any style attribute (eg. background color):

  • The TextBox object representing the cell (obtained using CDMLTable.getCell) is examined to see if the attribute is defined. If it is defined, its value is used.

  • The TextBox objects representing the prototype of the cells in the column and row of the cell (obtained using CDMLTable.getColStyle and CDMLTable.getRowStyle) are examined to see if the attribute is defined. If the attribute is defined, its value is used. If the attribute is defined in both the column and row prototypes, the prototype that is created later will take precedence.

  • The attribute is taken from the TextBox object representing the prototype of all cells (obtained using CDMLTable.getStyle).

For example, if you set the background to white using the prototype for all cells, the background of the whole table will change to white. If you then set the background to grey using the prototype for a row, the background for that row will change to grey. Finally, if you set the background to red using the text box that represents a cell, only that cell will have a red background.

Method | Inherited | Description
setPos | (Self) | Sets the position of the table.
setText | (Self) | Puts text into a cell in the table.
setCell | (Self) | Sets the number of rows and columns that a cell spans, and puts text in the cell.
insertCol | (Self) | Inserts a column to the table.
appendCol | (Self) | Appends a column to the right of the table.
getColCount | (Self) | Gets the number of columns in the table.
insertRow | (Self) | Inserts a row to the table.
appendRow | (Self) | Appends a row to the bottom of the table.
getRowCount | (Self) | Gets the number of rows in the table.
getCell | (Self) | Gets the TextBox object that represents a cell.
getColStyle | (Self) | Gets the TextBox object that represents the prototype of the cells in a column.
getRowStyle | (Self) | Gets the TextBox object that represents the prototype of the cells in a row.
getStyle | (Self) | Gets the TextBox object that represents the prototype of the cells in the table.
layout | (Self) | Lays out the table.
getColWidth | (Self) | Gets the width of a column.
getRowHeight | (Self) | Gets the height of a row.
getWidth | (Self) | Gets the width of the table.
getHeight | (Self) | Gets the height of the table.
setZOrder | (Self) | Sets the z-order (drawing order) of the table.


CDMLTable.setPos

CDMLTable.setPos

Usage

public void setPos(int x, int y [, int alignment ])

Description

Sets the position of the table.

Arguments

Argument | Default | Description
x | (Mandatory) | The x-coordinate of the reference point used to position the table.
y | (Mandatory) | The y-coordinate of the reference point used to position the table.
alignment | TopLeft | The alignment of the table with respect to the reference point. For example, a value of TopLeft means the reference point is the top- left corner of the table. See Alignment Specification for supported alignment types..

Return Value

None


CDMLTable.setText

CDMLTable.setText

Usage

public TextBox setText(int col, int row, String text)

Description

Puts text into a cell in the table.

Arguments

Argument | Default | Description
col | (Mandatory) | The column number of the cell. The column is numbered from left to right, with the leftmost column being 0.
row | (Mandatory) | The row number of the cell. The row is numbered from top to bottom, with the top row being 0.
text | (Mandatory) | The text to be put into the cell.

Return Value

A TextBox object representing the cell. This may be used to fine-tune the appearance of the cell.


CDMLTable.setCell

CDMLTable.setCell

Usage

public TextBox setCell(int col, int row, int width, int height, String text)

Description

Sets the number of rows and columns that a cell spans, and puts text in the cell.

Arguments

Argument | Default | Description
col | (Mandatory) | The column number of the cell. The column is numbered from left to right, with the leftmost column being 0.
row | (Mandatory) | The row number of the cell. The row is numbered from top to bottom, with the top row being 0.
width | (Mandatory) | The number of columns spanned by the cell. The cell will occupy the columns from (col) to (col + width - 1).
height | (Mandatory) | The number of rows spanned by the cell. The cell will occupy the rows from (row) to (row + height - 1).
text | (Mandatory) | The text to be put into the cell.

Return Value

A TextBox object representing the cell. This may be used to fine-tune the appearance of the cell.


CDMLTable.insertCol

CDMLTable.insertCol

Usage

public TextBox insertCol(int col)

Description

Inserts a column to the table.

Arguments

Argument | Default | Description
col | (Mandatory) | The column number of the inserted column. The column is numbered from left to right, with the leftmost column being 0.

Return Value

A TextBox object representing the prototype of the cells in the new column. This may be used to fine-tune the appearance of the cells in the new column.


CDMLTable.appendCol

CDMLTable.appendCol

Usage

public TextBox appendCol()

Description

Appends a column to the right of the table.

Arguments

None

Return Value

A TextBox object representing the prototype of the new column. This may be used to fine-tune the appearance of the new column.


CDMLTable.getColCount

CDMLTable.getColCount

Usage

public int getColCount()

Description

Gets the number of columns in the table.

Arguments

None

Return Value

The number of columns in the table.


CDMLTable.insertRow

CDMLTable.insertRow

Usage

public TextBox insertRow(int row)

Description

Inserts a row to the table.

Arguments

Argument | Default | Description
row | (Mandatory) | The row number of the inserted row. The row is numbered from top to bottom, with the top row being 0.

Return Value

A TextBox object representing the prototype of the new row. This may be used to fine-tune the appearance of the new row.


CDMLTable.appendRow

CDMLTable.appendRow

Usage

public TextBox appendRow()

Description

Appends a row to the bottom of the table.

Arguments

None

Return Value

A TextBox object representing the prototype of the cells in the new row. This may be used to fine-tune the appearance of the cells in the new row.


CDMLTable.getRowCount

CDMLTable.getRowCount

Usage

public int getRowCount()

Description

Gets the number of rows in the table.

Arguments

None

Return Value

The number of rows in the table.


CDMLTable.getCell

CDMLTable.getCell

Usage

public TextBox getCell(int col, int row)

Description

Gets the TextBox object that represents a cell.

Arguments

Argument | Default | Description
col | (Mandatory) | The column number of the cell. The column is numbered from left to right, with the leftmost column being 0.
row | (Mandatory) | The row number of the cell. The row is numbered from top to bottom, with the top row being 0.

Return Value

A TextBox object representing the cell. This may be used to fine-tune the appearance of the cell.


CDMLTable.getColStyle

CDMLTable.getColStyle

Usage

public TextBox getColStyle(int col)

Description

Gets the TextBox object that represents the prototype of the cells in a column.

Arguments

Argument | Default | Description
col | (Mandatory) | The column number of the column. The column is numbered from left to right, with the leftmost column being 0.

Return Value

A TextBox object representing the prototype of the cells in the column. This may be used to fine-tune the appearance of the cells in the column.


CDMLTable.getRowStyle

CDMLTable.getRowStyle

Usage

public TextBox getRowStyle(int row)

Description

Gets the TextBox object that represents the prototype of the cells in a row.

Arguments

Argument | Default | Description
row | (Mandatory) | The row number of the row. The row is numbered from top to bottom, with the top row being 0.

Return Value

A TextBox object representing the prototype of the cells in the row. This may be used to fine-tune the appearance of the cells in the row.


CDMLTable.getStyle

CDMLTable.getStyle

Usage

public TextBox getStyle()

Description

Gets the TextBox object that represents the prototype of the cells in the table.

Arguments

None

Return Value

A TextBox object representing the prototype of the cells in the table. This may be used to fine-tune the appearance of the cells in the table.


CDMLTable.layout

CDMLTable.layout

Usage

public void layout()

Description

Lays out the table.

Laying out the table means computing the table metrics - the widths and heights of all columns, rows and cells. When drawing the table, ChartDirector will automatically call this method. You only need to call this method if you need to get the table metrics (eg. using CDMLTable.getColWidth, CDMLTable.getRowHeight, CDMLTable.getWidth or CDMLTable.getHeight) before the table is drawn.

Arguments

None

Return Value

None


CDMLTable.getColWidth

CDMLTable.getColWidth

Usage

public int getColWidth(int col)

Description

Gets the width of a column.

Note that you need to call CDMLTable.layout first to layout the table before calling this method.

Arguments

Argument | Default | Description
col | (Mandatory) | The column number of the column. The column is numbered from left to right, with the leftmost column being 0.

Return Value

The width of the column in pixels.


CDMLTable.getRowHeight

CDMLTable.getRowHeight

Usage

public int getRowHeight(int row)

Description

Gets the height of a row.

Note that you need to call CDMLTable.layout first to layout the table before calling this method.

Arguments

Argument | Default | Description
row | (Mandatory) | The row number of the row. The row is numbered from top to bottom, with the top row being 0.

Return Value

The height of the row in pixels.


CDMLTable.getWidth

CDMLTable.getWidth

Usage

public int getWidth()

Description

Gets the width of the table.

Note that you need to call CDMLTable.layout first to layout the table before calling this method.

Arguments

None

Return Value

The width of the table in pixels.


CDMLTable.getHeight

CDMLTable.getHeight

Usage

public int getHeight()

Description

Gets the height of the table.

Note that you need to call CDMLTable.layout first to layout the table before calling this method.

Arguments

None

Return Value

The height of the table in pixels.


CDMLTable.setZOrder

CDMLTable.setZOrder

Usage

public void setZOrder(int z)

Description

Sets the z-order (drawing order) of the table.

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 table.

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

public void setPos(int x1, int y1, int x2, int 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

public void setColor(int 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

public void setWidth(int 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

public void setZOrder(int 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, exclusive of the drop shadow (if any).
getWidth | (Self) | Gets the width of the chart.
getHeight | (Self) | Gets the height of the chart.
getAbsOffsetX | (Self) | Gets the x offset of the chart relative to the outermost MultiChart container.
getAbsOffsetY | (Self) | Gets the y offset of the chart relative to the outermost MultiChart container.
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.
setDropShadow | (Self) | Adds a drop shadow to the chart.
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 file system search path for loading image files.
setSearchPath2 | (Self) | Sets the ClassLoader for loading images.
setSearchPath3 | (Self) | Search for image files using the ServletContext and ServletRequest.
setSearchPath4 | (Self) | Search for image files using a URL as the base path.
setTransparentColor | (Self) | Specifies a certain color to mean transparent when creating a raster 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.
addTable | (Self) | Adds a CDML table 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.
adjustBrightness | (Self) | Creates a color that is a darkened or brightened version of the given 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.
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 axes (if any) and compute the positions of the various objects in the chart.
makeImage | (Self) | Generates the chart as a java.awt.Image object.
enableVectorOutput | (Self) | Enables true vector graphics output.
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.
initDynamicLayer | (Self) | Initializes a dynamic layer for drawing text and shapes.
removeDynamicLayer | (Self) | Removes the dynamic layer if any.
getHTMLImageMap | (Self) | Generates an HTML image map for the chart.
getJsChartModel | (Self) | Gets the Javascript Chart Model for passing to WebChartViewer.setChartModel for the purpose of supporting track cursors in a web application.
getChartMetrics | (Self) | Gets the chart metrics for passing to WebChartViewer.setChartMetrics to support view ports for web applications.


BaseChart.setSize

BaseChart.setSize

Usage

public void setSize(int width, int height)

Description

Sets the size of the chart, exclusive of the drop shadow (if any).

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.getWidth

BaseChart.getWidth

Usage

public int getWidth()

Description

Gets the width of the chart.

Arguments

None

Return Value

An integer representing the width of the chart.


BaseChart.getHeight

BaseChart.getHeight

Usage

public int getHeight()

Description

Gets the height of the chart.

Arguments

None

Return Value

An integer representing the height of the chart.


BaseChart.getAbsOffsetX

BaseChart.getAbsOffsetX

Usage

public int getAbsOffsetX()

Description

Gets the x offset of the chart relative to the outermost MultiChart container.

Arguments

None

Return Value

An integer representing the x offset in pixels relative to the outermost MultiChart container, or 0 if the chart is not within a MultiChart container.


BaseChart.getAbsOffsetY

BaseChart.getAbsOffsetY

Usage

public int getAbsOffsetY()

Description

Gets the y offset of the chart relative to the outermost MultiChart container.

Arguments

None

Return Value

An integer representing the y offset in pixels relative to the outermost MultiChart container, or 0 if the chart is not within a MultiChart container.


BaseChart.setBackground

BaseChart.setBackground

Usage

public void setBackground(int color [, int edgeColor [, int 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

public void setRoundedFrame([ int extColor [, int r1 [, int r2 [, int r3 [, int 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. -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. -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. -1 means it is the same as the radius of the top-left corner.

Return Value

None


BaseChart.setDropShadow

BaseChart.setDropShadow

Usage

public void setDropShadow([ int color [, int offsetX [, int offsetY [, int blurRadius ]]]])

Description

Adds a drop shadow to the chart.

The drop shadow effect is created using a single color representation of the non-transparent part of the chart, offsetted by an amount, and put under the chart. The drop shadow can be blurred to create a soft drop shadow effect.

Note that adding a drop shadow will increase the width and height of the chart image so as to accommodate the drop shadow.

Because the drop shadow is located exterior to the original chart, it uses an exterior background color different from the background color of the original chart. The exterior background color is by default white, and can be configured with BaseChart.setRoundedFrame.

Arguments

Argument | Default | Description
color | AAAAAA | The color of the drop shadow.
offsetX | 5 | The x offset of the drop shadow.
offsetY | 7fffffff | The y offset of the drop shadow. 7fffffff means it is the same as the x offset.
blurRadius | 5 | The blur radius of the drop shadow.

Return Value

None


BaseChart.setBorder

BaseChart.setBorder

Usage

public void setBorder(int 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

public void setWallpaper(String 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

public void setBgImage(String img [, int 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

public void setSearchPath(String path)

Description

Sets the file system 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, if a relative path name is used for an image file, ChartDirector will search for the image file using a ClassLoader (see BaseChart.setSearchPath2 for details), and also in the "current directory".

The setSearchPath method allows you to specify a search path instead of using the "current directory". Multiple directories are supported by separating them with the path separator (java.io.File.pathSeparator - ";" for Windows and ":" for Linux/UNIX).

If you are using ChartDirector in a web server, you may want to search for the images relative to the current servlet context. Please refer to BaseChart.setSearchPath3 for details.

If you are using ChartDirector in an applet environment, you may want to search for the images based on the "code base" or "document base" of the Applet. Please refer to BaseChart.setSearchPath4 for details.

Arguments

Argument | Default | Description
path | (Mandatory) | A list of directories, separated with the path separator (java.io.File.pathSeparator) of your operating system (";" for Windows, ":" for Linux/UNIX).

Return Value

None


BaseChart.setSearchPath2

BaseChart.setSearchPath2

Usage

public void setSearchPath2(ClassLoader loader[, String path])

Description

Sets the ClassLoader for loading images.

Please refer to BaseChart.setSearchPath for the various methods ChartDirector uses to search for images.

By default, ChartDirector will use a ClassLoader (java.lang.ClassLoader) to search for image files. A ClassLoader will search its class path, using the same method for locating a Java class. A ClassLoader can load the images even if they are inside a JAR file.

In some systems, there are multiple ClassLoaders with different class paths. An example is a JSP web server with multiple servlet contexts. The setSearchPath2 method allows you to specify the ClassLoader to use for loading the images. If you do not specify the ClassLoader to use, ChartDirector will use the ClassLoader that loads ChartDirector itself.

Note that a ClassLoader loads images as Java resources. The image path will be handled as a Java resource path, that is, the path needs to be delimited by "/", and there must be no leading "/".

The setSearchPath2 accepts an optional argument for specifying a search path for searching the image under the class path. Multiple directories are supported by separating them with semi-colons.

To disable searching using the ClassLoader, set the ClassLoader to null.

Arguments

Argument | Default | Description
loader | (Mandatory) | The ClassLoader used to load the resource.
path | null | The package path(s) to prepend to the image path. Multiple directories are supported by separating them with semi-colons.

Return Value

None


BaseChart.setSearchPath3

BaseChart.setSearchPath3

Usage

public void setSearchPath3(ServletContext context[, ServletRequest request[, String path ]])

Description

Search for image files using the ServletContext and ServletRequest.

Please refer to BaseChart.setSearchPath for the various methods ChartDirector uses to search for images.

With setSearchPath3, ChartDirector will use the "servlet context" (that is, the path to the web application) as the root of the image path. For example, if the web application is called "myWebApp", and the image path is "/mydir/imagefile.gif", ChartDirector will locate the image assuming it is a resource at:

http://aaa.bbb.ccc.ddd/myWebApp/mydir/imagefile.gif

If the image path is a relative path, it will be interpreted as relative to the current servlet request path.

The setSearchPath3 accepts an optional argument for specifying a search path for the image. Multiple directories are supported by separating them with semi-colons.

For example, a common practice for many web applications is to put all images files in an "/images" subdirectory. In these cases, you can set the search path to "/images".

Arguments

Argument | Default | Description
context | (Mandatory) | The ServletContext used to resolve absolute paths. This object is usually obtained by using "getServletConfig().getServletContext()" in the Servlet.
request | null | The ServletRequest used to resolve relative paths. In JSP, this is the predefined variable "request". In a servlet, this object is available as the parameter passed in from the doGet or doPost method. null means all paths (relative or absolute) will be resolved using the ServletContext.
path | null | The search path to use. Multiple directories are supported by separating them with semi-colons.

Return Value

None


BaseChart.setSearchPath4

BaseChart.setSearchPath4

Usage

public void setSearchPath4(URL path)

Description

Search for image files using a URL as the base path.

Please refer to BaseChart.setSearchPath for the various methods ChartDirector uses to search for images.

With setSearchPath4, ChartDirector will use the given URL as the base path to load images. This is commonly used in applet applications, in which the applet is running in client machines, but the images are located on server machines.

For example, the following code uses the document base of the applet as the base path for loading images.

c.setSearchPath(getDocumentBase());

Note that in using setSearchPath4, the image path is assumed to be a URL, and the base path is used to resolve the parts of the URL not specified in the image path. This is similar to the paths used in <IMG> tags in web pages.

Arguments

Argument | Default | Description
path | (Mandatory) | An URL acting as the base path for loading images.

Return Value

None


BaseChart.setTransparentColor

BaseChart.setTransparentColor

Usage

public void setTransparentColor(int c)

Description

Specifies a certain color to mean transparent when creating a raster 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

public void setAntiAlias([ boolean shapeAntiAlias [, int 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 | A true value enables anti-alias when drawing lines and shapes. A false 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

public TextBox addTitle(String text [, String font [, double fontSize [, int fontColor [, int bgColor [, int 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

public TextBox addTitle2(int alignment, String text [, String font [, double fontSize [, int fontColor [, int bgColor [, int 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

public LegendBox addLegend(int x, int y [, boolean vertical [, String font [, double 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 | A true value means the legend keys are laid out vertically (one line per entry). A false 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

public LegendBox addLegend2(int x, int y, int noOfCols [, String font [, double 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

public LegendBox 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

public LegendBox 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

public DrawArea 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

public TextBox addText(int x, int y, String text [, String font [, double fontSize [, int fontColor [, int alignment [, double angle [, boolean 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 pixel coordinate of the left of the text box.
y | (Mandatory) | The y pixel 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 | 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.addTable

BaseChart.addTable

Usage

public CDMLTable addTable(int x, int y, int alignment, int col, int row)

Description

Adds a CDML table to the chart.

Arguments

Argument | Default | Description
x | (Mandatory) | The x-coordinate of the reference point used to position the table.
y | (Mandatory) | The y-coordinate of the reference point used to position the table.
alignment | (Mandatory) | The alignment of the table with respect to the reference point. For example, a value of TopLeft means the reference point is the top- left corner of the table. See Alignment Specification for supported alignment types..
col | (Mandatory) | The number of columns in the table.
row | (Mandatory) | The number of rows in the table.

Return Value

A CDMLTable object representing the CDML table added.


BaseChart.addLine

BaseChart.addLine

Usage

public Line addLine(int x1, int y1, int x2, int y2 [, int color [, int lineWidth ]])

Description

Adds a line to the chart.

Arguments

Argument | Default | Description
x1 | (Mandatory) | The x pixel coordinate of the first endpoint of the line.
y1 | (Mandatory) | The y pixel coordinate of the first endpoint of the line.
x2 | (Mandatory) | The x pixel coordinate of the second endpoint of the line.
y2 | (Mandatory) | The y pixel 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

public void addExtraField(String[] 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

public void addExtraField2({double | java.util.Date}[] 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

public void setColor(int paletteEntry, int 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

public void setColors(int[] 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

public void setColors2(int paletteEntry, int[] 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

public int getColor(int 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.adjustBrightness

BaseChart.adjustBrightness

Usage

public int adjustBrightness(int c, double brightness)

Description

Creates a color that is a darkened or brightened version of the given color.

A brightness less than 1 means the color is darkened, while a brightness greater than 1 means the color is brightened. For example, a brightness of 0.5 means the color is half as bright as the original color. If the original color is red, the color will become dark red. Conversely, a brightness of 2 means the color is twice as bright as the original color. If the original color is red, the color will become light red.

Arguments

Argument | Default | Description
c | (Mandatory) | The given color.
brightness | (Mandatory) | A non-negative number represent the factor to darken or brighten the color.

Return Value

A 32-bit integer representing the darkened or brightened color.


BaseChart.halfColor

BaseChart.halfColor

Usage

public int halfColor(int 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

public int dashLineColor(int color [, int 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

public int patternColor(int[] colorArray, int height [, int startX, int 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

public int patternColor2(String filename [, int startX, int 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

public int linearGradientColor(int startX, int startY, int endX, int endY, int startColor, int endColor [, boolean 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

public int linearGradientColor2(int startX, int startY, int endX, int endY, int[] colorArray [, boolean 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

public int radialGradientColor(int cx, int cy, int rx, int ry, int startColor, int endColor [, boolean 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

public int radialGradientColor2(int cx, int cy, int rx, int ry, int[] colorArray [, boolean 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

public int gradientColor(int startX, int startY, int endX, int endY, int startColor, int 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

public int gradientColor2(int[] colorArray [, double angle [, double scale [, int startX, int 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

public void setDefaultFonts(String normal [, String bold [, String italic [, String 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

public void setFontTable(int index, String 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

public String formatValue({double | java.util.Date} value, String 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

A text string containing the formatted result.


BaseChart.setNumberFormat

BaseChart.setNumberFormat

Usage

public void setNumberFormat([ char thousandSeparator [, char decimalPointChar [, char 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

public void setMonthNames(String[] 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

public void setWeekDayNames(String[] 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

public void setAMPM(String am, String 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

public void layout()

Description

Perform auto-scaling of the axes (if any) and compute the positions of the various objects in the chart.

ChartDirector automatically lays out the chart when creating the chart output (eg. using BaseChart.makeSession, BaseChart.makeChart or BaseChart.makeChart2). There is usually no need to layout explicitly.

However, if you would like to draw custom objects whose positions depend on the axis scales or the position of other objects, you may call the layout method to auto-scaling the axes (for charts that have axes) and to fix the positions of chart objects before creating the chart output.

You should not modify the positions of existing chart objects or add more data to the chart after layout.

Note that there is a similar method BaseChart.layoutLegend that lays out the legend box only. For XYChart objects, there is a method XYChart.layoutAxes that lays out and auto-scales the axes only. They allow the legend box size, axis scale, and axis thickness to be known without fixing the positions of all chart objects.

Arguments

None

Return Value

None


BaseChart.makeImage

BaseChart.makeImage

Usage

public Image makeImage()

Description

Generates the chart as a java.awt.Image object.

Arguments

None

Return Value

A java.awt.Image object representing the chart image.


BaseChart.enableVectorOutput

BaseChart.enableVectorOutput

Usage

public void enableVectorOutput()

Description

Enables true vector graphics output.

By default, when creating the output image, ChartDirector draws directly onto an output buffer representing the bitmap of the image. For example, for a chart 800 x 600 pixels in size, the output buffer may represent a 800 x 600 bitmap. The output buffer size is unchanged no matter how many items are drawn onto it. Even if the output contains 1 million elements (eg. 1 million symbols), the size of the output buffer is still the same.

On the other hand, a true vector output is indefinitely scalable and can be considered as having infinite resolution. To produce a true vector output, it is necessary to remember the graphics operations for every element in the output buffer. The output buffer size is therefore proportional to the number of elements to draw.

This method tells ChartDirector that it needs to remember the graphics operations to prepare for true vector output. If true vector output is needed, this method should be called immediately after creating the BaseChart object.

If this method is not called, and a vector graphics output format is used (such as SVG), instead of a true vector output, ChartDirector will output a raster image using the vector graphics format. (Most vector graphics formats support embedded raster images.)

Arguments

None

Return Value

None


BaseChart.makeChart

BaseChart.makeChart

Usage

public boolean makeChart(String filename)

Description

Generates the chart image and save it into a file.

ChartDirector supports PNG, JPG, GIF, WBMP, BMP, SVG and SVGZ. The format used is selected based on file extension, which should be png, jpg, jpeg, gif, wbmp, wmp, bmp, svg or svgz.

Note: To output true vector graphics in SVG or SVGZ format, please ensure BaseChart.enableVectorOutput is called immediately after creating the BaseChart object. Otherwise the output will be a bitmap image embedded in SVG or SVGZ.

Arguments

Argument | Default | Description
filename | (Mandatory) | The name of the file to save the image.

Return Value

A true value indicates no error. A false value indicates the operation is unsuccessful.


BaseChart.makeChart2

BaseChart.makeChart2

Usage

public byte[] makeChart2(int 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.
SVG | 5 | The SVG format.
SVGZ | 6 | The compressed SVG format.

Note: To output true vector graphics in SVG or SVGZ format, please ensure BaseChart.enableVectorOutput is called immediately after creating the BaseChart object. Otherwise the output will be a bitmap image embedded in SVG or SVGZ.

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

public DrawArea 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(HttpServletRequest request, string name [, int imageFormat ])

Description

Generates the chart as an image and save it to a session variable.

The makeSession method is designed to support web applications in which the chart is generated in the script that outputs HTML.

This method requires session variables be enabled in the web server, which should be the default for JSP servers.

HTML cannot "contain" any image. It can only contain the URL of the images, typically in <IMG> tags. Other tags, such as <IFRAME>, <OBJECT> or <EMBED>, or the "background" property of CSS, etc, can also be used. The browser will use the URLs to load the images from separate HTTP connections.

In the followings, for conciseness, we will use <IMG> in the description. It should be noted that the description applies to other tags to load the chart image as well.

As HTML cannot contain any image, the script that outputs HTML cannot output the chart image. It needs to save the image in some place, and output an <IMG> tag with an URL for retrieving the saved image.

To save the chart image, a common method is to save it to the hard disk. The URL to load the image is then the URL of the image file. Please refer to BaseChart.makeTmpFile if you would like to consider this method.

The makeSession method saves images in session variables, avoiding creating image files on the hard disk. The makeSession method returns a URL query string, which can be used with a ChartDirector utility script "getchart.jsp" to load the image from session variables.

To avoid having to save the chart image at all, an alternative approach is to use the URL of a script in the <IMG>. The browser will then access the script to load the image. The script can generate the chart image and streamed directly to the browser.

Note that the chart is not generated by the script that outputs HTML, but by another script that handles the <IMG> tag.

A limitation of this method is that the charts cannot contain image maps. Image maps are HTML tags (<MAP> and <AREA> tags) and can only be outputted by the script that generates HTML. If image maps are used, the charts need to be generated in the script that outputs HTML.

In a typical application, the chart is created like:

String chart1URL = c.makeSession(request, "chart1");

The web page then includes an <IMG> tag as follows:

<img src='<%=response.encodeURL("getchart.jsp?"+chart1URL)%>'>

Note that the above assumes "getchart.jsp" is in the same directory as your script. If it is in a different directory, you would need to modify the path in the <IMG> tag. Also, the directory that contains "getchart.jsp" must be in the same web application (servlet context) as your script, otherwise "getchart.jsp" will be unable to access the session variables created by your script.

As an alternative to getimage.jsp, ChartDirector also has a GetSessionImage servlet that performs the same function. This is useful for servlet applications that do not use JSP.

For example, if you have mapped "*.chart" to GetSessionImage, you may use "getchart.chart" as the URL instead of "getchart.jsp". Please refer to the Installation section for details.

Note: The getimage.jsp may not work properly in some very old web servers. In this case, the getimage.jsp will automatically redirect itself to the GetSessionImage servlet. Therefore, it may be useful to install the GetSessionImage servlet even if you may not need it.

Note: To output true vector graphics in SVG or SVGZ format, please ensure BaseChart.enableVectorOutput is called immediately after creating the BaseChart object. Otherwise the output will be a bitmap image embedded in SVG or SVGZ.

Arguments

Argument | Default | Description
request | (Mandatory) | The HttpServletRequest object representing the current request.
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, WMP, SVG or SVGZ.

Return Value

A string representing the query parameters for retrieving the image using "getchart.jsp" or the GetSessionImage servlet.


BaseChart.makeTmpFile

BaseChart.makeTmpFile

Usage

public String makeTmpFile(String dirname [, int imageFormat [, int 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 files older than a certain life time (default 600 seconds) in that directory.

Note that makeTmpFile expects dirname be a file system path, not a URL path. For example, the directory "/tmp/tmpcharts" means a directory at the root of the hard disk, not the root of the web document directory. Also, a relative path like "tmpcharts" or "../tmpcharts" is relative to the "current working directory" of the file system, which may not be the same as the "current script directory". It depends on the brand and configuration of the web server. To avoid uncertainties, it is not suggested to use relative paths.

To use a directory that is under the web document directory (so that the browser can load the image), please use the javax.servlet.ServletContext.getRealPath method to translate the URL path to a full 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 directory 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. Also, please ensure javax.servlet.ServletContext.getRealPath has been used to map URL paths to file system paths.

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.

Note: To output true vector graphics in SVG or SVGZ format, please ensure BaseChart.enableVectorOutput is called immediately after creating the BaseChart object. Otherwise the output will be a bitmap image embedded in SVG or SVGZ.

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, WMP, SVG or SVGZ.
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.initDynamicLayer

BaseChart.initDynamicLayer

Usage

public DrawArea initDynamicLayer()

Description

Initializes a dynamic layer for drawing text and shapes.

This method clears the existing dynamic layer, or creates a new one if there is no existing dynamic layer. This method returned a DrawArea object that can be used to draw on the dynamic layer. The dynamic layer can later be removed using BaseChart.removeDynamicLayer.

The design of the dynamic layer is for drawing small, rapidly updatable contents for desktop applications. For example, the dynamic layer can be used to implement a cross-hair mouse cursor, with text showing the location of the mouse cursor. To do this, in the mouse move event handler, BaseChart.initDynamicLayer can be used to create or clear the dynamic layer. The returned DrawArea object can then be used to draw the cross hair cursor (as two straight lines) and the text. When the mouse cursor leaves the chart, BaseChart.removeDynamicLayer can be used in the mouse out event handler to remove the cross-hair cursor and the text.

Note that as long as the dynamic layer is not removed with BaseChart.removeDynamicLayer, only the returned DrawArea object should be used to draw things on the dynamic layer. No other objects should be used to draw on the chart.

Arguments

None

Return Value

A DrawArea object that can be used to add text and shapes to the dynamic layer.


BaseChart.removeDynamicLayer

BaseChart.removeDynamicLayer

Usage

public void removeDynamicLayer()

Description

Removes the dynamic layer if any.

Arguments

None

Return Value

None


BaseChart.getHTMLImageMap

BaseChart.getHTMLImageMap

Usage

public String getHTMLImageMap(String url [, String queryFormat [, String extraAttr [, int offsetX, int 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.jsp?x=0&xLabel=Mon&dataSet=0&dataSetName=Revenue&value=100">
<area shape="rect" coords="74,219,103,119" href="myurl.jsp?x=1&xLabel=Tue&dataSet=0&dataSetName=Revenue&value=125">
<area shape="rect" coords="114,219,143,22" href="myurl.jsp?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 "x={x}&label={label}&name={name}&value={value}"
Pyramid chart | "index={index}&label={label}&value={value}&percent={percent}"

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 an 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.getJsChartModel

BaseChart.getJsChartModel

Usage

public String getJsChartModel([ String options ])

Description

Gets the Javascript Chart Model for passing to WebChartViewer.setChartModel for the purpose of supporting track cursors in a web application.

To support track cursors in a web application, the browser would need know certain details of the chart, its data, chart type and axis configuration. The Javascript Chart Model is a textual representation of those information. The WebChartViewer will send it to the browser to be used by the browser side Javascript ChartViewer (JsChartViewer).

The format of the Javascript Chart Model is not published.

Arguments

Argument | Default | Description
options | "" | This parameter is reserved for future use. Please do not use it.

Return Value

A text string representing the Javascript Chart Model.


BaseChart.getChartMetrics

BaseChart.getChartMetrics

Usage

public String getChartMetrics()

Description

Gets the chart metrics for passing to WebChartViewer.setChartMetrics to support view ports for web applications.

The format of the chart metrics is not published.

Arguments

None

Return Value

A text string representing the chart metrics.


ThreeDChart

ThreeDChart

The ThreeDChart class is an abstract class containing methods that are common to all true 3D chart types. ThreeDChart is a subclass of BaseChart.

Method | Inherited | Description
setPlotRegion | (Self) | Sets the position of the plot region.
setViewAngle | (Self) | Sets the 3D view angles.
setPerspective | (Self) | Sets the strength of the perspective effect.
xAxis | (Self) | Retrieves the x-axis of the ThreeDChart object.
yAxis | (Self) | Retrieves the y-axis of the ThreeDChart object.
zAxis | (Self) | Retrieves the z-axis of the ThreeDChart object.
setColorAxis | (Self) | Sets the position, length and orientation of the color axis (color legend).
colorAxis | (Self) | Gets the ColorAxis object representing the color axis (color legend).
setWallVisibility | (Self) | Shows or hides the plot region walls.
setWallColor | (Self) | Sets the color of the plot region walls.
setWallThickness | (Self) | Sets the thickness of the plot region walls.
setWallGrid | (Self) | Sets the grid line colors on plot region walls.
setZAxisPos | (Self) | Sets the position of the z-axis.
setSize | BaseChart | Sets the size of the chart, exclusive of the drop shadow (if any).
getWidth | BaseChart | Gets the width of the chart.
getHeight | BaseChart | Gets the height of the chart.
getAbsOffsetX | BaseChart | Gets the x offset of the chart relative to the outermost MultiChart container.
getAbsOffsetY | BaseChart | Gets the y offset of the chart relative to the outermost MultiChart container.
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.
setDropShadow | BaseChart | Adds a drop shadow to the chart.
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 file system search path for loading image files.
setSearchPath2 | BaseChart | Sets the ClassLoader for loading images.
setSearchPath3 | BaseChart | Search for image files using the ServletContext and ServletRequest.
setSearchPath4 | BaseChart | Search for image files using a URL as the base path.
setTransparentColor | BaseChart | Specifies a certain color to mean transparent when creating a raster 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.
addTable | BaseChart | Adds a CDML table 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.
adjustBrightness | BaseChart | Creates a color that is a darkened or brightened version of the given color.
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 axes (if any) and compute the positions of the various objects in the chart.
makeImage | BaseChart | Generates the chart as a java.awt.Image object.
enableVectorOutput | BaseChart | Enables true vector graphics output.
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.
initDynamicLayer | BaseChart | Initializes a dynamic layer for drawing text and shapes.
removeDynamicLayer | BaseChart | Removes the dynamic layer if any.
getHTMLImageMap | BaseChart | Generates an HTML image map for the chart.
getJsChartModel | BaseChart | Gets the Javascript Chart Model for passing to WebChartViewer.setChartModel for the purpose of supporting track cursors in a web application.
getChartMetrics | BaseChart | Gets the chart metrics for passing to WebChartViewer.setChartMetrics to support view ports for web applications.


ThreeDChart.setPlotRegion

ThreeDChart.setPlotRegion

Usage

public void setPlotRegion(int cx, int cy, int xWidth, int yDepth, int zHeight)

Description

Sets the position of the plot region.

The plot region is a 3D box, with x, y, and z axes along its border, using a right-hand cartesian coordinate system.

To create the chart image, you may imagine a camera taking a photograph of the box. The photograph can be taken at different angles, configurable with ThreeDChart.setViewAngle. The position of the plot region in the photograph is such that the center of the plot region is at a given point (cx, cy) on the image.

Arguments

Argument | Default | Description
cx | (Mandatory) | The x pixel coordinate of the point on the image at which the center of the plot region is located.
cy | (Mandatory) | The y pixel coordinate of the point on the image at which the center of the plot region is located.
xWidth | (Mandatory) | The length of the x-dimension of the plot region in pixels.
yDepth | (Mandatory) | The length of the y-dimension of the plot region in pixels.
zHeight | (Mandatory) | The length of the z-dimension of the plot region in pixels.

Return Value

None


ThreeDChart.setViewAngle

ThreeDChart.setViewAngle

Usage

public void setViewAngle(double elevation [, double rotation [, double twist ]])

Description

Sets the 3D view angles.

ChartDirector uses elevation, rotation and twist angles to specify the 3D view angles.

To explain the meaning of the angles, imagine the object being viewed is put at the center of a hollow sphere, and a camera (the view point) is put at the surface of the sphere, directed inwards to the center to look at the object.

The elevation angle refers to the "latitude" of the camera. An elevation angle of 0 degrees means the camera is at the "equator" pointing to the object from the side. An elevation angle of 90 degrees means the camera is at the "north pole" pointing down to the object. An angle elevation of -90 degrees means the camera is at the "south pole", pointing up to the object.

The rotation angle refers to the "longitude" of the camera. If the elevation is 0 degrees, and the rotation angle varies from 0 to 360 degrees, the camera will move around the "equator" in the easterly direction (counter-clockwise when viewed from the north pole).

The twist angle is for rotating the camera itself while still pointing to the object. For example, a twist angle of 90 degrees means you are holder the camera "vertically" instead of "horizontally". The rotation is clockwise from the view point of the person holding the camera.

Note that from the view point of the camera, the object will appear to be rotating in the opposite direction. For example, as the rotation angle rotates the camera counter-clockwise along the "equator", the object will appear to be rotating clockwise on the screen.

Note: The twist angle is not supported in the current version of ChartDirector. It should always be 0, and should be considered as a reserved argument for future use.

Arguments

Argument | Default | Description
elevation | (Mandatory) | The elevation angle in degrees.
rotation | 0 | The rotation angle in degrees.
twist | 0 | The twist angle in degrees.

Return Value

None


ThreeDChart.setPerspective

ThreeDChart.setPerspective

Usage

public void setPerspective(double perspective)

Description

Sets the strength of the perspective effect.

When taking the photograph of a scene, things closer to the camera are larger in the photograph, while things farther from the camera are smaller. For example, two trees of exactly the same height but at different distances from the camera will have different heights as measured in the photograph. This is known as the perspective effect.

This method configures the strength of the perspective effect for a ThreeDChart object. The nearer part of the plot region will be magnified, while the farther part will be reduced. The average size of the plot region will be approximately unchanged.

Arguments

Argument | Default | Description
perspective | (Mandatory) | The strength of the perspective effect. It approximately represents the maximum percentage magnification of the plot region, which is the same as the maximum percentage reduction. A value of 0 means no perspective effect. This value is usually between 0 to 100. If this method is never called, the default is 12.

Return Value

None


ThreeDChart.xAxis

ThreeDChart.xAxis

Usage

public Axis xAxis()

Description

Retrieves the x-axis of the ThreeDChart object.

Arguments

None

Return Value

The Axis object representing the x-axis of the ThreeDChart object.


ThreeDChart.yAxis

ThreeDChart.yAxis

Usage

public Axis yAxis()

Description

Retrieves the y-axis of the ThreeDChart object.

Arguments

None

Return Value

The Axis object representing the y-axis of the ThreeDChart object.


ThreeDChart.zAxis

ThreeDChart.zAxis

Usage

public Axis zAxis()

Description

Retrieves the z-axis of the ThreeDChart object.

Arguments

None

Return Value

The Axis object representing the z-axis of the ThreeDChart object.


ThreeDChart.setColorAxis

ThreeDChart.setColorAxis

Usage

public ColorAxis setColorAxis(int x, int y, int alignment, int length, int orientation)

Description

Sets the position, length and orientation of the color axis (color legend).

Arguments

Argument | Default | Description
x | (Mandatory) | The x-coordinate of the reference point used to position the color axis.
y | (Mandatory) | The y-coordinate of the reference point used to position the color axis.
alignment | (Mandatory) | The alignment of the color axis with respect to the reference point. For example, a value of TopLeft means the reference point is the top- left corner of the color axis. See Alignment Specification for supported alignment types..
length | (Mandatory) | The length of the color axis in pixels.
orientation | (Mandatory) | The orientation of the color axis. A value of Top/Bottom means the axis is horizontal, and the axis labels are at top/bottom side of the axis. A value of Left/Right means the axis is vertical, and the axis labels are at the left/right side of the axis.

Return Value

None


ThreeDChart.colorAxis

ThreeDChart.colorAxis

Usage

public ColorAxis colorAxis()

Description

Gets the ColorAxis object representing the color axis (color legend).

Arguments

None

Return Value

The ColorAxis object representing the color axis.


ThreeDChart.setWallVisibility

ThreeDChart.setWallVisibility

Usage

public void setWallVisibility(boolean xyVisible, boolean yzVisible, boolean zxVisible)

Description

Shows or hides the plot region walls.

By default, all walls are visible. This method can be used to hide some or all of the walls.

Arguments

Argument | Default | Description
xyVisible | (Mandatory) | A true value means the xy wall is visible. A false value means the xy wall is hidden.
yzVisible | (Mandatory) | A true value means the yz wall is visible. A false value means the yz wall is hidden.
zxVisible | (Mandatory) | A true value means the zx wall is visible. A false value means the zx wall is hidden.

Return Value

None


ThreeDChart.setWallColor

ThreeDChart.setWallColor

Usage

public void setWallColor(int xyColor [, int yzColor [, int zxColor [, int borderColor ]]])

Description

Sets the color of the plot region walls.

By default, the plot region walls are light grey (eeeeee) in color, with a grey (888888) border . This method can be used to modify the colors.

Arguments

Argument | Default | Description
xyColor | (Mandatory) | The color of the xy wall.
yzColor | -1 | The color of the yz wall. -1 means it is the same as xyColor.
zxColor | -1 | The color of the zx wall. -1 means it is the same as xyColor.
borderColor | -1 | The color of the wall border. -1 means to keep the existing value unchanged.

Return Value

None


ThreeDChart.setWallThickness

ThreeDChart.setWallThickness

Usage

public void setWallThickness(int xyThickness [, int yzThickness [, int zxThickness ]])

Description

Sets the thickness of the plot region walls.

By default, the plot region walls are 10 pixels thick. This method can be used to modify the thickness.

Arguments

Argument | Default | Description
xyThickness | (Mandatory) | The thickness of the xy wall in pixels.
yzThickness | -1 | The thickness of the yz wall in pixels. -1 means it is the same as xyThickness.
zxThickness | -1 | The thickness of the zx wall in pixels. -1 means it is the same as xyThickness.

Return Value

None


ThreeDChart.setWallGrid

ThreeDChart.setWallGrid

Usage

public void setWallGrid(int majorXGridColor [, int majorYGridColor [, int majorZGridColor [, int minorXGridColor [, int minorYGridColor [, int minorZGridColor ]]]]])

Description

Sets the grid line colors on plot region walls.

The grid lines on the walls are associated with the ticks on the x, y and z axes. Major ticks associate with major grid lines. Minor ticks associate with minor grid lines. By default, the major grid lines are light grey (cccccc), and the minor grid lines are lighter grey (dddddd). This method can be used to modify the grid line colors.

Arguments

Argument | Default | Description
majorXGridColor | (Mandatory) | The color of the major x-axis grid lines on the walls.
majorYGridColor | -1 | The color of the major y-axis grid lines on the walls. -1 means it is the same as the majorXGridColor.
majorZGridColor | -1 | The color of the major z-axis grid lines on the walls. -1 means it is the same as the majorXGridColor.
minorXGridColor | -1 | The color of the minor x-axis grid lines on the walls. -1 means it is the same as the majorXGridColor.
minorYGridColor | -1 | The color of the minor y-axis grid lines on the walls. -1 means it is the same as the majorYGridColor.
minorZGridColor | -1 | The color of the minor z-axis grid lines on the walls. -1 means it is the same as the majorZGridColor.

Return Value

None


ThreeDChart.setZAxisPos

ThreeDChart.setZAxisPos

Usage

public void setZAxisPos(int pos)

Description

Sets the position of the z-axis.

In a ThreeDChart object, the z-axis can be drawn either on the left side or the right side. By default, ChartDirector will draw the z-axis on the side that is nearer to the viewer.

This method can be used to specify which side the z-axis should be drawn.

Arguments

Argument | Default | Description
pos | (Mandatory) | The position of the z-axis, which must be either Left or Right.

Return Value

None


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.
getChart | (Self) | Gets the specified chart in the MultiChart.
getChartCount | (Self) | Gets the number of charts in the MultiChart.
setMainChart | (Self) | Sets the chart that receives view port mouse actions (for zooming and scrolling support).
setSize | BaseChart | Sets the size of the chart, exclusive of the drop shadow (if any).
getWidth | BaseChart | Gets the width of the chart.
getHeight | BaseChart | Gets the height of the chart.
getAbsOffsetX | BaseChart | Gets the x offset of the chart relative to the outermost MultiChart container.
getAbsOffsetY | BaseChart | Gets the y offset of the chart relative to the outermost MultiChart container.
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.
setDropShadow | BaseChart | Adds a drop shadow to the chart.
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 file system search path for loading image files.
setSearchPath2 | BaseChart | Sets the ClassLoader for loading images.
setSearchPath3 | BaseChart | Search for image files using the ServletContext and ServletRequest.
setSearchPath4 | BaseChart | Search for image files using a URL as the base path.
setTransparentColor | BaseChart | Specifies a certain color to mean transparent when creating a raster 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.
addTable | BaseChart | Adds a CDML table 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.
adjustBrightness | BaseChart | Creates a color that is a darkened or brightened version of the given color.
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 axes (if any) and compute the positions of the various objects in the chart.
makeImage | BaseChart | Generates the chart as a java.awt.Image object.
enableVectorOutput | BaseChart | Enables true vector graphics output.
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.
initDynamicLayer | BaseChart | Initializes a dynamic layer for drawing text and shapes.
removeDynamicLayer | BaseChart | Removes the dynamic layer if any.
getHTMLImageMap | BaseChart | Generates an HTML image map for the chart.
getJsChartModel | BaseChart | Gets the Javascript Chart Model for passing to WebChartViewer.setChartModel for the purpose of supporting track cursors in a web application.
getChartMetrics | BaseChart | Gets the chart metrics for passing to WebChartViewer.setChartMetrics to support view ports for web applications.


MultiChart.MultiChart

MultiChart.MultiChart

Usage

public MultiChart(int width, int height [, int bgColor [, int edgeColor [, int 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.


MultiChart.addChart

MultiChart.addChart

Usage

public void addChart(int x, int y, BaseChart 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.getChart

MultiChart.getChart

Usage

public BaseChart getChart([ int i ])

Description

Gets the specified chart in the MultiChart.

Arguments

Argument | Default | Description
i | 0 | The index of the chart. The index of the first chart set added to the MultiChart is 0. The index of the Nth data set added to the MultiChart is N - 1.

Return Value

The specified BaseChart object.


MultiChart.getChartCount

MultiChart.getChartCount

Usage

public int getChartCount()

Description

Gets the number of charts in the MultiChart.

Arguments

None

Return Value

The number of charts in the MultiChart.


MultiChart.setMainChart

MultiChart.setMainChart

Usage

public void setMainChart(BaseChart 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.
setLineStyleKey | (Self) | Determines whether to always use "line style legend keys" or not.
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.
setPos | Box | Sets the coordinates of the reference point of the box, which by default is 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.
getLeftX | Box | Gets the left x pixel coordinate of the box.
getTopY | Box | Gets the top y pixel coordinate of the box.
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

public void addKey(String text, int color [, int lineWidth [, DrawArea 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

public void addKey2(int pos, String text, int color [, int lineWidth [, DrawArea 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

public void setCols(int 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

public void setReverse([ boolean 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 | A true value means the legend entries are ordered based on descending legend entry priority number. false value means the legend entries are ordered based on ascending legend entry priority number.

Return Value

None


LegendBox.setText

LegendBox.setText

Usage

public void setText(String 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

public void setKeySize(int width [, int height [, int 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

public void setKeySpacing(int keySpacing [, int 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

public void setKeyBorder(int edgeColor [, int 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 Chart.glassEffect, Chart.softLighting and Chart.cylinderEffect effects.

Return Value

None


LegendBox.setLineStyleKey

LegendBox.setLineStyleKey

Usage

public void setLineStyleKey([ boolean b ])

Description

Determines whether to always use "line style legend keys" or not.

By default, ChartDirector will use a small colored square box as the legend key icon. This allows people to determine the colors for the data representations.

In some cases, colors alone cannot distinguish the data representations. For example, in a line chart with multiple lines, it is possible all lines are of the same color, and are distinguished by line styles (solid, dash, dotted, etc), etc), or the lines may be distinguished by data symbols (small circles, squares, etc) on the lines.

For charts with non-solid lines (eg. dash, dotted, etc) or lines with data symbols, ChartDirector will use "line style legend keys" for the lines. A line style legend key consist a of line with an optional data symbol, which reflects the line style and data symbol representing the data series.

This method can be used to force ChartDirector to always use the "line style legend keys".

Arguments

Argument | Default | Description
b | true | A true value means to always use "line style legend keys". A false value means to automatically determined if "line style legend keys" should be used.

Return Value

None


LegendBox.getImageCoor2

LegendBox.getImageCoor2

Usage

public String getImageCoor2(int dataItem [, int offsetX, int 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

public String getHTMLImageMap(String url [, String queryFormat [, String extraAttr [, int offsetX, int 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.
setSectorStyle | (Self) | Sets the sector shading style, edge color and edge width.
setData | (Self) | Sets the data used to draw the pie chart.
getSector | (Self) | Retrieves the Sector object representing a single sector in the pie chart.
setSize | BaseChart | Sets the size of the chart, exclusive of the drop shadow (if any).
getWidth | BaseChart | Gets the width of the chart.
getHeight | BaseChart | Gets the height of the chart.
getAbsOffsetX | BaseChart | Gets the x offset of the chart relative to the outermost MultiChart container.
getAbsOffsetY | BaseChart | Gets the y offset of the chart relative to the outermost MultiChart container.
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.
setDropShadow | BaseChart | Adds a drop shadow to the chart.
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 file system search path for loading image files.
setSearchPath2 | BaseChart | Sets the ClassLoader for loading images.
setSearchPath3 | BaseChart | Search for image files using the ServletContext and ServletRequest.
setSearchPath4 | BaseChart | Search for image files using a URL as the base path.
setTransparentColor | BaseChart | Specifies a certain color to mean transparent when creating a raster 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.
addTable | BaseChart | Adds a CDML table 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.
adjustBrightness | BaseChart | Creates a color that is a darkened or brightened version of the given color.
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 axes (if any) and compute the positions of the various objects in the chart.
makeImage | BaseChart | Generates the chart as a java.awt.Image object.
enableVectorOutput | BaseChart | Enables true vector graphics output.
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.
initDynamicLayer | BaseChart | Initializes a dynamic layer for drawing text and shapes.
removeDynamicLayer | BaseChart | Removes the dynamic layer if any.
getHTMLImageMap | BaseChart | Generates an HTML image map for the chart.
getJsChartModel | BaseChart | Gets the Javascript Chart Model for passing to WebChartViewer.setChartModel for the purpose of supporting track cursors in a web application.
getChartMetrics | BaseChart | Gets the chart metrics for passing to WebChartViewer.setChartMetrics to support view ports for web applications.


PieChart.PieChart

PieChart.PieChart

Usage

public PieChart(int width, int height [, int bgColor [, int edgeColor [, int 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.


PieChart.setPieSize

PieChart.setPieSize

Usage

public void setPieSize(int x, int y, int 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

public void setDonutSize(int x, int y, int r, int 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

public void set3D([ int depth [, double angle [, boolean 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 | Flag to indicate whether the pie is in standard 3D or shadow 3D mode. A true value means shadow 3D mode. A false value means standard 3D mode.

Return Value

None


PieChart.set3D2

PieChart.set3D2

Usage

public void set3D2(double[] depths [, double angle [, boolean 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 | Flag to indicate whether the pie is in standard 3D or shadow 3D mode. A true value means shadow 3D mode. A false value means standard 3D mode.

Return Value

None


PieChart.setStartAngle

PieChart.setStartAngle

Usage

public void setStartAngle(double startAngle [, boolean 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 | Flag to control the layout direction of the sectors. A true value means clockwise. A false value means anti-clockwise.

Return Value

None


PieChart.setExplode

PieChart.setExplode

Usage

public void setExplode([ int sectorNo [, int distance ]])

Description

Explode a sector from the pie.

Arguments

Argument | Default | Description
sectorNo | -1 | 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). -1 means to explode all sectors.
distance | -1 | The explosion distance in pixels. -1 means the distance is automatically determined.

Return Value

None


PieChart.setExplodeGroup

PieChart.setExplodeGroup

Usage

public void setExplodeGroup(int startSector, int endSector [, int 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

public TextBox setLabelStyle([ String font [, double fontSize [, int 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 sector labels. This may be used to fine-tune the appearance of the sector labels.


PieChart.setLabelFormat

PieChart.setLabelFormat

Usage

public void setLabelFormat(String 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

public void setLabelLayout(int layoutMethod [, int pos [, int topBound [, int 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

public void setLabelPos(int pos [, int 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

public void setJoinLine(int joinLineColor [, int 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

public void setLineColor(int edgeColor [, int 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.setSectorStyle

PieChart.setSectorStyle

Usage

public void setSectorStyle(int shadingMethod [, int edgeColor [, int edgeWidth ]])

Description

Sets the sector shading style, edge color and edge width.

This method affects all sectors. To set the sector shading style, edge color and edge width for one particular sector, use Sector.setStyle.

ChartDirector supports various shading effects, which are best illustrated using examples.

Example | Description
2D Pie Shading | Illustrates various shading effects for 2D pies.
3D Pie Shading | Illustrates various shading effects for 3D pies.
2D Donut Shading | Illustrates various shading effects for 2D donuts.
3D Donut Shading | Illustrates various shading effects for 3D donuts.

The followings are textual descriptions of the shading effects.

Constant | Value | Description
DefaultShading | 0 | This is the default shading method. The top surfaces are shaded with flat colors. For 3D sectors, the cylindrical surfaces are shaded with cylindrical lighting effects.
FlatShading | 1 | All surfaces are shaded with flat colors.
LocalGradientShading | 2 | The top surfaces are shaded with linear gradient colors. For each sector, the gradient is from the bottom of the sector bounding box to the top of the sector bounding box, with the bottom side brighter and the top side darker. For 3D sectors, the cylindrical surfaces are shaded with cylindrical lighting effects.
GlobalGradientShading | 3 | The top surfaces are shaded with linear gradient colors. The gradient is from the bottom the pie bounding box to the top of the pie bounding box, with the bottom side brighter and the top side darker. For 3D sectors, the cylindrical surfaces are shaded with cylindrical lighting effects.
ConcaveShading | 4 | The top surfaces are shaded with a special effect so that they look concave, with the pie center appears to be depressed relative to the perimeter. For 3D sectors, the cylindrical surfaces are shaded with cylindrical lighting effects.
RoundedEdgeShading | 6 | The top surfaces are shaded with a special effect so that the pie looks raised with a rounded raised edge at the perimeter.
RadialShading | 7 | The top surfaces are shaded with radial gradient colors, with the pie center brighter and the perimeter darker. For 3D sectors, the cylindrical surfaces are shaded with cylindrical lighting effects.
RingShading | 8 | This effect is intended to be used with 2D donut charts only. The top surfaces are shaded with a special effect so that a 2D donut will look like a torus.

Arguments

Argument | Default | Description
shadingMethod | (Mandatory) | The sector shading style to use, which must be one of the constants in the table above. -1 means to keep the existing value unchanged.
edgeColor | -1 | The edge color of the sectors. -1 means to keep the existing value unchanged.
edgeWidth | -1 | The edge width of the sectors. -1 means to keep the existing value unchanged.

Return Value

None


PieChart.setData

PieChart.setData

Usage

public void setData(double[] data [, String[] 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.getSector

PieChart.getSector

Usage

public Sector getSector(int sectorNo)

Description

Retrieves the Sector object representing a single sector in the pie chart.

You must call PieChart.setData to create the sectors first before calling this method.

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.getSector.

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.
setStyle | (Self) | Sets the sector shading style, edge color and edge width.
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

public void setExplode([ int 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

public TextBox setLabelStyle([ String font [, double fontSize [, int 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 sector label. This may be used to fine-tune the appearance of the sector label.


Sector.setLabelFormat

Sector.setLabelFormat

Usage

public void setLabelFormat(String 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

public void setLabelLayout(int layoutMethod [, int 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

public void setLabelPos(int pos [, int 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

public void setJoinLine(int joinLineColor [, int 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

public void setColor(int color [, int edgeColor [, int 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.setStyle

Sector.setStyle

Usage

public void setStyle(int shadingMethod [, int edgeColor [, int edgeWidth ]])

Description

Sets the sector shading style, edge color and edge width.

This method is the same as PieChart.setSectorStyle, except it only affects one sector. Please refer to PieChart.setSectorStyle for the detail explanation of this method.

Arguments

Argument | Default | Description
shadingMethod | (Mandatory) | The sector shading style to use. -1 means to keep the existing value unchanged.
edgeColor | -1 | The edge color of the sector. -1 means to keep the existing value unchanged.
edgeWidth | -1 | The edge width of the sector. -1 means to keep the existing value unchanged.

Return Value

None


Sector.getImageCoor

Sector.getImageCoor

Usage

public String getImageCoor([ int offsetX, int 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

public String getLabelCoor([ int offsetX, int 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 the 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 the primary x-axis of the XYChart.
xAxis2 | (Self) | Retrieves the Axis object representing the 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.
getPlotArea | (Self) | Gets the PlotArea object representing the plot area.
packPlotArea | (Self) | Adjusts the plot area size and position to fit the plot area and the axis labels in a bounding box.
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.
addContourLayer | (Self) | Adds a contour layer to the XYChart, and specify the data sets to use for drawing the layer.
getLayer | (Self) | Gets a Layer object based on the order in which it is being added to the chart.
getLayerByZ | (Self) | Gets a Layer object based on the order in which it is being drawn.
getLayerCount | (Self) | Gets the number of layers in the chart.
layoutAxes | (Self) | Performs axis auto-scaling and sets the axis positions and lengths.
getXCoor | (Self) | Gets the x pixel coordinate given the x data value.
getYCoor | (Self) | Gets the y pixel coordinate given the y data value.
getXValue | (Self) | Gets the x data value given the x pixel coordinate.
getYValue | (Self) | Gets the y data value given the y pixel coordinate.
getNearestXValue | (Self) | Gets the x data value that is nearest to the specified x pixel coordinate.
xZoneColor | (Self) | Creates an x-zone color. An 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, exclusive of the drop shadow (if any).
getWidth | BaseChart | Gets the width of the chart.
getHeight | BaseChart | Gets the height of the chart.
getAbsOffsetX | BaseChart | Gets the x offset of the chart relative to the outermost MultiChart container.
getAbsOffsetY | BaseChart | Gets the y offset of the chart relative to the outermost MultiChart container.
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.
setDropShadow | BaseChart | Adds a drop shadow to the chart.
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 file system search path for loading image files.
setSearchPath2 | BaseChart | Sets the ClassLoader for loading images.
setSearchPath3 | BaseChart | Search for image files using the ServletContext and ServletRequest.
setSearchPath4 | BaseChart | Search for image files using a URL as the base path.
setTransparentColor | BaseChart | Specifies a certain color to mean transparent when creating a raster 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.
addTable | BaseChart | Adds a CDML table 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.
adjustBrightness | BaseChart | Creates a color that is a darkened or brightened version of the given color.
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 axes (if any) and compute the positions of the various objects in the chart.
makeImage | BaseChart | Generates the chart as a java.awt.Image object.
enableVectorOutput | BaseChart | Enables true vector graphics output.
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.
initDynamicLayer | BaseChart | Initializes a dynamic layer for drawing text and shapes.
removeDynamicLayer | BaseChart | Removes the dynamic layer if any.
getHTMLImageMap | BaseChart | Generates an HTML image map for the chart.
getJsChartModel | BaseChart | Gets the Javascript Chart Model for passing to WebChartViewer.setChartModel for the purpose of supporting track cursors in a web application.
getChartMetrics | BaseChart | Gets the chart metrics for passing to WebChartViewer.setChartMetrics to support view ports for web applications.


XYChart.XYChart

XYChart.XYChart

Usage

public XYChart(int width, int height [, int bgColor [, int edgeColor [, int 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.


XYChart.yAxis

XYChart.yAxis

Usage

public Axis 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

public Axis yAxis2()

Description

Retrieves the Axis object representing the 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

public void syncYAxis([ double slope [, double 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

public void setYAxisOnRight([ boolean 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 | A true value means to interchange the positions of the primary and secondary y-axes. A false value means using the default positions for the primary and secondary y-axes.

Return Value

None


XYChart.xAxis

XYChart.xAxis

Usage

public Axis xAxis()

Description

Retrieves the Axis object representing the 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

public Axis xAxis2()

Description

Retrieves the Axis object representing the 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

public void setXAxisOnTop([ boolean 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 | A true value means to interchange the positions of the primary and secondary x-axes. A false value means using the default positions for the primary and secondary x-axes.

Return Value

None


XYChart.setAxisAtOrigin

XYChart.setAxisAtOrigin

Usage

public void setAxisAtOrigin([ int originMode [, int 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

public Axis addAxis(int align, int 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

An Axis object representing the new axis added.


XYChart.swapXY

XYChart.swapXY

Usage

public void swapXY([ boolean 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 | A true value means the x and y axes will be swapped. A false value means the x and y axes not be swapped.

Return Value

None


XYChart.setPlotArea

XYChart.setPlotArea

Usage

public PlotArea setPlotArea(int x, int y, int width, int height [, int bgColor [, int altBgColor [, int edgeColor [, int hGridColor [, int 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

The PlotArea object representing the plot area.


XYChart.getPlotArea

XYChart.getPlotArea

Usage

public PlotArea getPlotArea()

Description

Gets the PlotArea object representing the plot area.

Arguments

None

Return Value

The PlotArea object representing the plot area.


XYChart.packPlotArea

XYChart.packPlotArea

Usage

public void packPlotArea(int leftX, int topY, int rightX, int bottomY [, int minWidth [, int minHeight ]])

Description

Adjusts the plot area size and position to fit the plot area and the axis labels in a bounding box.

In some charts, the axis labels may vary widely and can be very short or very long. It may be difficult to determine to plot area position and size so as to reserve reasonable and sufficient space for the axis labels.

This method adjusts the size and position of the plot area, so that the plot area, together with the axis labels can fit within a given bounding box.

Note that this method only adjusts for the thickness of the primary and secondary axes, and assumes they are at the border of the plot area. For other axes, you may use Axis.getThickness to get their thickness and adjust the plot area size and position accordingly.

For this method to determine the thickness of the axes, it needs to auto-scale the axes to determine the axis labels. That means all the data should be entered to the chart before calling this method.

Furthermore, the labels generated by auto-scaling depend on the number of labels that can fit on the axis, which in turn depends on the plot area size. So even the final plot area size is determined by this method, the XYChart.setPlotArea must still be used to set a reasonable initial plot area size.

To adjust only the plot area width and horizontal position, and leave the height and vertical position unchanged, simply use a bounding box with zero height (eg. set both topY and bottomY to 0). Similarly, to adjust only the height and vertical position, use a bounding box with zero width.

In some extreme cases, the axis labels may be so long that the plot area needs to adjust to an unreasonably small size, or even zero in size. For example, the axis labels may be names entered by the user, and the user may enter a name thousands of characters long. These extreme cases should be avoided by checking and limiting the length of the labels before passing the labels to ChartDirector. This method also has a safeguard for these unreasonable labels by ensuring the plot area will not shrink below a given minimum size.

Arguments

Argument | Default | Description
leftX | (Mandatory) | The left x coordinate of the bounding box.
topY | (Mandatory) | The top y coordinate of the bounding box.
rightX | (Mandatory) | The right x coordinate of the bounding box.
bottomY | (Mandatory) | The bottom y coordinate of the bounding box.
minWidth | 0 | The minimum width the plot area can adjust to.
minHeight | 0 | The minimum height the plot area can adjust to.

Return Value

None


XYChart.setClipping

XYChart.setClipping

Usage

public void setClipping([ int 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. 0 means the clipping region is equal to the plot area.

Return Value

None


XYChart.setTrimData

XYChart.setTrimData

Usage

public void setTrimData(int startPos [, int 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

public BarLayer addBarLayer(double[] data [, int color [, String name [, int 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

public BarLayer addBarLayer2([ int dataCombineMethod [, int 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

public BarLayer addBarLayer3(double[] data [, int[] colors [, String[] names [, int 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

public LineLayer addLineLayer(double[] data [, int color [, String name [, int 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

public LineLayer addLineLayer2([ int dataCombineMethod [, int 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

public SplineLayer addSplineLayer([ double[] data [, int color [, String 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 "monotonicity" of the spline curve can be configured by using SplineLayer.setMonotonicity. 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

public StepLineLayer addStepLineLayer([ double[] data [, int color [, String 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

public TrendLayer addTrendLayer(double[] data [, int color [, String name [, int 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

public TrendLayer addTrendLayer2(double[] xData, double[] yData [, int color [, String name [, int 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

public InterLineLayer addInterLineLayer(LineObj line1, LineObj line2, int color12 [, int 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

public ScatterLayer addScatterLayer(double[] xData, double[] yData [, String name [, int symbol [, int symbolSize [, int fillColor [, int 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. -1 means using LineColor as the edge color.

Return Value

A ScatterLayer object representing the scatter layer created.


XYChart.addAreaLayer

XYChart.addAreaLayer

Usage

public AreaLayer addAreaLayer(double[] data [, int color [, String name [, int 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

public AreaLayer addAreaLayer2([ int dataCombineMethod [, int 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

public BoxWhiskerLayer addBoxWhiskerLayer(double[] boxTop, double[] boxBottom [, double[] maxData [, double[] minData [, double[] midData [, int fillColor [, int whiskerColor [, int edgeColor ]]]]]])

Description

Adds a box-whisker layer to the XYChart, and specify the data sets to use for drawing the layer.

A standard box-whisker symbol represents 5 values. In this documentation, they are called maxData, boxTop, midData, boxBottom and minData. The 5 values should be in descending order. The symbol consists of a line joining the maxData and minData, a box from boxTop to boxBottom, and 3 mark lines at maxData, midData and minData.

You may use empty arrays to disable showing some parts of the box-whisker symbol.

For example, to show the box only, simply set the maxData, minData and midData to empty arrays.

Similarly, if the boxTop, boxBottom and midData are set to empty arrays, only the maxData and minData mark lines and the joining lines are visible. This symbol is often used to represent "error bands" together with other chart layers.

In addition to maxData, midData and minData mark lines, you may add additional mark lines 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

public BoxWhiskerLayer addBoxWhiskerLayer2(double[] boxTop, double[] boxBottom [, double[] maxData [, double[] minData [, double[] midData [, int[] fillColors [, double whiskerBrightness [, String[] 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

public BoxWhiskerLayer addBoxLayer(double[] boxTop, double[] boxBottom [, int color [, String 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

public VectorLayer addVectorLayer(double[] xData, double[] yData, double[] lengths, double[] directions [, int lengthScale [, int color [, String name ]]])

Description

Adds a vector layer to the chart.

By default, the vectors start from the given reference points and point away from it. You may use VectorLayer.setArrowAlignment to specify other options, such as for the vectors to point into the reference points, or to have the reference points being the mid-points of the vectors.

ChartDirector supports specifying the vector lengths and directions directly, or indirectly as the lengths and directions from the reference points to the reference end points. This is controlled by lengthScale as described in the following table.

Constant | Value | Description
PixelScale | 0 | The lengths are measured in pixels. The angles are measured clockwise in degrees, with the upwards position as 0.
XAxisScale | 1 | The lengths are measured in x-axis scale. The angles are measured clockwise in degrees, with the upwards position as 0.
YAxisScale | 2 | The lengths are measured in y-axis scale. The angles are measured clockwise in degrees, with the upwards position as 0.
EndPoints | 3 | The vector lengths and directions are measured as the lengths and directions between the reference points and the reference end points.

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 either the lengths of the vectors or the x coordinates of the reference end points, depending on lengthScale.
directions | (Mandatory) | An array of numbers representing either the directions of the vectors or the y coordinates of the reference end points, depending on lengthScale.
lengthScale | PixelScale | The method to specify vector lengths and directions, 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

public HLOCLayer addHLOCLayer(double[] highData, double[] lowData [, double[] openData [, double[] closeData [, int 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

public HLOCLayer 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

public HLOCLayer addHLOCLayer3(double[] highData, double[] lowData, double[] openData, double[] closeData, int upColor, int downColor [, int colorMode [, double 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. -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

public CandleStickLayer addCandleStickLayer(double[] highData, double[] lowData, double[] openData, double[] closeData [, int riseColor [, int fallColor [, int 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.addContourLayer

XYChart.addContourLayer

Usage

public ContourLayer addContourLayer(double[] xData, double[] yData, double[] zData)

Description

Adds a contour layer to the XYChart, and specify the data sets to use for drawing the layer.

ChartDirector supports both gridded and scattered data. If the data points are on a rectangular grid will no missing points, they will be handled as gridded data. Otherwise, they will be handled as scattered data.

For gridded data, you may provide the x and y values of the grid, and the z values of the data points. For a 10 x 15 grid, that means the x data series should have 10 values, the y data series should have 15 values, and the z data series should have 150 values. The x and y data series should be strictly monotonic (either strictly increasing or strictly decreasing).

For both gridded and scattered data, you may also provide the (x, y, z) values of the data points. For example, for 150 data points, the x, y and z data series should each have 150 values. ChartDirector will automatically detect if the data points are gridded or scattered.

Arguments

Argument | Default | Description
xData | (Mandatory) | An array of numbers representing the x data series.
yData | (Mandatory) | An array of numbers representing the y data series.
zData | (Mandatory) | An array of numbers representing the z data series.

Return Value

A ContourLayer object representing the contour layer created.


XYChart.getLayer

XYChart.getLayer

Usage

public Layer getLayer(int i)

Description

Gets a Layer object based on the order in which it is being added to the chart.

Arguments

Argument | Default | Description
i | (Mandatory) | The index of the data layer. The index of the first layer added to the chart is 0. The index of the Nth layer added to the chart is N - 1.

Return Value

The specified Layer object.


XYChart.getLayerByZ

XYChart.getLayerByZ

Usage

public Layer getLayerByZ(int zIndex)

Description

Gets a Layer object based on the order in which it is being drawn.

In ChartDirector, by default, the first layer added will stay on the top of the chart. The second layer will be added under the first layer, and so on. It means The layers will be drawn in the reverse order that they are added to the chart. The ordering can be configured with Layer.moveFront or Layer.moveBack.

Arguments

Argument | Default | Description
zIndex | (Mandatory) | The z-index of the required layer. The z-index of the first layer drawn is 0. The z-index for the Nth layer drawn is N - 1.

Return Value

The Layer object at the specified z-order.


XYChart.getLayerCount

XYChart.getLayerCount

Usage

public int getLayerCount()

Description

Gets the number of layers in the chart.

Arguments

None

Return Value

The number of layers in the chart.


XYChart.layoutAxes

XYChart.layoutAxes

Usage

public void layoutAxes()

Description

Performs axis auto-scaling and sets the axis positions and lengths.

ChartDirector automatically calls this method when creating the chart output (eg. using BaseChart.makeSession, BaseChart.makeChart or BaseChart.makeChart2). There is usually no need to call this method explicitly.

However, if you would like to draw custom objects whose positions or contents depend on the axis scales, you may call this method to auto-scaling the axes before creating the chart output.

The axes will auto-scale based on the data at the time of calling this method. New data added afterwards will not affect the axis scale.

You should not modify the axis scale (eg. using Axis.setLinearScale, Axis.setLabels, etc) after calling this method.

Arguments

None

Return Value

None


XYChart.getXCoor

XYChart.getXCoor

Usage

public int getXCoor(double v)

Description

Gets the x pixel coordinate given the x data value.

This method only accepts numeric values as input. If the axis scale is a date/time scale, and you are using a java.util.Date value, please use Chart.CTime to convert it to a number.

Note: This method should be used only after ChartDirector has output the chart image, or after XYChart.layoutAxes, BaseChart.layout or XYChart.packPlotArea has been called. ChartDirector needs to perform auto- scaling and layout the axis before it can convert between pixel coordinates and data values.

For an XYChart with 3D layers, this method will get the pixel coordinate of the data value on the top layer 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 pixel coordinate of the x data value.


XYChart.getYCoor

XYChart.getYCoor

Usage

public int getYCoor(double v [, Axis yAxis ])

Description

Gets the y pixel coordinate given the y data value.

This method only accepts numeric values as input. If the axis scale is a date/time scale, and you are using a java.util.Date value, please use Chart.CTime to convert it to a number.

Note: This method should be used only after ChartDirector has output the chart image, or after XYChart.layoutAxes, BaseChart.layout or XYChart.packPlotArea has been called. ChartDirector needs to perform auto- scaling and layout the axis before it can convert between pixel coordinates and data values.

For an XYChart with 3D layers, this method will get the pixel coordinate of the data value on the top layer 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 pixel coordinate of the y data value.


XYChart.getXValue

XYChart.getXValue

Usage

public double getXValue(int xCoor)

Description

Gets the x data value given the x pixel coordinate.

This method always returns a numeric value. If the axis scale is a date/time scale, and you are expecting a java.util.Date data type, please use Chart.NTime to convert the number to the java.util.Date data type.

Note: This method should be used only after ChartDirector has output the chart image, or after XYChart.layoutAxes, BaseChart.layout or XYChart.packPlotArea has been called. ChartDirector needs to perform auto- scaling and layout the axis before it can convert between pixel coordinates and data values.

Arguments

Argument | Default | Description
xCoor | (Mandatory) | The x pixel coordinate.

Return Value

The x data value at the x pixel coordinate.


XYChart.getYValue

XYChart.getYValue

Usage

public double getYValue(int yCoor [, Axis yAxis ])

Description

Gets the y data value given the y pixel coordinate.

This method always returns a numeric value. If the axis scale is a date/time scale, and you are expecting a java.util.Date data type, please use Chart.NTime to convert the number to the java.util.Date data type.

Note: This method should be used only after ChartDirector has output the chart image, or after XYChart.layoutAxes, BaseChart.layout or XYChart.packPlotArea has been called. ChartDirector needs to perform auto- scaling and layout the axis before it can convert between pixel coordinates and data values.

Arguments

Argument | Default | Description
yCoor | (Mandatory) | The y pixel coordinate.
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 data value at the y pixel coordinate.


XYChart.getNearestXValue

XYChart.getNearestXValue

Usage

public double getNearestXValue(double xCoor)

Description

Gets the x data value that is nearest to the specified x pixel coordinate.

This method will search all x data values in the XYChart to look for the x data value that is nearest to the given x coordinate. If there are two x data values equally near to the specified x pixel coordinate, this method will arbitrarily return one of the values.

Arguments

Argument | Default | Description
xCoor | (Mandatory) | The x pixel coordinate to search for.

Return Value

The x data value that is nearest to the specified x coordinate.


XYChart.xZoneColor

XYChart.xZoneColor

Usage

public int xZoneColor(double threshold, int belowColor, int aboveColor)

Description

Creates an x-zone color. An x-zone will change from one color to another depending on a threshold value on the x-axis.

For example, if an 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 an 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 an x-zone color can be other dynamic colors. For example, one color can be a solid color, while the other color can 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

public int yZoneColor(double threshold, int belowColor, int aboveColor [, Axis 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 or XYChart.getPlotArea.

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.
setGridAxis | (Self) | Sets the axis used for drawing grid lines.
moveGridBefore | (Self) | Moves the grid lines in front of a Layer.
getLeftX | (Self) | Gets the left x pixel coordinate of the plot area.
getRightX | (Self) | Gets the right x pixel coordinate of the plot area.
getTopY | (Self) | Gets the top y pixel coordinate of the plot area.
getBottomY | (Self) | Gets the bottom y pixel coordinate of the plot area.
getWidth | (Self) | Gets the width of the plot area.
getHeight | (Self) | Gets the height of the plot area.


PlotArea.setBackground

PlotArea.setBackground

Usage

public void setBackground(int color [, int altBgColor [, int 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

public void setBackground2(String img [, int 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

public void setAltBgColor(boolean horizontal, int color1, int color2 [, int 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 means to use horizontal bands. false 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

public void set4QBgColor(int Q1Color, int Q2Color, int Q3Color, int Q4Color [, int 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

public void setGridColor(int hGridColor [, int vGridColor [, int minorHGridColor [, int 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

public void setGridWidth(int hGridWidth [, int vGridWidth [, int minorHGridWidth [, int 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


PlotArea.setGridAxis

PlotArea.setGridAxis

Usage

public void setGridAxis(Axis xGridAxis, Axis yGridAxis)

Description

Sets the axis used for drawing grid lines.

By default, the grid lines will be based on the ticks on the primary x-axis (XYChart.xAxis) and primary y-axis (XYChart.yAxis). This method may be used to specify alternative x-axis and y-axis to base the grid lines on.

Arguments

Argument | Default | Description
xGridAxis | (Mandatory) | The x-axis used for drawing grid lines.
yGridAxis | (Mandatory) | The y-axis used for drawing grid lines.

Return Value

None


PlotArea.moveGridBefore

PlotArea.moveGridBefore

Usage

public void moveGridBefore([ Layer layer ])

Description

Moves the grid lines in front of a Layer.

By default, the grid lines will be drawn at the back of the plot area, behind all the layers. This method can be used to move the grid lines in front of a given layer.

Arguments

Argument | Default | Description
layer | [Null] | The Layer for the grid lines to move in front of. A null value means that the grid lines will be behind all layers.

Return Value

None


PlotArea.getLeftX

PlotArea.getLeftX

Usage

public int getLeftX()

Description

Gets the left x pixel coordinate of the plot area.

Arguments

None

Return Value

The left x pixel coordinate of the plot area.


PlotArea.getRightX

PlotArea.getRightX

Usage

public int getRightX()

Description

Gets the right x pixel coordinate of the plot area.

Arguments

None

Return Value

The right x pixel coordinate of the plot area.


PlotArea.getTopY

PlotArea.getTopY

Usage

public int getTopY()

Description

Gets the top y pixel coordinate of the plot area.

Arguments

None

Return Value

The top y pixel coordinate of the plot area.


PlotArea.getBottomY

PlotArea.getBottomY

Usage

public int getBottomY()

Description

Gets the bottom y pixel coordinate of the plot area.

Arguments

None

Return Value

The bottom y pixel coordinate of the plot area.


PlotArea.getWidth

PlotArea.getWidth

Usage

public int getWidth()

Description

Gets the width of the plot area.

Arguments

None

Return Value

The width of the plot area in pixels.


PlotArea.getHeight

PlotArea.getHeight

Usage

public int getHeight()

Description

Gets the height of the plot area.

Arguments

None

Return Value

The height of the plot area in pixels.


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.
setLength | (Self) | Sets the length of the axis.
setMargin | (Self) | Reserve margins at the ends of the axis.
setIndent | (Self) | Specifies if the axis should be "indented" or not.
setOffset | (Self) | Sets the positional offset of the axis.
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.
makeLabelTable | (Self) | Creates a CDML table and docks it to the axis, with one row (for horizontal axis) or column (for vertical axis) containing the axis labels.
getLabelTable | (Self) | Gets the CDML table created by Axis.makeLabelTable.
getMinValue | (Self) | Gets the lower bound of the axis.
getMaxValue | (Self) | Gets the upper bound of the axis.
getX | (Self) | Gets the x-coordinate of starting point of the axis.
getY | (Self) | Gets the y-coordinate of starting point of the axis.
getAlignment | (Self) | Gets the side of the plot area that the axis is associated with.
getThickness | (Self) | Gets the thickness of the axis.
getTicks | (Self) | Gets the values of the ticks.
getLabel | (Self) | Gets the label at the specified position on the axis.
getFormattedLabel | (Self) | Gets the label at the specified position on the axis, formatting one if necessary.
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

public TextBox setLabelStyle([ String font [, double fontSize [, int fontColor [, double 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 axis labels. This may be used to fine-tune the appearance of the axis labels.


Axis.setLabelFormat

Axis.setLabelFormat

Usage

public void setLabelFormat(String 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

public void setMultiFormat(int filter1, String format1, int filter2, String format2 [, int labelSpan [, boolean 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 Chart.StartOfMonthFilter), and the first format string can be "{value|mmm-dd}". The second filter can be the "all pass" filter (created using Chart.AllPassFilter), and the format string can be "{value|dd}".

Supported filters in ChartDirector include:

Filter | Description
Chart.StartOfHourFilter | Creates a data filter that matches date/times that represent the start of a new hour in a date/time series.
Chart.StartOfDayFilter | Creates a data filter that matches date/times that represent the start of a new day in a date/time series.
Chart.StartOfWeekFilter | Creates a data filter that matches date/times that represent the start of a new week in a date/time series.
Chart.StartOfMonthFilter | Creates a data filter that matches date/times that represent the start of a new month in a date/time series.
Chart.StartOfYearFilter | Creates a data filter that matches date/times that represent the start of a new year in a date/time series.
Chart.RegularSpacingFilter | Creates a data filter that matches 1 out of every N elements.
Chart.AllPassFilter | Creates a data filter that matches every element.
Chart.NonePassFilter | Creates a data filter that matches no element.
Chart.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 | 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

public void setMultiFormat2(int filterId, String formatString [, int labelSpan [, boolean 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 | 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

public void setFormatCondition(String condition [, double 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

public void setLabelGap(int 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

public void setLabelOffset(double offset)

Description

Shifts the axis labels from its default position along the axis.

The offset can be specified in axis scale unit. For example, an offset of 50 means the tick is shifted 50 units along the axis.

The offset can also be specified as a multiple of the major tick increment. This is by using the TickInc predefined constant to represent the major tick increment. For example, an offset of 0.5 * TickInc means the offset is half the major tick increment.

To shift the axis labels in pixel units, the Box.setPos method of the axis label prototype (obtained using Axis.setLabelStyle) can also used instead.

Arguments

Argument | Default | Description
offset | (Mandatory) | The distance to shift the labels along the axis.

Return Value

None


Axis.setTitle

Axis.setTitle

Usage

public TextBox setTitle(String text [, String font [, double fontSize [, int 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

public void setTitlePos(int alignment [, int 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

public void setColors(int axisColor [, int labelColor [, int titleColor [, int 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

public void setTickLength(int 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

public void setTickLength2(int majorTickLen, int 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

public void setTickWidth(int majorTickWidth [, int 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

public void setTickColor(int majorTickColor [, int 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 minor ticks. -1 means the color is the same as majorTickColor.

Return Value

None


Axis.setTickOffset

Axis.setTickOffset

Usage

public void setTickOffset(double offset)

Description

Shifts the position of the ticks along the axis.

The offset can be specified in axis scale unit. For example, an offset of 50 means the tick is shifted 50 units along the axis.

The offset can also be specified as a multiple of the major tick increment. This is by using the TickInc predefined constant to represent the major tick increment. For example, an offset of 0.5 * TickInc means the offset is half the major tick increment.

For a label based axis (set up with Axis.setLabels or Axis.setLabels2), by default, the ticks are center aligned with the labels. This method is commonly used to shift the ticks to put them in between the labels. This is by using an offset of 0.5 to shift the ticks for half the label interval.

Arguments

Argument | Default | Description
offset | (Mandatory) | The distance to shift the ticks along the axis.

Return Value

None


Axis.setMinTickInc

Axis.setMinTickInc

Usage

public void setMinTickInc(double 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 treated 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

public void setWidth(int 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.setLength

Axis.setLength

Usage

public void setLength(int length)

Description

Sets the length of the axis.

During axis layout, ChartDirector will automatically set vertical axes to the same length as the plot area height, and horizontal axes to the same length as the plot area width.

Calling this method before axis layout has no effect, as the length will be overwritten during axis layout. This method should only be called after axis layout (after calling XYChart.layoutAxes, BaseChart.layout or XYChart.packPlotArea).

Arguments

Argument | Default | Description
length | (Mandatory) | The length of the axis in pixels.

Return Value

None


Axis.setMargin

Axis.setMargin

Usage

public void setMargin(int topMargin [, int 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

public void setIndent(boolean 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 value sets the axis to indented mode. A false value sets the axis to non-indented mode.

Return Value

None


Axis.setOffset

Axis.setOffset

Usage

public void setOffset(int x, int y)

Description

Sets the positional offset of the axis.

By default, ChartDirector draws horizontal axes at the top/bottom borders of the plot area, and vertical axes at the left/right borders of the plot area.

This method can be used to shift an axis from its standard position.

Arguments

Argument | Default | Description
x | (Mandatory) | The x offset in pixels.
y | (Mandatory) | The y offset in pixels.

Return Value

None


Axis.setAutoScale

Axis.setAutoScale

Usage

public void setAutoScale([ double topExtension [, double bottomExtension [, double 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

public void setRounding(boolean roundMin, boolean 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 value means the lesser end of the axis should be rounded to align with tick positions. A false value means no rounding.
roundMax | (Mandatory) | A true value means the greater end of the axis should be rounded to align with tick positions. A false value means no rounding.

Return Value

None


Axis.setTickDensity

Axis.setTickDensity

Usage

public void setTickDensity(int majorTickSpacing [, int 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

public void setReverse([ boolean 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 | A true value means the axis is reversed. A false value means the axis is not reversed.

Return Value

None


Axis.setLabels

Axis.setLabels

Usage

public TextBox setLabels(String[] 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.

A leading '-' or '~' character is treated as a tick specification character and will not appear on the labels. It just specifies the the tick style to be associated with the labels. If you want have a label that actually begins with '-' or '~', you may start the label with '\-' or '\~' 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.

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 axis labels. This may be used to fine-tune the appearance of the axis labels.


Axis.setLabels2

Axis.setLabels2

Usage

public void setLabels2({double | java.util.Date}[] labels [, String 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 axis labels. This may be used to fine-tune the appearance of the axis labels.


Axis.setLabelStep

Axis.setLabelStep

Usage

public void setLabelStep(int majorTickStep [, int minorTickStep [, int majorTickOffset [, int 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. 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

public void setLinearScale(double lowerLimit, double upperLimit [, double majorTickInc [, double 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. 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. 0 means no minor tick is used.

Return Value

None


Axis.setLinearScale2

Axis.setLinearScale2

Usage

public void setLinearScale2(double lowerLimit, double upperLimit, String[] labels)

Description

Sets the axis to use the given linear scale and the given labels.

Note that the first character of a label can be interpreted as a tick specification character. Please refer to Axis.setLabels for more details.

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

public void setLinearScale3([ String 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

public void setLogScale(double lowerLimit, double upperLimit [, double majorTickInc [, double 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 predefined constant LogTick means the ticks will be a segment from the sequence ..., 1, 2, 5, 10, 20, 50, 100, ... These numbers are roughly equally spaced in a logarithmic axis. The predefined constant LinearTick the tick increment will be linear within two consecutive powers of 10, like ..., 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, ... 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 predefined constant LogTick and LinearTick has the same meaning as in the majorTickInc argument. 0 means no minor tick is used.

Return Value

None


Axis.setLogScale2

Axis.setLogScale2

Usage

public void setLogScale2(double lowerLimit, double upperLimit, String[] 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

public void setLogScale3([ String 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

public void setDateScale({double | java.util.Date} lowerLimit, {double | java.util.Date} upperLimit [, double majorTickInc [, double 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. 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. 0 means no minor tick is used.

Return Value

None


Axis.setDateScale2

Axis.setDateScale2

Usage

public void setDateScale2({double | java.util.Date} lowerLimit, {double | java.util.Date} upperLimit, String[] 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

public void setDateScale3([ String 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

public void syncAxis(Axis axis [, double slope [, double 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. A value of null means not to synchronize to any axis.
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

public void copyAxis(Axis 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

public void addLabel(double pos, String label)

Description

Adds an extra label on the axis.

Note that the first character of the label can be interpreted as a tick specification character. Please refer to Axis.setLabels for more details.

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

public Mark addMark(double value, int lineColor [, String text [, String font [, double 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

public void addZone(double startValue, double endValue, int 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.makeLabelTable

Axis.makeLabelTable

Usage

public CDMLTable makeLabelTable()

Description

Creates a CDML table and docks it to the axis, with one row (for horizontal axis) or column (for vertical axis) containing the axis labels.

Before calling this method, it is necessarily to set the labels on the axis first using Axis.setLabels or Axis.setLabels2. You should only use this method on a label based axis with no label stepping.

This method will automatically indent the axis (see Axis.setIndent), and set the tick offset to 0.5 (see Axis.setTickOffset). This is to ensure the plot area grid lines align with the table grid lines (instead of align with the labels).

You may use the returned CDMLTable object to insert additional rows and/or columns to the table. A common application of this method is to insert the data values to the table, so the chart will have a data table docked to the axis, aligned with the chart contents.

Arguments

None

Return Value

A CDMLTable object containing the axis labels.


Axis.getLabelTable

Axis.getLabelTable

Usage

public CDMLTable getLabelTable()

Description

Gets the CDML table created by Axis.makeLabelTable.

Arguments

None

Return Value

A CDMLTable object containing the axis labels.


Axis.getMinValue

Axis.getMinValue

Usage

public double 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 axis layout (after calling XYChart.layoutAxes, BaseChart.layout or XYChart.packPlotArea).

Arguments

None

Return Value

The lower bound of the axis.


Axis.getMaxValue

Axis.getMaxValue

Usage

public double 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 axis layout (after calling XYChart.layoutAxes, BaseChart.layout or XYChart.packPlotArea).

Arguments

None

Return Value

The upper bound of the axis.


Axis.getX

Axis.getX

Usage

public int getX()

Description

Gets the x-coordinate of starting point of the axis.

For an XYChart object, the starting point of a horizontal axis is its left end point, and the starting point of a vertical axis is its bottom end point. For a PolarChart object, the starting point of a radial axis is the origin. For other types of charts, the starting point of an axis is undefined.

Arguments

None

Return Value

The x-coordinate of starting point of the axis.


Axis.getY

Axis.getY

Usage

public int getY()

Description

Gets the y-coordinate of starting point of the axis.

For an XYChart object, the starting point of a horizontal axis is its left end point, and the starting point of a vertical axis is its bottom end point. For a PolarChart object, the starting point of a radial axis is the origin. For other types of charts, the starting point of an axis is undefined.

Arguments

None

Return Value

The y-coordinate of starting point of the axis.


Axis.getAlignment

Axis.getAlignment

Usage

public int getAlignment()

Description

Gets the side of the plot area that the axis is associated with.

This method is only applicable to XYChart objects.

Arguments

None

Return Value

A constant equals to Left, Right, Top or Bottom, depending on the side of the plot area that the axis is associated with.


Axis.getThickness

Axis.getThickness

Usage

public double getThickness()

Description

Gets the thickness of the axis.

The axis can be considered as a line, with one side facing the internal of the plot area, and the other side not facing the plot area. By default, the latter side includes the axis labels and axis title (although ChartDirector allows the axis to be configured so that the labels and titles are internal to the plot area).

The thickness of an axis only refers to the thickness of the side not facing the plot area. For a vertical axis, it is the width of the bounding box of that side, including the axis ticks, labels and title if they are on that side. For a horizontal axis, it is the height of the bounding box.

The intention of this method is to allow the chart to be adjusted to leave enough space for the axis labels and title.

This method should be called only after axis layout (after calling XYChart.layoutAxes, BaseChart.layout or XYChart.packPlotArea).

Arguments

None

Return Value

The thickness of the axis in pixels.


Axis.getTicks

Axis.getTicks

Usage

public double[] 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

public String getLabel(double 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.getFormattedLabel

Axis.getFormattedLabel

Usage

public String getFormattedLabel(double i [, String formatString ])

Description

Gets the label at the specified position on the axis, formatting one if necessary.

Arguments

Argument | Default | Description
i | (Mandatory) | The position specified as a value on the axis scale.
formatString | "" | The format string used to format a label if necessary. Please refer to Axis.setLabelFormat for the syntax of the format string. An empty string means the format will be automatically determined.

Return Value

Returns the label at the specified position. If there is no axis label at that position, formats one using the format string.


Axis.getHTMLImageMap

Axis.getHTMLImageMap

Usage

public String getHTMLImageMap(String url [, String queryFormat [, String extraAttr [, int offsetX, int 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

public String getAxisImageMap(int noOfSegments, int mapWidth, String url [, String queryFormat [, String extraAttr [, int offsetX, int 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.


ColorAxis

ColorAxis

The ColorAxis class represents color axes. It is a subclass of Axis.

A color axis is similar to an x or y axis. However, instead of mapping data values to positions, a color axis maps data values to colors. Color axes are used in ContourLayer and in SurfaceChart objects.

Similar to an x or y axis, a color axis is visually represented as a thin bar that can be horizontal or vertical, and has a scale along its length. The scale can be set explicitly or can be determined by auto-scaling.

Note: If you are using the color axis on a surface chart, please note that by default, the color axis scale is synchronized to the z axis. You need to use Axis.syncAxis to cancel the synchronization before you can independently set the color axis scale.

In addition to the scale, a color axis is colored with a continuous color gradient or discrete color steps along its length. This maps the values on the axis with colors.

For an x or y axis, the major and minor ticks correspond to major and minor grid lines on the chart. For a color axis, these ticks correspond to major and minor contour lines on the chart.

Like an x or y axis, you can add marks to the color axis using Axis.addMark. They will become mark contour lines on the chart.

The color axis, if visible, acts as a color legend. The axis stem is a thin rectangle 15 pixels in width, configurable with Axis.setWidth. A bounding box can be added to surround the color axis using ColorAxis.setBoundingBox.

A color axis works normally (determines color mapping and contour levels) even if it is not displayed.

Method | Inherited | Description
setAxisPos | (Self) | Sets the position of the color axis.
setColorGradient | (Self) | Sets the continuous color gradient or discrete color steps for the color axis.
setLevels | (Self) | Sets the maximum number of contour intervals on the axis.
setCompactAxis | (Self) | Sets whether to compact the axis or not.
setAxisBorder | (Self) | Sets the border color and 3D border effect of the axis stem.
setBoundingBox | (Self) | Sets the background color, border color and 3D border effect of the bounding box.
setBoxMargin | (Self) | Sets all margins (left, right, top, and bottom) of the bounding box to the same value.
setBoxMargin2 | (Self) | Sets the margins of the bounding box in pixels.
setRoundedCorners | (Self) | Sets the border style of the bounding box to rounded corners.
getBoxWidth | (Self) | Gets the width of the color axis inclusive of the bounding box.
getBoxHeight | (Self) | Gets the height of the color axis inclusive of the bounding box.
getColor | (Self) | Gets the color given the data value.
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.
setLength | Axis | Sets the length of the axis.
setMargin | Axis | Reserve margins at the ends of the axis.
setIndent | Axis | Specifies if the axis should be "indented" or not.
setOffset | Axis | Sets the positional offset of the axis.
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.
makeLabelTable | Axis | Creates a CDML table and docks it to the axis, with one row (for horizontal axis) or column (for vertical axis) containing the axis labels.
getLabelTable | Axis | Gets the CDML table created by Axis.makeLabelTable.
getMinValue | Axis | Gets the lower bound of the axis.
getMaxValue | Axis | Gets the upper bound of the axis.
getX | Axis | Gets the x-coordinate of starting point of the axis.
getY | Axis | Gets the y-coordinate of starting point of the axis.
getAlignment | Axis | Gets the side of the plot area that the axis is associated with.
getThickness | Axis | Gets the thickness of the axis.
getTicks | Axis | Gets the values of the ticks.
getLabel | Axis | Gets the label at the specified position on the axis.
getFormattedLabel | Axis | Gets the label at the specified position on the axis, formatting one if necessary.
getHTMLImageMap | Axis | Generates an HTML image map for the axis labels.
getAxisImageMap | Axis | Generates an HTML image map for the axis itself.


ColorAxis.setAxisPos

ColorAxis.setAxisPos

Usage

public void setAxisPos(int x, int y, int alignment)

Description

Sets the position of the color axis.

Arguments

Argument | Default | Description
x | (Mandatory) | The x-coordinate of the reference point used to position the color axis.
y | (Mandatory) | The y-coordinate of the reference point used to position the color axis.
alignment | (Mandatory) | The alignment of the color axis with respect to the reference point. For example, a value of TopLeft means the reference point is the top- left corner of the color axis. See Alignment Specification for supported alignment types..

Return Value

None


ColorAxis.setColorGradient

ColorAxis.setColorGradient

Usage

public void setColorGradient([ boolean isContinuous [, int[] colors [, int underflowColor [, int overflowColor ]]]])

Description

Sets the continuous color gradient or discrete color steps for the color axis.

Arguments

Argument | Default | Description
isContinuous | true | True ti set to continuous color gradient. False to set to discrete color steps.
colors | [Empty_Array] | An array of colors used to define the continuous color gradient. If an empty array is used, the colors are automatically determined. ChartDirector will interpolate between the colors to create the continuous gradient. If discrete color steps are used, ChartDirector will take samples along the continuous color gradient. The number of samples is determined by the number of ticks on the axis, and may not equal the number of colors in the colors array.
underflowColor | -1 | The color to use if a value falls below the minimum value of the axis scale. -1 means the underflowColor is the same color at the minimum value.
overflowColor | -1 | The color to use if a value exceeds the maximum value of the axis scale. -1 means the overflowColor is the same color at the maximum value.

Return Value

None


ColorAxis.setLevels

ColorAxis.setLevels

Usage

public void setLevels(int maxLevels)

Description

Sets the maximum number of contour intervals on the axis.

If discrete color steps are used, the number of contour intervals is the number of color steps on the axis.

For a general color axis, the number of contour intervals is equal to the number of ticks minus 1. For example, an axis with 6 ticks at [0, 2, 4, 6, 8, 10] has 6 contour lines and 5 contour intervals.

The main usage of this method is to limit the number of contour lines and/or color steps on the contour layer.

If this method is never called, the default maximum number of contour intervals is 16.

Arguments

Argument | Default | Description
maxLevels | (Mandatory) | An integer representing the maximum number of contour intervals.

Return Value

None


ColorAxis.setCompactAxis

ColorAxis.setCompactAxis

Usage

public void setCompactAxis([ boolean b ])

Description

Sets whether to compact the axis or not.

For a color axis, the axis can assume any length. Typically, an initial length is specified so that ChartDirector can determine how many labels can be fitted on the axis, and auto-scale the axis accordingly.

After the labels are determined, ChartDirector can compact the axis by setting its length to the minimum length compatible with the major tick density (see Axis.setTickDensity).

For example, suppose ChartDirector auto-scaling has set the axis labels to be [0, 1, 2, 3, 4, 5], and the major tick density is 20 pixels, ChartDirector will set the axis length to 100 pixels, irrespective of its original length.

If this method is never called, the default is not to compact the axis.

Arguments

Argument | Default | Description
b | true | A true value means to compact the axis. A false value means not to compact the axis.

Return Value

None


ColorAxis.setAxisBorder

ColorAxis.setAxisBorder

Usage

public void setAxisBorder(int edgeColor [, int raisedEffect ])

Description

Sets the border color and 3D border effect of the axis stem.

Arguments

Argument | Default | Description
edgeColor | (Mandatory) | The edge color of the axis stem.
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 Chart.glassEffect, Chart.softLighting and Chart.cylinderEffect effects.

Return Value

None


ColorAxis.setBoundingBox

ColorAxis.setBoundingBox

Usage

public void setBoundingBox(int fillColor [, int edgeColor [, int raisedEffect ]])

Description

Sets the background color, border color and 3D border effect of the bounding box.

Arguments

Argument | Default | Description
fillColor | (Mandatory) | The background color of the bounding box.
edgeColor | Transparent | The border color of the bounding 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 Chart.glassEffect, Chart.softLighting and Chart.cylinderEffect effects.

Return Value

None


ColorAxis.setBoxMargin

ColorAxis.setBoxMargin

Usage

public void setBoxMargin(int m)

Description

Sets all margins (left, right, top, and bottom) of the bounding box to the same value.

The margins of a bounding box refer to the distances between the borders of the bounding box to the color axis inside.

Arguments

Argument | Default | Description
m | (Mandatory) | The left, right, top and bottom margins in pixels.

Return Value

None


ColorAxis.setBoxMargin2

ColorAxis.setBoxMargin2

Usage

public void setBoxMargin2(int leftMargin, int rightMargin, int topMargin, int bottomMargin)

Description

Sets the margins of the bounding box in pixels.

The margins of a bounding box refer to the distances between the borders of the bounding box to the color axis inside.

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


ColorAxis.setRoundedCorners

ColorAxis.setRoundedCorners

Usage

public void setRoundedCorners([ int r1 [, int r2 [, int r3 [, int r4 ]]]])

Description

Sets the border style of the bounding box to 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. -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. -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. -1 means it is the same as the radius of the top-left corner.

Return Value

None


ColorAxis.getBoxWidth

ColorAxis.getBoxWidth

Usage

public int getBoxWidth()

Description

Gets the width of the color axis inclusive of the bounding box.

This method should be called only after axis layout (after calling XYChart.layoutAxes, BaseChart.layout or XYChart.packPlotArea).

Arguments

None

Return Value

The width of the color axis inclusive of the bounding box.


ColorAxis.getBoxHeight

ColorAxis.getBoxHeight

Usage

public int getBoxHeight()

Description

Gets the height of the color axis inclusive of the bounding box.

This method should be called only after axis layout (after calling XYChart.layoutAxes, BaseChart.layout or XYChart.packPlotArea).

Arguments

None

Return Value

The height of the color axis inclusive of the bounding box.


ColorAxis.getColor

ColorAxis.getColor

Usage

public int getColor(double z)

Description

Gets the color given the data value.

Note: You must call XYChart.layoutAxes, BaseChart.layout or XYChart.packPlotArea first before calling this method. ChartDirector needs to perform auto-scaling and layout the axis before it can compute the color.

Arguments

Argument | Default | Description
z | (Mandatory) | The data value.

Return Value

The color that corresponds to the data value.


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.
setPos | Box | Sets the coordinates of the reference point of the box, which by default is 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.
getLeftX | Box | Gets the left x pixel coordinate of the box.
getTopY | Box | Gets the top y pixel coordinate of the box.
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

public void setValue(double 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

public void setMarkColor(int lineColor [, int textColor [, int 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

public void setLineWidth(int 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

public void setDrawOnTop(boolean 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 value means drawing the mark line at the front of the chart layers. A false value means drawing the mark line at the back of the plot area.

Return Value

None


Mark.getLine

Mark.getLine

Usage

public LineObj 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 lighting effect for the data representation.
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.
getLegendIcon | (Self) | Gets the CDML representation of the legend icon for a data set.
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 a DataSet object based on the order in which it is being added to the chart.
getDataSetByZ | (Self) | Gets a DataSet object based on the order in which it is being drawn.
getDataSetCount | (Self) | Gets the number of data sets in the layer.
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.
setBaseLine | (Self) | Sets the baseline for the data representation.
alignLayer | (Self) | Aligns the layer with a data set of another bar chart layer in Side layout.
getXCoor | (Self) | Gets the x pixel coordinate given the x data value.
getYCoor | (Self) | Gets the y pixel coordinate given the y data value.
getNearestXValue | (Self) | Gets the x data value that is nearest to the specified x pixel coordinate.
getXIndexOf | (Self) | Gets the data point index at the specified x data value.
getXPosition | (Self) | Gets the x positional value of a data point, as measured on the primary x-axis.
xZoneColor | (Self) | Creates an x-zone color. An 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.
moveFront | (Self) | Moves the layer in front of another layer.
moveBack | (Self) | Moves the layer behind another layer.
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

public void set3D([ int d [, int 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

public void setLineWidth(int 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

public void setBorderColor(int color [, int lightingEffect ])

Description

Sets the default border color and lighting effect for the data representation.

The border color only applies to data representation that has a border, such as a bar, an area or a 3D line. It does not apply to data representation that does not have a border, such as a 2D line. The border color affect all data sets in the layer. To set the border color of one particular data set, use DataSet.setDataColor.

Only certain layer types support lighting effects. They are described in the following table.

Layer Type | Lighting Effects
BarLayer | Setting lightingEffect to an integer within +/- 4000 will create a bevel border around the bar. The border will appear as raised for a positive number, and depressed for a negative number. The border width will be the magnitude of the number in pixels. Setting lightingEffect to the return value of Chart.glassEffect, Chart.softLighting, Chart.cylinderEffect or Chart.barLighting will enable the respective effect on the bar.
BoxWhiskerLayer | Supports the same lighting effect as the BarLayer, except Chart.barLighting.
LineLayer | For a 3D line layer, Chart.phongLighting can be used to shade the 3D line surface.
SplineLayer | Supports the same lighting effect as the LineLayer.

Arguments

Argument | Default | Description
color | (Mandatory) | The border color.
lightingEffect | 0 | Specifies the 3D bevel border width or special shading effects as described in the above table.

Return Value

None


Layer.setLegendOrder

Layer.setLegendOrder

Usage

public void setLegendOrder(int dataSetOrder [, int 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. -1 means the priority is 10000 x (layer_index + 1).

Return Value

None


Layer.setLegend

Layer.setLegend

Usage

public void setLegend(int 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.getLegendIcon

Layer.getLegendIcon

Usage

public char getLegendIcon(int dataSetNo)

Description

Gets the CDML representation of the legend icon for a data set.

The CDML representation can be used in any ChartDirector API that supports CDML. Note that the CDML representation is only valid in the BaseChart object that contains the data set. It is not allowed to use the CDML representation obtained from one chart in a different chart.

The legend icon is the same icon that would appear in the LegendBox. If you modify the icon using methods of the LegendBox object (such as using LegendBox.setKeyBorder to set the legend icon border), the modification will also apply to the icon returned by this method.

Arguments

Argument | Default | Description
dataSetNo | (Mandatory) | The index of the data set. The index of the first data set added to the layer is 0. The index of the Nth data set added to the layer is N - 1.

Return Value

The CDML representation of the legend icon for the data set.


Layer.setDataCombineMethod

Layer.setDataCombineMethod

Usage

public void setDataCombineMethod(int 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

public DataSet addDataSet(double[] data [, int color [, String 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

public DataSet getDataSet(int dataSetNo)

Description

Gets a DataSet object based on the order in which it is being added to the chart.

Arguments

Argument | Default | Description
dataSetNo | (Mandatory) | The index of the data set. The index of the first data set added to the layer is 0. The index of the Nth data set added to the layer is N - 1.

Return Value

The specified DataSet object.


Layer.getDataSetByZ

Layer.getDataSetByZ

Usage

public DataSet getDataSetByZ(int zIndex)

Description

Gets a DataSet object based on the order in which it is being drawn.

In certain layer types, the data sets are drawn in a certain order. For example, in a line layer, the data sets represent lines and they are drawn one by one. In contrast, for a candlestick layer, the high, low, open and close data sets are combined into candlestick symbols, and there is no specific order on which data sets are drawn.

This method can be used to get the data set based on the order it is being drawn. If the data sets are not drawn in any specific order, this method will return the data sets in the reverse order to which it is added to the layer.

Arguments

Argument | Default | Description
zIndex | (Mandatory) | The z-index of the required data set. The z-index of the first data set drawn is 0. The z-index for the Nth data set drawn is N - 1.

Return Value

The DataSet object at the specified z-order.


Layer.getDataSetCount

Layer.getDataSetCount

Usage

public int getDataSetCount()

Description

Gets the number of data sets in the layer.

Arguments

None

Return Value

The number of data sets in the layer.


Layer.addDataGroup

Layer.addDataGroup

Usage

public void addDataGroup([ String 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

public void addExtraField(String[] 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

public void addExtraField2({double | java.util.Date}[] 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

public void setUseYAxis(Axis 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

public void setUseYAxis2([ boolean 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 | A true value means the secondary y-axis will be used. A false value means the primary y-axis will be used.

Return Value

None


Layer.setXData

Layer.setXData

Usage

public void setXData({double | java.util.Date}[] 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

public void setXData@2({double | java.util.Date} minValue, {double | java.util.Date} 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.setBaseLine

Layer.setBaseLine

Usage

public void setBaseLine(double baseLine)

Description

Sets the baseline for the data representation.

Certain data representation, such as bars in bar layers and area in area layers, are drawn from a base line. The base line by default is y = 0.

For example, for a vertical bar layer, the bars start from y = 0 and grow upwards for positive data (assuming the y-axis is not reversed), and downwards for negative data.

This method can be used to modify the base line to other values.

Arguments

Argument | Default | Description
baseLine | (Mandatory) | The value of the base line.

Return Value

None


Layer.alignLayer

Layer.alignLayer

Usage

public void alignLayer(Layer layer, int 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

public int getXCoor(double v)

Description

Gets the x pixel coordinate given the x data value.

This method only accepts numeric values as input. If the axis scale is a date/time scale, and you are using a java.util.Date value, please use Chart.CTime to convert it to a number.

Note: This method should be used only after ChartDirector has output the chart image, or after XYChart.layoutAxes, BaseChart.layout or XYChart.packPlotArea has been called. ChartDirector needs to perform auto- scaling and layout the axis before it can convert between pixel coordinates and data values.

Arguments

Argument | Default | Description
v | (Mandatory) | The x data value.

Return Value

The x pixel coordinate of the x data value.


Layer.getYCoor

Layer.getYCoor

Usage

public int getYCoor(double v [, Axis yAxis ])

Description

Gets the y pixel coordinate given the y data value.

This method only accepts numeric values as input. If the axis scale is a date/time scale, and you are using a java.util.Date value, please use Chart.CTime to convert it to a number.

Note: This method should be used only after ChartDirector has output the chart image, or after XYChart.layoutAxes, BaseChart.layout or XYChart.packPlotArea has been called. ChartDirector needs to perform auto- scaling and layout the axis before it can convert between pixel coordinates and data values.

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 value means the primary y-axis. A false value means the secondary y-axis.

Return Value

The y pixel coordinate of the y data value.


Layer.getNearestXValue

Layer.getNearestXValue

Usage

public double getNearestXValue(double xCoor)

Description

Gets the x data value that is nearest to the specified x pixel coordinate.

This method will search all x data values in the Layer to look for the x data value that is nearest to the given x coordinate. If there are two x data values equally near to the specified x pixel coordinate, this method will arbitrarily return one of the values.

Arguments

Argument | Default | Description
xCoor | (Mandatory) | The x pixel coordinate to search for.

Return Value

The x data value that is nearest to the specified x coordinate.


Layer.getXIndexOf

Layer.getXIndexOf

Usage

public int getXIndexOf(double xValue [, double tolerance ])

Description

Gets the data point index at the specified x data value.

The index can be used in DataSet.getValue and DataSet.getPosition to obtain the y values and positions of the data points for all data sets in the layer.

The tolerance argument is to allow this method to consider data points that are not exactly at xValue, but are within tolerance from it.

If multiple data points at within tolerance, this method will return the index of the data point nearest to xValue. If multiple data points are equally near to xValue, this method will choose one arbitrarily and return its data point index. If no data points are found, this method will return -1.

Arguments

Argument | Default | Description
xValue | (Mandatory) | The x data value used to look for the data points in order to get the data point index of the nearest data point.
tolerance | 0 | The tolerance allowed for for data points that are not exactly at the specified xValue.

Return Value

The data point index of the data point nearest to the specified x data value up to the specified tolerance, or -1 if no data points are found.


Layer.getXPosition

Layer.getXPosition

Usage

public double getXPosition(int i)

Description

Gets the x positional value of a data point, as measured on the primary x-axis.

Arguments

Argument | Default | Description
i | (Mandatory) | The data point index of the data point. The first data point is 0; the nth data point is (n - 1).

Return Value

The x positional value of the data point.


Layer.xZoneColor

Layer.xZoneColor

Usage

public int xZoneColor(double threshold, int belowColor, int aboveColor)

Description

Creates an x-zone color. An x-zone will change from one color to another depending on a threshold value on the x-axis.

For example, if an 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 an 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 an x-zone color can be other dynamic colors. For example, one color can be a solid color, while the other color can 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

public int yZoneColor(double threshold, int belowColor, int aboveColor [, Axis 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 value means the primary y-axis. A false value means the secondary y-axis.

Return Value

A 32-bit integer representing the y-zone color.


Layer.setDataLabelStyle

Layer.setDataLabelStyle

Usage

public TextBox setDataLabelStyle([ String font [, double fontSize [, int fontColor [, double 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 data labels. This may be used to fine-tune the appearance of the data labels.


Layer.setDataLabelFormat

Layer.setDataLabelFormat

Usage

public void setDataLabelFormat(String 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

public TextBox addCustomDataLabel(int dataSet, int dataItem, String label [, String font [, double fontSize [, int fontColor [, double 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 index of the data point. The first data set is 0; the nth data set is (n - 1).
dataItem | (Mandatory) | The data point index of the data point. The first data point is 0; 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 custom data label. This may be used to fine-tune the appearance of the custom data label.


Layer.setAggregateLabelStyle

Layer.setAggregateLabelStyle

Usage

public TextBox setAggregateLabelStyle([ String font [, double fontSize [, int fontColor [, double 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 aggregate data labels. This may be used to fine-tune the appearance of the aggregate data labels.


Layer.setAggregateLabelFormat

Layer.setAggregateLabelFormat

Usage

public void setAggregateLabelFormat(String 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

public TextBox addCustomAggregateLabel(int dataItem, String label [, String font [, double fontSize [, int fontColor [, double 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 custom aggregate label. This may be used to fine-tune the appearance of the custom aggregate label.


Layer.addCustomGroupLabel

Layer.addCustomGroupLabel

Usage

public TextBox addCustomGroupLabel(int dataGroup, int dataItem, String label [, String font [, double fontSize [, int fontColor [, double 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 index of the data point. The first data group is 0; the nth data group is (n - 1).
dataItem | (Mandatory) | The data point index of the data point. The first data point is 0; 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 custom data group label. This may be used to fine-tune the appearance of the custom data group label.


Layer.moveFront

Layer.moveFront

Usage

public void moveFront([ Layer layer ])

Description

Moves the layer in front of another layer.

By default, the front to back ordering of the Layer objects are the same as the order in which they are added to the chart. For example, a layer added first will be in front of a layer added last.

This method can be used to move the layer in front of another layer.

Arguments

Argument | Default | Description
layer | [Null] | The Layer for this layer to move in front of. The default value of null means the layer will be moved in front of all current layers.

Return Value

None


Layer.moveBack

Layer.moveBack

Usage

public void moveBack([ Layer layer ])

Description

Moves the layer behind another layer.

By default, the front to back ordering of the Layer objects are the same as the order in which they are added to the chart. For example, a layer added first will be in front of a layer added last.

This method can be used to move the layer behind another layer.

Arguments

Argument | Default | Description
layer | [Null] | The Layer for this layer to move behind. A null object means the layer will be moved behind all current layers.

Return Value

None


Layer.getImageCoor

Layer.getImageCoor

Usage

public String getImageCoor(int dataSet, int dataItem [, int offsetX, int 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 index of the data point. The first data set is 0; the nth data set is (n - 1).
dataItem | (Mandatory) | The data point index of the data point. The first data point is 0; 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

public String getImageCoor2(int dataItem [, int offsetX, int 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="[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

public String getHTMLImageMap(String url [, String queryFormat [, String extraAttr [, int offsetX, int 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

public void setHTMLImageMap(String url [, String queryFormat [, String 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.
setMinImageMapSize | (Self) | Sets the minimum height (or width if the x-axis and y-axis are swapped with XYChart.swapXY) of the hot spots defined by the image map.
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 lighting effect for the data representation.
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.
getLegendIcon | Layer | Gets the CDML representation of the legend icon for a data set.
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 a DataSet object based on the order in which it is being added to the chart.
getDataSetByZ | Layer | Gets a DataSet object based on the order in which it is being drawn.
getDataSetCount | Layer | Gets the number of data sets in the layer.
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.
setBaseLine | Layer | Sets the baseline for the data representation.
alignLayer | Layer | Aligns the layer with a data set of another bar chart layer in Side layout.
getXCoor | Layer | Gets the x pixel coordinate given the x data value.
getYCoor | Layer | Gets the y pixel coordinate given the y data value.
getNearestXValue | Layer | Gets the x data value that is nearest to the specified x pixel coordinate.
getXIndexOf | Layer | Gets the data point index at the specified x data value.
getXPosition | Layer | Gets the x positional value of a data point, as measured on the primary x-axis.
xZoneColor | Layer | Creates an x-zone color. An 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.
moveFront | Layer | Moves the layer in front of another layer.
moveBack | Layer | Moves the layer behind another layer.
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

public void setBarGap(double barGap [, double 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

public void setBarWidth(int barWidth [, int 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

public void setOverlapRatio(double overlapRatio [, boolean 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 | If this value is true, 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, then the overlapping order will be reversed.

Return Value

None


BarLayer.setBarShape

BarLayer.setBarShape

Usage

public void setBarShape(int shape [, int dataGroup [, int 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. -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. -1 means the shape applies to all data points.

Return Value

None


BarLayer.setBarShape2

BarLayer.setBarShape2

Usage

public void setBarShape2(int[] shape [, int dataGroup [, int 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. -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. -1 means the shape applies to all data points.

Return Value

None


BarLayer.setMinLabelSize

BarLayer.setMinLabelSize

Usage

public void setMinLabelSize(int size)

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
size | (Mandatory) | The minimum length of the bar segments in pixels, below which data labels will be hidden.

Return Value

None


BarLayer.setMinImageMapSize

BarLayer.setMinImageMapSize

Usage

public void setMinImageMapSize(int size)

Description

Sets the minimum height (or width if the x-axis and y-axis are swapped with XYChart.swapXY) of the hot spots defined by the image map.

By default, the hot spots defined by image map exactly cover the bars. For very short bars, the hot spots may be very small, and it may become difficult to move the mouse over the hot spots.

This method ensures the hot spots are at least of certain size, even if the bars are shorter. The default is 5 pixels.

Arguments

Argument | Default | Description
size | (Mandatory) | The minimum height (or width if the x-axis and y-axis are swapped with XYChart.swapXY) of the hot spots defined by the image map.

Return Value

None


BarLayer.setIconSize

BarLayer.setIconSize

Usage

public void setIconSize(int height [, int 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 regardless of 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. -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
setFastLineMode | (Self) | Enables or disables fast line mode.
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 lighting effect for the data representation.
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.
getLegendIcon | Layer | Gets the CDML representation of the legend icon for a data set.
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 a DataSet object based on the order in which it is being added to the chart.
getDataSetByZ | Layer | Gets a DataSet object based on the order in which it is being drawn.
getDataSetCount | Layer | Gets the number of data sets in the layer.
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.
setBaseLine | Layer | Sets the baseline for the data representation.
alignLayer | Layer | Aligns the layer with a data set of another bar chart layer in Side layout.
getXCoor | Layer | Gets the x pixel coordinate given the x data value.
getYCoor | Layer | Gets the y pixel coordinate given the y data value.
getNearestXValue | Layer | Gets the x data value that is nearest to the specified x pixel coordinate.
getXIndexOf | Layer | Gets the data point index at the specified x data value.
getXPosition | Layer | Gets the x positional value of a data point, as measured on the primary x-axis.
xZoneColor | Layer | Creates an x-zone color. An 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.
moveFront | Layer | Moves the layer in front of another layer.
moveBack | Layer | Moves the layer behind another layer.
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.setFastLineMode

LineLayer.setFastLineMode

Usage

public void setFastLineMode([ boolean b ])

Description

Enables or disables fast line mode.

In a chart, the plot area width is usually a few hundred to around 2000 pixels. For a line chart that "flows" horizontally (eg. from left to right), if there are a lot more data points (eg. 100000 data points than the plot area pixel width, many of the points would be at the same x-pixel coordinates. The line segments joining the data points at the same x-pixel coordinates would just be oscillating up and down, overlapping themselves. What is visible at each x-pixel position is essentially a line joining the minimum point and the maximum point.

In fast line mode, ChartDirector will automatically detect that there are too many points in the same x-pixel coordinate, and draws only a line segment joining the extreme points at that coordinate. The resulting line is visually indistinguishable from a line in which the line segments join all data points. The fast line mode can significantly reduce the number of points drawn without affecting the chart appearance.

The fast line mode has no effect if there are not significantly more data points than the pixel width of the plot area. For charts with evenly spaced data points, the fast line mode would only act on x-pixel positions with too many data points. Thus the fast line mode can be enabled on line charts regardless of the number of data points.

The fast line mode should not be used if the data points are not flowing horizontally (or vertically if XYChart.swapXY is in effect), but are flowing in random directions.

Arguments

Argument | Default | Description
b | true | A true value enables fast line mode. A false value disables fast line mode.

Return Value

None


LineLayer.setSymbolScale

LineLayer.setSymbolScale

Usage

public void setSymbolScale(double[] zDataX [, int scaleTypeX [, double[] zDataY [, int 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

public void setGapColor(int lineColor [, int 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

public void setImageMapWidth(int 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

public LineObj getLine([ int 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 LineLayer.

SplineLayer objects are created by using XYChart.addSplineLayer.

Method | Inherited | Description
setMonotonicity | (Self) | Sets the monotonicity constraint when computing the spline curve.
setTension | (Self) | Sets the tension to use when computing the spline curve.
setFastLineMode | LineLayer | Enables or disables fast line mode.
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 lighting effect for the data representation.
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.
getLegendIcon | Layer | Gets the CDML representation of the legend icon for a data set.
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 a DataSet object based on the order in which it is being added to the chart.
getDataSetByZ | Layer | Gets a DataSet object based on the order in which it is being drawn.
getDataSetCount | Layer | Gets the number of data sets in the layer.
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.
setBaseLine | Layer | Sets the baseline for the data representation.
alignLayer | Layer | Aligns the layer with a data set of another bar chart layer in Side layout.
getXCoor | Layer | Gets the x pixel coordinate given the x data value.
getYCoor | Layer | Gets the y pixel coordinate given the y data value.
getNearestXValue | Layer | Gets the x data value that is nearest to the specified x pixel coordinate.
getXIndexOf | Layer | Gets the data point index at the specified x data value.
getXPosition | Layer | Gets the x positional value of a data point, as measured on the primary x-axis.
xZoneColor | Layer | Creates an x-zone color. An 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.
moveFront | Layer | Moves the layer in front of another layer.
moveBack | Layer | Moves the layer behind another layer.
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.setMonotonicity

SplineLayer.setMonotonicity

Usage

public void setMonotonicity(int monotonicMode)

Description

Sets the monotonicity constraint when computing the spline curve.

Monotonicity means a sequence is increasing or decreasing in one direction. For example, the sequence 1, 2, 3, 4 is monotonically increasing, while the sequence 1, 3, 2, 5, 4 is not monotonic.

A standard spline curve can overshoot or undershoot if the underlying points have "sharp corners". That means without any constrain, even if the data points are monotonic, the spline curve joining the points is not necessarily monotonic. It can overshoot and then "fall back".

In many charts, it may be desirable to constraint the spline curve to flow in a certain direction. For example, in a time based chart, it may be desirable to constraint the curve always flow from left to right.

ChartDirector supports the following monotonic modes.

Constant | Value | Description
MonotonicNone | 0 | The spline curve is not constraint to flow in any direction. This results in the smoothest spline curve.
MonotonicX | 1 | The spline curve is constraint to not overshooting or undershooting in the x-axis direction. This means if the data points are monotonic in the x-axis direction, the spline curve will also be monotonic in the x-axis direction.
MonotonicY | 2 | The spline curve is constraint to not overshooting or undershooting in the y-axis direction. This means if the data points are monotonic in the y-axis direction, the spline curve will also be monotonic in the y-axis direction.
MonotonicXY | 3 | The spline curve is constraint to not overshooting or undershooting in both the x-axis and the y-axis directions. This means if the data points are monotonic in the x-axis direction, the spline curve will also be monotonic in the x-axis direction. If the data points are monotonic in the y-axis direction, the spline curve will also be monotonic in the y-axis direction.
MonotonicAuto | 4 | Automatically choose between MonotonicX, MonotonicY or MonotonicXY, depending on whether the data points are monotonic in the x-axis direction, or y-axis direction, or both.

Arguments

Argument | Default | Description
monotonicMode | (Mandatory) | The monotonic constraint of the spline curve. Must be be one of the constants in the above table. If this method is never called for a spline layer, the default is MonotonicAuto.

Return Value

None


SplineLayer.setTension

SplineLayer.setTension

Usage

public void setTension(double 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.
setFastLineMode | LineLayer | Enables or disables fast line mode.
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 lighting effect for the data representation.
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.
getLegendIcon | Layer | Gets the CDML representation of the legend icon for a data set.
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 a DataSet object based on the order in which it is being added to the chart.
getDataSetByZ | Layer | Gets a DataSet object based on the order in which it is being drawn.
getDataSetCount | Layer | Gets the number of data sets in the layer.
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.
setBaseLine | Layer | Sets the baseline for the data representation.
alignLayer | Layer | Aligns the layer with a data set of another bar chart layer in Side layout.
getXCoor | Layer | Gets the x pixel coordinate given the x data value.
getYCoor | Layer | Gets the y pixel coordinate given the y data value.
getNearestXValue | Layer | Gets the x data value that is nearest to the specified x pixel coordinate.
getXIndexOf | Layer | Gets the data point index at the specified x data value.
getXPosition | Layer | Gets the x positional value of a data point, as measured on the primary x-axis.
xZoneColor | Layer | Creates an x-zone color. An 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.
moveFront | Layer | Moves the layer in front of another layer.
moveBack | Layer | Moves the layer behind another layer.
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

public void setAlignment(int 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 regression analysis on the data points. It draws the optimal line or curve that fits the data points, with optional confidence and prediction bands.

In regression analysis, a function with some unknown coefficients is chosen first. The "method of least square" is used to estimate the coefficients, so that the function optimally fit the data points.

In the most common case, the function chosen is a linear function with unknown slope and intercept (the unknown coefficients). Linear regression is used to determine the slope and intercept such that the line optimally fit the data points.

The regression type supported by ChartDirector are listed below. They can be chosen using TrendLayer.setRegressionType. The default regression type is linear regression.

Regression Type | Description
Linear | y = a0 + a1x
Constrained Linear | y = a1x
Polynomial | y = Σanxn
Exponential | y = ea0 + a1x
Logarithmic | y = a0 + a1log(x)

The coefficients estimated by regression analysis are based on available data. They may be not equal to the "real" values, which are unknown. In ChartDirector, the uncertainties can be represented visually as a confidence band around the regression line or curve. For example, the 95% confidence band means there are 95% probability that the real line or curve is in that band. Confidence bands can be added to the chart using TrendLayer.addConfidenceBand.

Even if the regression line or curve is known with 100% accuracy, a given data point may still not lie exactly on the curve or line. It is because there can be noise in the data. The prediction band is the region that the data points are likely to be found. For example, a 95% prediction band means there are 95% probability that a data point will be in that band. Prediction bands can be added to the chart using TrendLayer.addPredictionBand.

A prediction band is always wider or the same as a confidence band of the same probability. It is because the uncertainties of the data point are due to both the uncertainties of the regression line or curve and the noise.

Method | Inherited | Description
setRegressionType | (Self) | Sets the regression type to be used.
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. The method is only defined if the regression type is linear or constrained linear.
getIntercept | (Self) | Gets the y-axis intercept of the trend line. The method is only defined if the regression type is linear.
getCoefficient | (Self) | Gets the coefficients of the regression function.
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 lighting effect for the data representation.
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.
getLegendIcon | Layer | Gets the CDML representation of the legend icon for a data set.
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 a DataSet object based on the order in which it is being added to the chart.
getDataSetByZ | Layer | Gets a DataSet object based on the order in which it is being drawn.
getDataSetCount | Layer | Gets the number of data sets in the layer.
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.
setBaseLine | Layer | Sets the baseline for the data representation.
alignLayer | Layer | Aligns the layer with a data set of another bar chart layer in Side layout.
getXCoor | Layer | Gets the x pixel coordinate given the x data value.
getYCoor | Layer | Gets the y pixel coordinate given the y data value.
getNearestXValue | Layer | Gets the x data value that is nearest to the specified x pixel coordinate.
getXIndexOf | Layer | Gets the data point index at the specified x data value.
getXPosition | Layer | Gets the x positional value of a data point, as measured on the primary x-axis.
xZoneColor | Layer | Creates an x-zone color. An 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.
moveFront | Layer | Moves the layer in front of another layer.
moveBack | Layer | Moves the layer behind another layer.
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.setRegressionType

TrendLayer.setRegressionType

Usage

public void setRegressionType(int regressionType)

Description

Sets the regression type to be used.

Please refer to the description of TrendLayer for the supported regression types.

Arguments

Argument | Default | Description
regressionType | (Mandatory) | Must be one of the constants LinearRegression, ConstrainedLinearRegression, ExponentialRegression and LogarithmicRegression, or the return value of Chart.PolynomialRegression. They represent linear regression, constrained linear regression, exponential regression, logarithmic regression, and polynomial regression of configurable degree.

Return Value

None


TrendLayer.addConfidenceBand

TrendLayer.addConfidenceBand

Usage

public void addConfidenceBand(double confidence, int upperFillColor [, int upperEdgeColor [, int upperLineWidth [, int lowerFillColor [, int lowerEdgeColor [, int 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

public void addPredictionBand(double confidence, int upperFillColor [, int upperEdgeColor [, int upperLineWidth [, int lowerFillColor [, int lowerEdgeColor [, int 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

public double getSlope()

Description

Gets the slope of the trend line. The method is only defined if the regression type is linear or constrained linear.

Arguments

None

Return Value

The slope of the linear or constrained linear trend line.


TrendLayer.getIntercept

TrendLayer.getIntercept

Usage

public double getIntercept()

Description

Gets the y-axis intercept of the trend line. The method is only defined if the regression type is linear.

Arguments

None

Return Value

The y-axis intercept of the linear trend line.


TrendLayer.getCoefficient

TrendLayer.getCoefficient

Usage

public double getCoefficient(int i)

Description

Gets the coefficients of the regression function.

The coefficients depend on the regression type. They are indexed as a0, a1, a2, ... in the regression type table published on TrendLayer.

Arguments

Argument | Default | Description
i | (Mandatory) | The index of the coefficient to get.

Return Value

The coefficient ai in the regression function.


TrendLayer.getCorrelation

TrendLayer.getCorrelation

Usage

public double getCorrelation()

Description

Gets the correlation coefficient of the trend line.

Arguments

None

Return Value

The correlation coefficient of the trend line.


TrendLayer.getStdError

TrendLayer.getStdError

Usage

public double getStdError()

Description

Gets the standard error of the trend line.

Arguments

None

Return Value

The standard error of the trend line.


TrendLayer.setImageMapWidth

TrendLayer.setImageMapWidth

Usage

public void setImageMapWidth(int 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

public LineObj 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 lighting effect for the data representation.
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.
getLegendIcon | Layer | Gets the CDML representation of the legend icon for a data set.
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 a DataSet object based on the order in which it is being added to the chart.
getDataSetByZ | Layer | Gets a DataSet object based on the order in which it is being drawn.
getDataSetCount | Layer | Gets the number of data sets in the layer.
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.
setBaseLine | Layer | Sets the baseline for the data representation.
alignLayer | Layer | Aligns the layer with a data set of another bar chart layer in Side layout.
getXCoor | Layer | Gets the x pixel coordinate given the x data value.
getYCoor | Layer | Gets the y pixel coordinate given the y data value.
getNearestXValue | Layer | Gets the x data value that is nearest to the specified x pixel coordinate.
getXIndexOf | Layer | Gets the data point index at the specified x data value.
getXPosition | Layer | Gets the x positional value of a data point, as measured on the primary x-axis.
xZoneColor | Layer | Creates an x-zone color. An 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.
moveFront | Layer | Moves the layer in front of another layer.
moveBack | Layer | Moves the layer behind another layer.
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

public void setGapColor(int gapColor12 [, int 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. -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
setFastLineMode | LineLayer | Enables or disables fast line mode.
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 lighting effect for the data representation.
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.
getLegendIcon | Layer | Gets the CDML representation of the legend icon for a data set.
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 a DataSet object based on the order in which it is being added to the chart.
getDataSetByZ | Layer | Gets a DataSet object based on the order in which it is being drawn.
getDataSetCount | Layer | Gets the number of data sets in the layer.
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.
setBaseLine | Layer | Sets the baseline for the data representation.
alignLayer | Layer | Aligns the layer with a data set of another bar chart layer in Side layout.
getXCoor | Layer | Gets the x pixel coordinate given the x data value.
getYCoor | Layer | Gets the y pixel coordinate given the y data value.
getNearestXValue | Layer | Gets the x data value that is nearest to the specified x pixel coordinate.
getXIndexOf | Layer | Gets the data point index at the specified x data value.
getXPosition | Layer | Gets the x positional value of a data point, as measured on the primary x-axis.
xZoneColor | Layer | Creates an x-zone color. An 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.
moveFront | Layer | Moves the layer in front of another layer.
moveBack | Layer | Moves the layer behind another layer.
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 the x-axis and y-axis are swapped with XYChart.swapXY) 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 lighting effect for the data representation.
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.
getLegendIcon | Layer | Gets the CDML representation of the legend icon for a data set.
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 a DataSet object based on the order in which it is being added to the chart.
getDataSetByZ | Layer | Gets a DataSet object based on the order in which it is being drawn.
getDataSetCount | Layer | Gets the number of data sets in the layer.
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.
setBaseLine | Layer | Sets the baseline for the data representation.
alignLayer | Layer | Aligns the layer with a data set of another bar chart layer in Side layout.
getXCoor | Layer | Gets the x pixel coordinate given the x data value.
getYCoor | Layer | Gets the y pixel coordinate given the y data value.
getNearestXValue | Layer | Gets the x data value that is nearest to the specified x pixel coordinate.
getXIndexOf | Layer | Gets the data point index at the specified x data value.
getXPosition | Layer | Gets the x positional value of a data point, as measured on the primary x-axis.
xZoneColor | Layer | Creates an x-zone color. An 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.
moveFront | Layer | Moves the layer in front of another layer.
moveBack | Layer | Moves the layer behind another layer.
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

public void setGapColor(int 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

public void setMinLabelSize(int size)

Description

Sets the minimum height (or width if the x-axis and y-axis are swapped with XYChart.swapXY) 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 the x- axis and y-axis are swapped with XYChart.swapXY) 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
size | (Mandatory) | The minimum height (or width if the x-axis and y-axis are swapped with XYChart.swapXY) 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.
setMinImageMapSize | (Self) | Sets the minimum height (or width if the x-axis and y-axis are swapped with XYChart.swapXY) of the hot spots defined by the image map.
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 lighting effect for the data representation.
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.
getLegendIcon | Layer | Gets the CDML representation of the legend icon for a data set.
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 a DataSet object based on the order in which it is being added to the chart.
getDataSetByZ | Layer | Gets a DataSet object based on the order in which it is being drawn.
getDataSetCount | Layer | Gets the number of data sets in the layer.
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.
setBaseLine | Layer | Sets the baseline for the data representation.
alignLayer | Layer | Aligns the layer with a data set of another bar chart layer in Side layout.
getXCoor | Layer | Gets the x pixel coordinate given the x data value.
getYCoor | Layer | Gets the y pixel coordinate given the y data value.
getNearestXValue | Layer | Gets the x data value that is nearest to the specified x pixel coordinate.
getXIndexOf | Layer | Gets the data point index at the specified x data value.
getXPosition | Layer | Gets the x positional value of a data point, as measured on the primary x-axis.
xZoneColor | Layer | Creates an x-zone color. An 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.
moveFront | Layer | Moves the layer in front of another layer.
moveBack | Layer | Moves the layer behind another layer.
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

public void setDataGap(double 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

public void setDataWidth(int 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


BaseBoxLayer.setMinImageMapSize

BaseBoxLayer.setMinImageMapSize

Usage

public void setMinImageMapSize(int size)

Description

Sets the minimum height (or width if the x-axis and y-axis are swapped with XYChart.swapXY) of the hot spots defined by the image map.

By default, the hot spots defined by image map exactly cover the symbols. For very short symbols, the hot spots may be very small, and it may become difficult to move the mouse over the hot spots.

This method ensures the hot spots are at least of certain size, even if the symbols are shorter. The default is 5 pixels.

Arguments

Argument | Default | Description
size | (Mandatory) | The minimum height (or width if the x-axis and y-axis are swapped with XYChart.swapXY) of the hot spots defined by the image map.

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.
setMinImageMapSize | BaseBoxLayer | Sets the minimum height (or width if the x-axis and y-axis are swapped with XYChart.swapXY) of the hot spots defined by the image map.
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 lighting effect for the data representation.
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.
getLegendIcon | Layer | Gets the CDML representation of the legend icon for a data set.
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 a DataSet object based on the order in which it is being added to the chart.
getDataSetByZ | Layer | Gets a DataSet object based on the order in which it is being drawn.
getDataSetCount | Layer | Gets the number of data sets in the layer.
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.
setBaseLine | Layer | Sets the baseline for the data representation.
alignLayer | Layer | Aligns the layer with a data set of another bar chart layer in Side layout.
getXCoor | Layer | Gets the x pixel coordinate given the x data value.
getYCoor | Layer | Gets the y pixel coordinate given the y data value.
getNearestXValue | Layer | Gets the x data value that is nearest to the specified x pixel coordinate.
getXIndexOf | Layer | Gets the data point index at the specified x data value.
getXPosition | Layer | Gets the x positional value of a data point, as measured on the primary x-axis.
xZoneColor | Layer | Creates an x-zone color. An 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.
moveFront | Layer | Moves the layer in front of another layer.
moveBack | Layer | Moves the layer behind another layer.
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

public void setColorMethod(int colorMethod, int riseColor [, int fallColor [, double 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. -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.
setMinImageMapSize | BaseBoxLayer | Sets the minimum height (or width if the x-axis and y-axis are swapped with XYChart.swapXY) of the hot spots defined by the image map.
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 lighting effect for the data representation.
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.
getLegendIcon | Layer | Gets the CDML representation of the legend icon for a data set.
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 a DataSet object based on the order in which it is being added to the chart.
getDataSetByZ | Layer | Gets a DataSet object based on the order in which it is being drawn.
getDataSetCount | Layer | Gets the number of data sets in the layer.
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.
setBaseLine | Layer | Sets the baseline for the data representation.
alignLayer | Layer | Aligns the layer with a data set of another bar chart layer in Side layout.
getXCoor | Layer | Gets the x pixel coordinate given the x data value.
getYCoor | Layer | Gets the y pixel coordinate given the y data value.
getNearestXValue | Layer | Gets the x data value that is nearest to the specified x pixel coordinate.
getXIndexOf | Layer | Gets the data point index at the specified x data value.
getXPosition | Layer | Gets the x positional value of a data point, as measured on the primary x-axis.
xZoneColor | Layer | Creates an x-zone color. An 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.
moveFront | Layer | Moves the layer in front of another layer.
moveBack | Layer | Moves the layer behind another layer.
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.
setMinImageMapSize | BaseBoxLayer | Sets the minimum height (or width if the x-axis and y-axis are swapped with XYChart.swapXY) of the hot spots defined by the image map.
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 lighting effect for the data representation.
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.
getLegendIcon | Layer | Gets the CDML representation of the legend icon for a data set.
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 a DataSet object based on the order in which it is being added to the chart.
getDataSetByZ | Layer | Gets a DataSet object based on the order in which it is being drawn.
getDataSetCount | Layer | Gets the number of data sets in the layer.
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.
setBaseLine | Layer | Sets the baseline for the data representation.
alignLayer | Layer | Aligns the layer with a data set of another bar chart layer in Side layout.
getXCoor | Layer | Gets the x pixel coordinate given the x data value.
getYCoor | Layer | Gets the y pixel coordinate given the y data value.
getNearestXValue | Layer | Gets the x data value that is nearest to the specified x pixel coordinate.
getXIndexOf | Layer | Gets the data point index at the specified x data value.
getXPosition | Layer | Gets the x positional value of a data point, as measured on the primary x-axis.
xZoneColor | Layer | Creates an x-zone color. An 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.
moveFront | Layer | Moves the layer in front of another layer.
moveBack | Layer | Moves the layer behind another layer.
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

public void setBoxColor(int item, int 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

public void setBoxColors(int[] colors [, String[] 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

public void setWhiskerBrightness(double 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.
setVectorMargin | (Self) | Sets the margins to shorten the vectors.
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 lighting effect for the data representation.
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.
getLegendIcon | Layer | Gets the CDML representation of the legend icon for a data set.
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 a DataSet object based on the order in which it is being added to the chart.
getDataSetByZ | Layer | Gets a DataSet object based on the order in which it is being drawn.
getDataSetCount | Layer | Gets the number of data sets in the layer.
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.
setBaseLine | Layer | Sets the baseline for the data representation.
alignLayer | Layer | Aligns the layer with a data set of another bar chart layer in Side layout.
getXCoor | Layer | Gets the x pixel coordinate given the x data value.
getYCoor | Layer | Gets the y pixel coordinate given the y data value.
getNearestXValue | Layer | Gets the x data value that is nearest to the specified x pixel coordinate.
getXIndexOf | Layer | Gets the data point index at the specified x data value.
getXPosition | Layer | Gets the x positional value of a data point, as measured on the primary x-axis.
xZoneColor | Layer | Creates an x-zone color. An 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.
moveFront | Layer | Moves the layer in front of another layer.
moveBack | Layer | Moves the layer behind another layer.
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

public void setVector(double[] lengths, double[] directions [, int lengthScale ])

Description

Sets the lengths and directions for the vectors.

ChartDirector supports specifying the vector lengths and directions directly, or indirectly as the lengths and directions from the reference points to the reference end points. This is controlled by lengthScale as described in the following table.

Constant | Value | Description
PixelScale | 0 | The lengths are measured in pixels. The angles are measured clockwise in degrees, with the upwards position as 0.
XAxisScale | 1 | The lengths are measured in x-axis scale. The angles are measured clockwise in degrees, with the upwards position as 0.
YAxisScale | 2 | The lengths are measured in y-axis scale. The angles are measured clockwise in degrees, with the upwards position as 0.
EndPoints | 3 | The vector lengths and directions are measured as the lengths and directions between the reference points and the reference end points.

Arguments

Argument | Default | Description
lengths | (Mandatory) | An array of numbers representing either the lengths of the vectors or the x coordinates of the reference end points, depending on lengthScale.
directions | (Mandatory) | An array of numbers representing either the directions of the vectors or the y coordinates of the reference end points, depending on lengthScale.
lengthScale | PixelScale | The method to specify vector lengths and directions, which must be one of the predefined constants in the table above.

Return Value

None


VectorLayer.setArrowHead

VectorLayer.setArrowHead

Usage

public void setArrowHead(int width [, int 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. 0 means the height is the same as the width.

Return Value

None


VectorLayer.setArrowHead2

VectorLayer.setArrowHead2

Usage

public void setArrowHead2(int[] 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

public void setArrowStem(int[] 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

public void setArrowAlignment(int 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.setVectorMargin

VectorLayer.setVectorMargin

Usage

public void setVectorMargin(double startMargin [, double endMargin ])

Description

Sets the margins to shorten the vectors.

By default, vectors will be drawn from the given start points to the given end points.

In some cases, it may be desirable to shorten the vectors so that they do not start exactly at the start points and/or end exactly at the end points. For example, the vectors may be used to point to some circular symbols created by a ScatterLayer. The vectors may need to point to the perimeter of the circles, rather than their centers. This can be achieved by shortening the vectors by the radius of the circles.

Arguments

Argument | Default | Description
startMargin | (Mandatory) | The length to shorten at the start of the vector in pixels.
endMargin | NoValue | The length to shorten at the end of the vector in pixels. NoValue means the length is the same as startMargin.

Return Value

None


VectorLayer.setIconSize

VectorLayer.setIconSize

Usage

public void setIconSize(int height [, int 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. 0 means the width is automatically determined.

Return Value

None


ContourLayer

ContourLayer

The ContourLayer class represents contour layers. ContourLayer is a subclass of Layer.

ContourLayer objects are created by using XYChart.addContourLayer.

The data for the ContourLayer are the z values at some points in the xy plane. Both gridded and scattered data points are supported.

Using the data, the ContourLayer computes the z values of all pixels in the xy plane. The computation can be based on spline or bilinear/line surface fitting, configurable using ContourLayer.setSmoothInterpolation.

The ContourLayer then colors the pixels based on the z values, and draws contour lines to join positions with the same z values. The color mapping and contour levels are controlled by the ColorAxis object of the ContourLayer, obtainable using ContourLayer.colorAxis.

Method | Inherited | Description
setZData | (Self) | Sets the z data used for the contour chart.
setColorAxis | (Self) | Sets the position, length and orientation of the color axis (color legend).
colorAxis | (Self) | Gets the ColorAxis object representing the color axis (color legend).
setSmoothInterpolation | (Self) | Sets whether to use spline or bilinear/linear surface interpolation.
setZBounds | (Self) | Clips the z values to the given bounds.
setContourColor | (Self) | Sets contour line colors.
setContourWidth | (Self) | Sets contour line widths.
setExactContour | (Self) | Sets whether to use exact contours or boundary contours.
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 lighting effect for the data representation.
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.
getLegendIcon | Layer | Gets the CDML representation of the legend icon for a data set.
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 a DataSet object based on the order in which it is being added to the chart.
getDataSetByZ | Layer | Gets a DataSet object based on the order in which it is being drawn.
getDataSetCount | Layer | Gets the number of data sets in the layer.
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.
setBaseLine | Layer | Sets the baseline for the data representation.
alignLayer | Layer | Aligns the layer with a data set of another bar chart layer in Side layout.
getXCoor | Layer | Gets the x pixel coordinate given the x data value.
getYCoor | Layer | Gets the y pixel coordinate given the y data value.
getNearestXValue | Layer | Gets the x data value that is nearest to the specified x pixel coordinate.
getXIndexOf | Layer | Gets the data point index at the specified x data value.
getXPosition | Layer | Gets the x positional value of a data point, as measured on the primary x-axis.
xZoneColor | Layer | Creates an x-zone color. An 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.
moveFront | Layer | Moves the layer in front of another layer.
moveBack | Layer | Moves the layer behind another layer.
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.


ContourLayer.setZData

ContourLayer.setZData

Usage

public void setZData(double[] zData)

Description

Sets the z data used for the contour chart.

Arguments

Argument | Default | Description
zData | (Mandatory) | An array of numbers as the z data for the contour chart.

Return Value

None


ContourLayer.setColorAxis

ContourLayer.setColorAxis

Usage

public ColorAxis setColorAxis(int x, int y, int alignment, int length, int orientation)

Description

Sets the position, length and orientation of the color axis (color legend).

Arguments

Argument | Default | Description
x | (Mandatory) | The x-coordinate of the reference point used to position the color axis.
y | (Mandatory) | The y-coordinate of the reference point used to position the color axis.
alignment | (Mandatory) | The alignment of the color axis with respect to the reference point. For example, a value of TopLeft means the reference point is the top- left corner of the color axis. See Alignment Specification for supported alignment types..
length | (Mandatory) | The length of the color axis in pixels.
orientation | (Mandatory) | The orientation of the color axis. A value of Top/Bottom means the axis is horizontal, and the axis labels are at top/bottom side of the axis. A value of Left/Right means the axis is vertical, and the axis labels are at the left/right side of the axis.

Return Value

None


ContourLayer.colorAxis

ContourLayer.colorAxis

Usage

public ColorAxis colorAxis()

Description

Gets the ColorAxis object representing the color axis (color legend).

Arguments

None

Return Value

The ColorAxis object representing the color axis.


ContourLayer.setSmoothInterpolation

ContourLayer.setSmoothInterpolation

Usage

public void setSmoothInterpolation(boolean b)

Description

Sets whether to use spline or bilinear/linear surface interpolation.

The data points for the contour layer are samples of the z values at certain gridded or scattered (x, y) points. However, to draw the contour and to color the layer, it is necessarily to know the z values at all pixels in the xy plane. ChartDirector uses surface interpolation to compute the z values at all pixels from the given data points.

In spline surface interpolation, ChartDirector will compute a smooth surface that passes through all data points. In bilinear/linear surface interpolation, ChartDirector will use the data points to partition the (x, y) plane into rectangular or triangular regions, and will fit bilinear or linear surfaces to the regions.

Spline surface interpolation generally produces smoother contours and is the default.

Arguments

Argument | Default | Description
b | (Mandatory) | A true value means to use spline surface interpolation. A false value means to use bilinear/linear surface interpolation.

Return Value

None


ContourLayer.setZBounds

ContourLayer.setZBounds

Usage

public void setZBounds([ double minZ [, double maxZ ]])

Description

Clips the z values to the given bounds.

In spline surface interpolation (see ContourLayer.setSmoothInterpolation), it is possible that the interpolated surface contains regions that are higher than the highest data point, or lower than the lowest data point.

As an example, consider a linear sequence of points with z values [10, 20, 30, 40, 40, 30, 20, 10]. The first 4 points represent an upward slope, while the last 4 points represent a download slope. If these points are to be joined with a smooth spline, the peak will naturally fall somewhere between the middle two points and exceed 40. So there will be a region in the spline higher than the highest data point.

In some applications, it may be desirable to limit the z values to certain bounds. For example, if the data are about rainfall, it is not desirable if the interpolated surface falls below 0, as there cannot be negative rainfall. The setZBounds method can be used to clip the interpolated surface to the desired bounds.

Arguments

Argument | Default | Description
minZ | DataBound | The minimum z value to clip to. Use NoValue if there is no minimum z bound. The special constant DataBound means that the minimum z value is the minimum data value.
maxZ | DataBound | The maximum z value to clip to. Use NoValue if there is no maximum z bound. The special constant DataBound means that the maximum z value is the maximum data value.

Return Value

None


ContourLayer.setContourColor

ContourLayer.setContourColor

Usage

public void setContourColor(int contourColor [, int minorContourColor ])

Description

Sets contour line colors.

Arguments

Argument | Default | Description
contourColor | (Mandatory) | The major contour line color. If this method is never called, the default contour line color is semi-transparent black (80000000).
minorContourColor | -1 | The minor contour line color. -1 means the minor contour line color is the same as the major contour line color.

Return Value

None


ContourLayer.setContourWidth

ContourLayer.setContourWidth

Usage

public void setContourWidth(int contourWidth [, int minorContourWidth ])

Description

Sets contour line widths.

Arguments

Argument | Default | Description
contourWidth | (Mandatory) | The major contour line width in pixels. If this method is never called, the default contour line width is 1 pixel.
minorContourWidth | -1 | The minor contour line width. -1 means the minor contour line width is the same as the major contour line width.

Return Value

None


ContourLayer.setExactContour

ContourLayer.setExactContour

Usage

public void setExactContour([ boolean contour [, boolean markContour ]])

Description

Sets whether to use exact contours or boundary contours.

In exact contour mode, the contour at z = N refers to all points at z = N. For example, the contour at z = 10 refers to all points at z = 10. These points normally constitute lines. However, in case there is an exactly flat region at z = 10, the entire region will be the contour and will be colored using the contour color. In other words, instead of lines, a contour can become a region.

In boundary contour mode, the contour at z = N refers to the boundary between z < N and z >= N, except for the highest contour in which case the contour is the boundary between z <= N and z > N. With this method, if there is a flat region, the contour will occur at the boundary of the region.

If this method is never called, the default is to use boundary contour mode.

Arguments

Argument | Default | Description
contour | true | A true value specifies exact contour mode for standard contours, otherwise boundary contour mode will be used.
markContour | [Same_As_Contour] | A true value specifies exact contour mode for mark contours. A false value specifies boundary contour mode for mark contours. A mark contour is an extra contour added using Axis.addMark on the color axis (obtained using ContourLayer.colorAxis). If this parameter is not specified, the default is to use the same contour mode as standard contours.

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.
getDataName | (Self) | Gets the name of the data set.
setDataColor | (Self) | Sets the colors used to draw the data set.
getDataColor | (Self) | Gets the main color 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.
getLegendIcon | (Self) | Gets the CDML representation of the legend icon for the data set.
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.
getUseYAxis | (Self) | Gets the y-axis to use when drawing the data set.
getValue | (Self) | Gets the value of a data point.
getPosition | (Self) | Gets the positional value of a data point.


DataSet.setDataName

DataSet.setDataName

Usage

public void setDataName(String 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.getDataName

DataSet.getDataName

Usage

public String getDataName()

Description

Gets the name of the data set.

Arguments

None

Return Value

The name of the data set.


DataSet.setDataColor

DataSet.setDataColor

Usage

public void setDataColor(int dataColor [, int edgeColor [, int shadowColor [, int 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.getDataColor

DataSet.getDataColor

Usage

public int getDataColor()

Description

Gets the main color used to draw the data set.

Arguments

None

Return Value

The main color used to draw the data set.


DataSet.setDataSymbol

DataSet.setDataSymbol

Usage

public void setDataSymbol(int symbol [, int size [, int fillColor [, int edgeColor [, int 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

public void setDataSymbol2(String 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

public void setDataSymbol3(DrawArea 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

public void setDataSymbol4(int[] polygon [, int size [, int fillColor [, int 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.getLegendIcon

DataSet.getLegendIcon

Usage

public String getLegendIcon()

Description

Gets the CDML representation of the legend icon for the data set.

The CDML representation can be used in any ChartDirector API that supports CDML. Note that the CDML representation is only valid in the BaseChart object that contains the data set. It is not allowed to use the CDML representation obtained from one chart in a different chart.

The legend icon is the same icon that would appear in the LegendBox. If you modify the icon using methods of the LegendBox object (such as using LegendBox.setKeyBorder to set the legend icon border), the modification will also apply to the icon returned by this method.

Arguments

None

Return Value

The CDML representation of the legend icon for the data set.


DataSet.setLineWidth

DataSet.setLineWidth

Usage

public void setLineWidth(int 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

public TextBox setDataLabelStyle([ String font [, double fontSize [, int fontColor [, double 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 data labels. This may be used to fine-tune the appearance of the data labels.


DataSet.setDataLabelFormat

DataSet.setDataLabelFormat

Usage

public void setDataLabelFormat(String 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

public void setUseYAxis(Axis 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

public void setUseYAxis2([ boolean 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 | A true value means the secondary y-axis will be used. A false value means the primary y-axis will be used.

Return Value

None


DataSet.getUseYAxis

DataSet.getUseYAxis

Usage

public Axis getUseYAxis()

Description

Gets the y-axis to use when drawing the data set.

Arguments

None

Return Value

An Axis object representing the y-axis to use when drawing the data set.


DataSet.getValue

DataSet.getValue

Usage

public double getValue(int i)

Description

Gets the value of a data point.

Arguments

Argument | Default | Description
i | (Mandatory) | The data point index of the data point. The first data point is 0; the nth data point is (n - 1).

Return Value

The value of the data point.


DataSet.getPosition

DataSet.getPosition

Usage

public double getPosition(int i)

Description

Gets the positional value of a data point.

The positional value is the value used to position the data point. Usually, the positional value is equal to the data value. However, for chart types in which the data sets are combined using the Stack or Percentage method, the positional value can be different from the data value. For example, for stacked charts, the positional value of a data point is equal to the accumulative value of the corresponding data points from data sets added before the target data set.

Arguments

Argument | Default | Description
i | (Mandatory) | The data point index of the data point. The first data point is 0; the nth data point is (n - 1).

Return Value

The positional value of the data point.


SurfaceChart

SurfaceChart

The SurfaceChart class represents surface charts. SurfaceChart is a subclass of ThreeDChart.

Method | Inherited | Description
SurfaceChart | (Self) | Creates a new SurfaceChart object.
setData | (Self) | Sets the data for the surface chart.
setInterpolation | (Self) | Enables and sets the degree and method of interpolation of the data points.
setShadingMode | (Self) | Sets the shading mode for the surface.
setLighting | (Self) | Sets the Phong lighting parameters for the front side of the surface.
setBackSideBrightness | (Self) | Sets the back side brightness as a ratio of the front side brightness.
setBackSideLighting | (Self) | Sets the Phong lighting parameters for the back side of the surface.
setBackSideColor | (Self) | Sets the color of the back side of the surface.
setSurfaceAxisGrid | (Self) | Sets the colors of the axis grid lines on the surface.
setSurfaceDataGrid | (Self) | Sets the colors of the data grid lines on the surface.
setContourColor | (Self) | Sets the colors of the contour lines on the surface.
setPlotRegion | ThreeDChart | Sets the position of the plot region.
setViewAngle | ThreeDChart | Sets the 3D view angles.
setPerspective | ThreeDChart | Sets the strength of the perspective effect.
xAxis | ThreeDChart | Retrieves the x-axis of the ThreeDChart object.
yAxis | ThreeDChart | Retrieves the y-axis of the ThreeDChart object.
zAxis | ThreeDChart | Retrieves the z-axis of the ThreeDChart object.
setColorAxis | ThreeDChart | Sets the position, length and orientation of the color axis (color legend).
colorAxis | ThreeDChart | Gets the ColorAxis object representing the color axis (color legend).
setWallVisibility | ThreeDChart | Shows or hides the plot region walls.
setWallColor | ThreeDChart | Sets the color of the plot region walls.
setWallThickness | ThreeDChart | Sets the thickness of the plot region walls.
setWallGrid | ThreeDChart | Sets the grid line colors on plot region walls.
setZAxisPos | ThreeDChart | Sets the position of the z-axis.
setSize | BaseChart | Sets the size of the chart, exclusive of the drop shadow (if any).
getWidth | BaseChart | Gets the width of the chart.
getHeight | BaseChart | Gets the height of the chart.
getAbsOffsetX | BaseChart | Gets the x offset of the chart relative to the outermost MultiChart container.
getAbsOffsetY | BaseChart | Gets the y offset of the chart relative to the outermost MultiChart container.
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.
setDropShadow | BaseChart | Adds a drop shadow to the chart.
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 file system search path for loading image files.
setSearchPath2 | BaseChart | Sets the ClassLoader for loading images.
setSearchPath3 | BaseChart | Search for image files using the ServletContext and ServletRequest.
setSearchPath4 | BaseChart | Search for image files using a URL as the base path.
setTransparentColor | BaseChart | Specifies a certain color to mean transparent when creating a raster 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.
addTable | BaseChart | Adds a CDML table 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.
adjustBrightness | BaseChart | Creates a color that is a darkened or brightened version of the given color.
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 axes (if any) and compute the positions of the various objects in the chart.
makeImage | BaseChart | Generates the chart as a java.awt.Image object.
enableVectorOutput | BaseChart | Enables true vector graphics output.
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.
initDynamicLayer | BaseChart | Initializes a dynamic layer for drawing text and shapes.
removeDynamicLayer | BaseChart | Removes the dynamic layer if any.
getHTMLImageMap | BaseChart | Generates an HTML image map for the chart.
getJsChartModel | BaseChart | Gets the Javascript Chart Model for passing to WebChartViewer.setChartModel for the purpose of supporting track cursors in a web application.
getChartMetrics | BaseChart | Gets the chart metrics for passing to WebChartViewer.setChartMetrics to support view ports for web applications.


SurfaceChart.SurfaceChart

SurfaceChart.SurfaceChart

Usage

public SurfaceChart(int width, int height [, int bgColor [, int edgeColor [, int raisedEffect ]]])

Description

Creates a new SurfaceChart 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 SurfaceChart object created.


SurfaceChart.setData

SurfaceChart.setData

Usage

public void setData(double[] xData, double[] yData, double[] zData)

Description

Sets the data for the surface chart.

ChartDirector supports both gridded and scattered data. If the data points are on a rectangular grid will no missing points, they will be handled as gridded data. Otherwise, they will be handled as scattered data.

For gridded data, you may provide the x and y values of the grid, and the z values of the data points. For a 10 x 15 grid, that means the x data series should have 10 values, the y data series should have 15 values, and the z data series should have 150 values. The x and y data series should be strictly monotonic (either strictly increasing or strictly decreasing).

For both gridded and scattered data, you may also provide the (x, y, z) values of the data points. For example, for 150 data points, the x, y and z data series should each have 150 values. ChartDirector will automatically detect if the data points are gridded or scattered.

Arguments

Argument | Default | Description
xData | (Mandatory) | An array of numbers representing the x data series.
yData | (Mandatory) | An array of numbers representing the y data series.
zData | (Mandatory) | An array of numbers representing the z data series.

Return Value

None


SurfaceChart.setInterpolation

SurfaceChart.setInterpolation

Usage

public void setInterpolation(int xSamples [, int ySamples [, boolean isSmooth ]])

Description

Enables and sets the degree and method of interpolation of the data points.

A surface chart consists of planar patches, drawn using the data points as the vertices. To create visually smooth surfaces, we may use a large number of small planar patches. However, this requires a large number of data points.

For example, consider a plot region of which the x and y dimensions are both 400 pixels in length. To create a smooth surface, if gridded data are used, the distance between grid lines should be no more than a few pixels. Suppose a grid spacing of 8 pixels is used. The grid size will be 51 x 51, and 2601 data points will be needed.

If the number of available data points are too small to create a smooth surface, This method can be used to generate a denser grid of data points from the original data points using interpolation.

Two types of interpolation are supported. In spline surface interpolation, ChartDirector will compute a smooth surface that passes through the original data points, and sample the spline surface for the new data points. In bilinear/linear interpolation, ChartDirector will apply bilinear/linear interpolation to its vertices of the original patches to compute the new data points.

Arguments

Argument | Default | Description
xSamples | (Mandatory) | The number of samples on the x-dimension to interpolate to.
ySamples | -1 | The number of samples on the y-dimension to interpolate to. -1 means it is the same as xSamples.
isSmooth | true | A true value means to use spline surface interpolation. A false value means to use bilinear/linear interpolation.

Return Value

None


SurfaceChart.setShadingMode

SurfaceChart.setShadingMode

Usage

public void setShadingMode(int shadingMode [, int wireWidth ])

Description

Sets the shading mode for the surface.

ChartDirector supports the following methods for shading the surface.

Constant | Value | Description
SmoothShading | 0 | The brightness of the surface varies smoothly.
TriangularShading | 0 | The surface is divided into triangular patches. The brightness of the patches varies according to their orientation. Within a patch, the brightness is constant.
RectangularShading | 0 | The surface is divided into rectangular patches. The brightness of the patches varies according to their orientation. Within a patch, the brightness is constant.
TriangularFrame | 0 | The surface is divided into triangular patches. Only the edges of the patches are drawn.
RectangularFrame | 0 | The surface is divided into rectangular patches. Only the edges of the patches are drawn.

Arguments

Argument | Default | Description
shadingMode | (Mandatory) | The shading mode, which must be one of the above constants.
wireWidth | 1 | The wire width for use with wireframe shading modes.

Return Value

None


SurfaceChart.setLighting

SurfaceChart.setLighting

Usage

public void setLighting(double ambientIntensity, double diffuseIntensity, double specularIntensity, double shininess)

Description

Sets the Phong lighting parameters for the front side of the surface.

The surface of a surface chart has two sides. The side that is facing the positive z direction of the plot region is the front side. The side that is facing the negative z direction of the plot region is the back side.

ChartDirector uses the Phong lighting model to adjust the brightness of the surface to make it look realistic. The light source is assumed to be from the direction of the viewer and is far away. The default lighting parameters for the front side are 0.5 for both ambient and diffuse reflections, 1 for specular reflection and 8 for shininess.

Arguments

Argument | Default | Description
ambientIntensity | (Mandatory) | The ambient reflection coefficient of the Phong lighting model.
diffuseIntensity | (Mandatory) | The diffuse reflection coefficient of the Phong lighting model.
specularIntensity | (Mandatory) | The specular reflection coefficient of the Phong lighting model.
shininess | (Mandatory) | The shininess coefficient of the Phong lighting model.

Return Value

None


SurfaceChart.setBackSideBrightness

SurfaceChart.setBackSideBrightness

Usage

public void setBackSideBrightness(double brightness)

Description

Sets the back side brightness as a ratio of the front side brightness.

The surface of a surface chart has two sides. The side that is facing the positive z direction of the plot region is the front side. The side that is facing the negative z direction of the plot region is the back side.

By default, the back side brightness is half the front side brightness. This method can be used to adjust the ratio.

Arguments

Argument | Default | Description
brightness | (Mandatory) | The ratio of the back side brightness to the front side brightness.

Return Value

None


SurfaceChart.setBackSideLighting

SurfaceChart.setBackSideLighting

Usage

public void setBackSideLighting(double ambientIntensity, double diffuseIntensity, double specularIntensity, double shininess)

Description

Sets the Phong lighting parameters for the back side of the surface.

The surface of a surface chart has two sides. The side that is facing the positive z direction of the plot region is the front side. The side that is facing the negative z direction of the plot region is the back side.

ChartDirector uses the Phong lighting model to adjust the brightness of the surface to make it look realistic. The default lighting parameters for the back side is half the brightness of those for the front side. This method may be used to set alternative lighting parameters for the back side.

Arguments

Argument | Default | Description
ambientIntensity | (Mandatory) | The ambient reflection coefficient of the Phong lighting model.
diffuseIntensity | (Mandatory) | The diffuse reflection coefficient of the Phong lighting model.
specularIntensity | (Mandatory) | The specular reflection coefficient of the Phong lighting model.
shininess | (Mandatory) | The shininess coefficient of the Phong lighting model.

Return Value

None


SurfaceChart.setBackSideColor

SurfaceChart.setBackSideColor

Usage

public void setBackSideColor(int color)

Description

Sets the color of the back side of the surface.

The surface of a surface chart has two sides. The side that is facing the positive z direction of the plot region is the front side. The side that is facing the negative z direction of the plot region is the back side.

By default, the back side is colored similar to the front side, but with different brightness of lighting parameters. This method can be used to color the back side with a fixed color instead.

Arguments

Argument | Default | Description
color | (Mandatory) | The color used for the back side.

Return Value

None


SurfaceChart.setSurfaceAxisGrid

SurfaceChart.setSurfaceAxisGrid

Usage

public void setSurfaceAxisGrid(int majorXGridColor [, int majorYGridColor [, int minorXGridColor [, int minorYGridColor ]]])

Description

Sets the colors of the axis grid lines on the surface.

Axis grid lines are grid lines associated with the ticks on the x and y axes. Major grid lines associate with major ticks. Minor grid lines associate with minor ticks. They can be drawn on the surface of the surface chart, and on the plot region walls. This method is for the surface of the surface chart. For the plot region walls, see ThreeDChart.setWallGrid.

Arguments

Argument | Default | Description
majorXGridColor | (Mandatory) | The color of the major x-axis grid lines on the surface.
majorYGridColor | -1 | The color of the major y-axis grid lines on the surface. -1 means it is the same as the majorXGridColor.
minorXGridColor | -1 | The color of the minor x-axis grid lines on the surface. -1 means it is the same as the majorXGridColor.
minorYGridColor | -1 | The color of the minor y-axis grid lines on the surface. -1 means it is the same as the majorYGridColor.

Return Value

None


SurfaceChart.setSurfaceDataGrid

SurfaceChart.setSurfaceDataGrid

Usage

public void setSurfaceDataGrid(int xGridColor [, int yGridColor ])

Description

Sets the colors of the data grid lines on the surface.

Data grid lines are grid lines that define the positions of the data points. They can be drawn on the surface of the surface chart.

Arguments

Argument | Default | Description
xGridColor | (Mandatory) | The color of the x data grid lines.
yGridColor | -1 | The color of the y data grid lines. -1 means it is the same as the yGridColor.

Return Value

None


SurfaceChart.setContourColor

SurfaceChart.setContourColor

Usage

public void setContourColor(int contourColor [, int minorContourColor ])

Description

Sets the colors of the contour lines on the surface.

The contour lines are lines that join regions of the same z value on the surface. The contour levels are determined by the ticks on the z-axis. Major ticks associate with major contour lines. Minor ticks associate with minor contour lines.

Arguments

Argument | Default | Description
contourColor | (Mandatory) | The color of the major contour lines.
minorContourColor | -1 | The color of the minor contour lines. -1 means it is the same as the contourColor.

Return Value

None


ThreeDScatterChart

ThreeDScatterChart

The ThreeDScatterChart class represents 3D scatter charts. ThreeDScatterChart is a subclass of ThreeDChart.

Method | Inherited | Description
ThreeDScatterChart | (Self) | Creates a new ThreeDScatterChart object.
addScatterGroup | (Self) | Adds a group of scatter symbols to the ThreeDScatterChart.
setPlotRegion | ThreeDChart | Sets the position of the plot region.
setViewAngle | ThreeDChart | Sets the 3D view angles.
setPerspective | ThreeDChart | Sets the strength of the perspective effect.
xAxis | ThreeDChart | Retrieves the x-axis of the ThreeDChart object.
yAxis | ThreeDChart | Retrieves the y-axis of the ThreeDChart object.
zAxis | ThreeDChart | Retrieves the z-axis of the ThreeDChart object.
setColorAxis | ThreeDChart | Sets the position, length and orientation of the color axis (color legend).
colorAxis | ThreeDChart | Gets the ColorAxis object representing the color axis (color legend).
setWallVisibility | ThreeDChart | Shows or hides the plot region walls.
setWallColor | ThreeDChart | Sets the color of the plot region walls.
setWallThickness | ThreeDChart | Sets the thickness of the plot region walls.
setWallGrid | ThreeDChart | Sets the grid line colors on plot region walls.
setZAxisPos | ThreeDChart | Sets the position of the z-axis.
setSize | BaseChart | Sets the size of the chart, exclusive of the drop shadow (if any).
getWidth | BaseChart | Gets the width of the chart.
getHeight | BaseChart | Gets the height of the chart.
getAbsOffsetX | BaseChart | Gets the x offset of the chart relative to the outermost MultiChart container.
getAbsOffsetY | BaseChart | Gets the y offset of the chart relative to the outermost MultiChart container.
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.
setDropShadow | BaseChart | Adds a drop shadow to the chart.
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 file system search path for loading image files.
setSearchPath2 | BaseChart | Sets the ClassLoader for loading images.
setSearchPath3 | BaseChart | Search for image files using the ServletContext and ServletRequest.
setSearchPath4 | BaseChart | Search for image files using a URL as the base path.
setTransparentColor | BaseChart | Specifies a certain color to mean transparent when creating a raster 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.
addTable | BaseChart | Adds a CDML table 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.
adjustBrightness | BaseChart | Creates a color that is a darkened or brightened version of the given color.
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 axes (if any) and compute the positions of the various objects in the chart.
makeImage | BaseChart | Generates the chart as a java.awt.Image object.
enableVectorOutput | BaseChart | Enables true vector graphics output.
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.
initDynamicLayer | BaseChart | Initializes a dynamic layer for drawing text and shapes.
removeDynamicLayer | BaseChart | Removes the dynamic layer if any.
getHTMLImageMap | BaseChart | Generates an HTML image map for the chart.
getJsChartModel | BaseChart | Gets the Javascript Chart Model for passing to WebChartViewer.setChartModel for the purpose of supporting track cursors in a web application.
getChartMetrics | BaseChart | Gets the chart metrics for passing to WebChartViewer.setChartMetrics to support view ports for web applications.


ThreeDScatterChart.ThreeDScatterChart

ThreeDScatterChart.ThreeDScatterChart

Usage

public ThreeDScatterChart(int width, int height [, int bgColor [, int edgeColor [, int raisedEffect ]]])

Description

Creates a new ThreeDScatterChart 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 ThreeDScatterChart object created.


ThreeDScatterChart.addScatterGroup

ThreeDScatterChart.addScatterGroup

Usage

public ThreeDScatterGroup addScatterGroup(double[] xData, double[] yData, double[] zData [, String name [, int symbol [, int symbolSize [, int fillColor [, int edgeColor ]]]]])

Description

Adds a group of scatter symbols to the ThreeDScatterChart.

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.
yData | (Mandatory) | An array of numbers representing the y values of the data points.
zData | (Mandatory) | An array of numbers representing the z values of the data points.
name | "" | The name of the symbol group. The name will be used in the legend box, if one is available. An empty string means the symbol group has no name.
symbol | CircleShape | 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. SameAsMainColor means the color is based on the z value of the symbol as according to the ColorAxis (accessible via ThreeDChart.colorAxis).
edgeColor | -1 | The edge color used to draw the edge of the symbol. -1 means using LineColor as the edge color.

Return Value

A ThreeDScatterGroup object representing the symbol group created.


ThreeDScatterGroup

ThreeDScatterGroup

The ThreeDScatterGroup class represents a group of scatter symbols in a ThreeDScatterChart object.

ThreeDScatterGroup objects are created by using ThreeDScatterChart.addScatterGroup.

Method | Inherited | Description
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.
setDropLine | (Self) | Sets the drop line color and width.
setLegendIcon | (Self) | Sets the size and color of the legend icon.


ThreeDScatterGroup.setDataSymbol

ThreeDScatterGroup.setDataSymbol

Usage

public void setDataSymbol(int symbol [, int size [, int fillColor [, int edgeColor [, int 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 | 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. SameAsMainColor means the color is based on the z value of the symbol as according to the ColorAxis (accessible via ThreeDChart.colorAxis).
edgeColor | -1 | The edge color used to draw the edge of the symbol. -1 means using LineColor as the edge color.
lineWidth | 1 | The line width used for drawing the symbols.

Return Value

None


ThreeDScatterGroup.setDataSymbol2

ThreeDScatterGroup.setDataSymbol2

Usage

public void setDataSymbol2(String 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


ThreeDScatterGroup.setDataSymbol3

ThreeDScatterGroup.setDataSymbol3

Usage

public void setDataSymbol3(DrawArea 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


ThreeDScatterGroup.setDataSymbol4

ThreeDScatterGroup.setDataSymbol4

Usage

public void setDataSymbol4(int[] polygon [, int size [, int fillColor [, int 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 that the color is automatically selected from the palette. SameAsMainColor means the color is based on the z value of the symbol as according to the ColorAxis (accessible via ThreeDChart.colorAxis).
edgeColor | -1 | The edge color used to draw the edge of the symbol. -1 means using LineColor as the edge color.

Return Value

None


ThreeDScatterGroup.setDropLine

ThreeDScatterGroup.setDropLine

Usage

public void setDropLine(int dropLineColor [, int dropLineWidth ])

Description

Sets the drop line color and width.

Drop lines are vertical lines that join the data points to the bottom of the plot region. It helps in visualizing the height of the data points.

Arguments

Argument | Default | Description
dropLineColor | (Mandatory) | The color of the drop line.
dropLineWidth | 1 | The width of the drop line.

Return Value

None


ThreeDScatterGroup.setLegendIcon

ThreeDScatterGroup.setLegendIcon

Usage

public void void setLegendIcon(int width [, int height [, int color ]])

Description

Sets the size and color of the legend icon.

By default, the legend icon is the same as the symbol added to the chart in its shape, size and color. In some cases, it may be desirable for the legend icon to have a different size from the plotted symbol. For example, the size of the legend icon may be sized to match the font size of the legend box, rather than the plotted size of the symbol.

ThreeDScatterChart allows the color of the symbols to vary based on the z value of the symbol. So the symbols may or may not have a fix color. By default, the mid-point of the ColorAxis (accessible via ThreeDChart.colorAxis) will be used as the legend icon color. The setLegendIcon method can be used to modify the color of the legend icon.

Setting the width or height to 0 disables the legend entry.

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 the same as the width.
color | -1 | The color of the legend icon. -1 means the color is the same as the symbol color at the mid-point of the ColorAxis.

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, exclusive of the drop shadow (if any).
getWidth | BaseChart | Gets the width of the chart.
getHeight | BaseChart | Gets the height of the chart.
getAbsOffsetX | BaseChart | Gets the x offset of the chart relative to the outermost MultiChart container.
getAbsOffsetY | BaseChart | Gets the y offset of the chart relative to the outermost MultiChart container.
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.
setDropShadow | BaseChart | Adds a drop shadow to the chart.
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 file system search path for loading image files.
setSearchPath2 | BaseChart | Sets the ClassLoader for loading images.
setSearchPath3 | BaseChart | Search for image files using the ServletContext and ServletRequest.
setSearchPath4 | BaseChart | Search for image files using a URL as the base path.
setTransparentColor | BaseChart | Specifies a certain color to mean transparent when creating a raster 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.
addTable | BaseChart | Adds a CDML table 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.
adjustBrightness | BaseChart | Creates a color that is a darkened or brightened version of the given color.
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 axes (if any) and compute the positions of the various objects in the chart.
makeImage | BaseChart | Generates the chart as a java.awt.Image object.
enableVectorOutput | BaseChart | Enables true vector graphics output.
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.
initDynamicLayer | BaseChart | Initializes a dynamic layer for drawing text and shapes.
removeDynamicLayer | BaseChart | Removes the dynamic layer if any.
getHTMLImageMap | BaseChart | Generates an HTML image map for the chart.
getJsChartModel | BaseChart | Gets the Javascript Chart Model for passing to WebChartViewer.setChartModel for the purpose of supporting track cursors in a web application.
getChartMetrics | BaseChart | Gets the chart metrics for passing to WebChartViewer.setChartMetrics to support view ports for web applications.


PolarChart.PolarChart

PolarChart.PolarChart

Usage

public PolarChart(int width, int height [, int bgColor [, int edgeColor [, int 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.


PolarChart.setPlotArea

PolarChart.setPlotArea

Usage

public void setPlotArea(int x, int y, int r [, int bgColor [, int edgeColor [, int 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

public void setPlotAreaBg(int bgColor1 [, int bgColor2 [, boolean 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. -1 means it is the same as the first background color.
altRings | true | A true value means the background colors alternate in the radial direction, resulting in concentric circles. A false value means the background colors alternates in the angular direction, resulting in alternating sectors.

Return Value

None


PolarChart.setGridColor

PolarChart.setGridColor

Usage

public void setGridColor([ int rGridColor [, int rGridWidth [, int aGridColor [, int 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

public void setGridStyle(boolean polygonGrid [, boolean 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 value means polygonal grid will be used. A false value means circular grid will be used.
gridOnTop | true | A true value means the grid lines will be on top of the polar plot area. A false value means the grid lines will be at the bottom of the polar plot area.

Return Value

None


PolarChart.setStartAngle

PolarChart.setStartAngle

Usage

public void setStartAngle(double startAngle [, boolean 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 | A true value means the radial grid line will be laid out in the clockwise direction. A false value means the radial grid lines will be laid out in the counter-clockwise direction.

Return Value

None


PolarChart.angularAxis

PolarChart.angularAxis

Usage

public AngularAxis 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

public RadialAxis 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

public int getXCoor(double r, double 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. ChartDirector needs to perform auto-scaling and layout the axis 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

public int getYCoor(double r, double 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. ChartDirector needs to perform auto-scaling and layout the axis 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

public PolarLineLayer addLineLayer(double[] data [, int color [, String 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

public PolarAreaLayer addAreaLayer(double[] data [, int color [, String 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

public PolarSplineLineLayer addSplineLineLayer(double[] data [, int color [, String 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

public PolarSplineAreaLayer addSplineAreaLayer(double[] data [, int color [, String 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

public PolarVectorLayer addVectorLayer(double[] rData, double[] aData, double[] lengths, double[] directions [, int lengthScale [, int color [, String name ]]])

Description

Adds a vector layer to the chart.

By default, the vectors start from the given reference points and point away from it. You may use PolarVectorLayer.setArrowAlignment to specify other options, such as for the vectors to point into the reference points, or to have the reference points being the mid-points of the vectors.

ChartDirector supports specifying the vector lengths and directions directly, or indirectly as the lengths and directions from the reference points to the reference end points. This is controlled by lengthScale as described in the following table.

Constant | Value | Description
PixelScale | 0 | The lengths are measured in pixels. The angles are measured clockwise in degrees, with the upwards position as 0.
RadialAxisScale | 2 | radial axis scale
EndPoints | 3 | The vector lengths and directions are measured as the lengths and directions between the reference points and the reference end points.

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 either the lengths of the vectors or the radial coordinates of the reference end points, depending on lengthScale.
directions | (Mandatory) | An array of numbers representing either the directions of the vectors or the angular coordinates of the reference end points, depending on lengthScale.
lengthScale | PixelScale | The method to specify vector lengths and directions, 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.
setLength | Axis | Sets the length of the axis.
setMargin | Axis | Reserve margins at the ends of the axis.
setIndent | Axis | Specifies if the axis should be "indented" or not.
setOffset | Axis | Sets the positional offset of the axis.
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.
makeLabelTable | Axis | Creates a CDML table and docks it to the axis, with one row (for horizontal axis) or column (for vertical axis) containing the axis labels.
getLabelTable | Axis | Gets the CDML table created by Axis.makeLabelTable.
getMinValue | Axis | Gets the lower bound of the axis.
getMaxValue | Axis | Gets the upper bound of the axis.
getX | Axis | Gets the x-coordinate of starting point of the axis.
getY | Axis | Gets the y-coordinate of starting point of the axis.
getAlignment | Axis | Gets the side of the plot area that the axis is associated with.
getThickness | Axis | Gets the thickness of the axis.
getTicks | Axis | Gets the values of the ticks.
getLabel | Axis | Gets the label at the specified position on the axis.
getFormattedLabel | Axis | Gets the label at the specified position on the axis, formatting one if necessary.
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

public TextBox setLabelStyle([ String font [, double fontSize [, int fontColor [, double 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 axis labels. This may be used to fine-tune the appearance of the axis labels.


AngularAxis.setLabelGap

AngularAxis.setLabelGap

Usage

public void setLabelGap(int 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

public TextBox setLabels(String[] 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.

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 with a radial grid line. To disable the grid line, use '-' or '~' as the first character of the label. The leading '-' or '~' character will not be displayed, but is just a signal to disable the grid line. If you want have a label that actually begins with '-' or '~', you may start the label with '\-' or '\~' instead.

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 axis labels. This may be used to fine-tune the appearance of the axis labels.


AngularAxis.setLabels2

AngularAxis.setLabels2

Usage

public TextBox setLabels2(double[] labels [, String 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 axis labels. This may be used to fine-tune the appearance of the axis labels.


AngularAxis.addLabel

AngularAxis.addLabel

Usage

public void addLabel(double pos, String label)

Description

Adds an extra label on the axis.

Note that the first character of the label can be interpreted as a tick specification character. Please refer to AngularAxis.setLabels for more details.

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

public void setLinearScale(double lowerLimit, double upperLimit [, double majorTickInc [, double 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. 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. 0 means no minor tick is used.

Return Value

None


AngularAxis.setLinearScale2

AngularAxis.setLinearScale2

Usage

public void setLinearScale2(double lowerLimit, double upperLimit, String[] labels)

Description

Sets the axis to use the given linear scale and the given labels.

Note that the first character of a label can be interpreted as a tick specification character. Please refer to AngularAxis.setLabels for more details.

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

public void addZone(double startValue, double endValue, int startRadius, int endRadius, int fillColor [, int 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 radial axis scale.
endRadius | (Mandatory) | The ending radius of the zone in radial axis scale.
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

public void addZone2(double startValue, double endValue, int fillColor [, int 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

public String getHTMLImageMap(String url [, String queryFormat [, String extraAttr [, int offsetX, int 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

public String getAxisImageMap(int noOfSegments, int mapWidth, String url [, String queryFormat [, String extraAttr [, int offsetX, int 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

public void setAngles(double[] 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

public void setBorderColor(int 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

public void setLineWidth(int 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

public void setDataSymbol(int symbol [, int size [, int fillColor [, int edgeColor [, int 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 representation will be used.
edgeColor | -1 | The edge color used to draw the edge of the symbol. -1 means the border color of the data representation will be used.
lineWidth | 1 | The line width used for drawing the symbols.

Return Value

None


PolarLayer.setDataSymbol2

PolarLayer.setDataSymbol2

Usage

public void setDataSymbol2(String 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

public void setDataSymbol3(DrawArea 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

public void setDataSymbol4(int[] polygon [, int size [, int fillColor [, int 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 representation will be used.
edgeColor | -1 | The edge color used to draw the edge of the symbol. -1 means the border color of the data representation will be used.

Return Value

None


PolarLayer.setSymbolScale

PolarLayer.setSymbolScale

Usage

public void setSymbolScale(double[] zData [, int 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

public TextBox setDataLabelStyle([ String font [, double fontSize [, int fontColor [, double 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 data labels. This may be used to fine-tune the appearance of the data labels.


PolarLayer.setDataLabelFormat

PolarLayer.setDataLabelFormat

Usage

public void setDataLabelFormat(String 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

public TextBox addCustomDataLabel(int i, String label [, String font [, double fontSize [, int fontColor [, double 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 index of the data point. The first data point is 0; 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 custom data label. This may be used to fine-tune the appearance of the custom data label.


PolarLayer.setImageMapWidth

PolarLayer.setImageMapWidth

Usage

public void setImageMapWidth(int 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

public String getImageCoor(int dataItem [, int offsetX, int 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 index of the data point. The first data point is 0; 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

public String getHTMLImageMap(String url [, String queryFormat [, String extraAttr [, int offsetX, int 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

public void setHTMLImageMap(String url [, String queryFormat [, String 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

public void setCloseLoop(boolean 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 value means the polar line should form a close loop. A false value means the polar line should not form a close loop.

Return Value

None


PolarLineLayer.setGapColor

PolarLineLayer.setGapColor

Usage

public void setGapColor(int lineColor [, int 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

public void setTension(double 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

public void setTension(double 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.
setVectorMargin | (Self) | Sets the margins to shorten the vectors.
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

public void setVector(double[] lengths, double[] directions [, int lengthScale ])

Description

Sets the lengths and directions for the vectors.

ChartDirector supports specifying the vector lengths and directions directly, or indirectly as the lengths and directions from the reference points to the reference end points. This is controlled by lengthScale as described in the following table.

Constant | Value | Description
PixelScale | 0 | The lengths are measured in pixels. The angles are measured clockwise in degrees, with the upwards position as 0.
RadialAxisScale | 2 | radial axis scale
EndPoints | 3 | The vector lengths and directions are measured as the lengths and directions between the reference points and the reference end points.

Arguments

Argument | Default | Description
lengths | (Mandatory) | An array of numbers representing either the lengths of the vectors or the radial coordinates of the reference end points, depending on lengthScale.
directions | (Mandatory) | An array of numbers representing either the directions of the vectors or the angular coordinates of the reference end points, depending on lengthScale.
lengthScale | PixelScale | The method to specify vector lengths and directions, which must be one of the predefined constants in the table above.

Return Value

None


PolarVectorLayer.setArrowHead

PolarVectorLayer.setArrowHead

Usage

public void setArrowHead(int width [, int 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. 0 means the height is the same as the width.

Return Value

None


PolarVectorLayer.setArrowHead2

PolarVectorLayer.setArrowHead2

Usage

public void setArrowHead2(int[] 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

public void setArrowStem(int[] 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

public void setArrowAlignment(int 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.setVectorMargin

PolarVectorLayer.setVectorMargin

Usage

public void setVectorMargin(double startMargin [, double endMargin ])

Description

Sets the margins to shorten the vectors.

By default, vectors will be drawn from the given start points to the given end points.

In some cases, it may be desirable to shorten the vectors so that they do not start exactly at the start points and/or end exactly at the end points. For example, the vectors may be used to point to some circular symbols created by a ScatterLayer. The vectors may need to point to the perimeter of the circles, rather than their centers. This can be achieved by shortening the vectors by the radius of the circles.

Arguments

Argument | Default | Description
startMargin | (Mandatory) | The length to shorten at the start of the vector in pixels.
endMargin | NoValue | The length to shorten at the end of the vector in pixels. NoValue means the length is the same as startMargin.

Return Value

None


PolarVectorLayer.setIconSize

PolarVectorLayer.setIconSize

Usage

public void setIconSize(int height [, int 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. 0 means the width is automatically determined.

Return Value

None


PyramidChart

PyramidChart

The PyramidChart class represents pyramid charts (including cone charts and funnel charts). The PyramidChart class is a subclass of BaseChart.

Method | Inherited | Description
PyramidChart | (Self) | Creates a new PyramidChart object.
setPyramidSize | (Self) | Sets the position and size of the pyramid in a pyramid chart.
setConeSize | (Self) | Sets the position and size of the cone in a cone chart.
setFunnelSize | (Self) | Sets the position and size of the funnel in a funnel chart.
setViewAngle | (Self) | Sets the 3D view angles.
setPyramidSides | (Self) | Sets the number of sides of the base polygon in a pyramid chart.
setCenterLabel | (Self) | Adds labels to the center of the pyramid layers.
setRightLabel | (Self) | Adds labels to the right of the pyramid layers.
setLeftLabel | (Self) | Adds labels to the left of the pyramid layers.
setJoinLine | (Self) | Sets the color and line width of the join lines that join the pyramid layers with the left and right labels.
setJoinLineGap | (Self) | Sets the gaps of the join lines that join the pyramid layers with the left and right labels.
setGradientShading | (Self) | Sets gradient shading mode.
setLighting | (Self) | Sets Phong lighting mode.
setLayerGap | (Self) | Sets the gaps between pyramid layers.
setLayerBorder | (Self) | Sets the color and line width of the layer border.
setData | (Self) | Sets the data used to draw the pyramid chart.
getLayer | (Self) | Retrieves the PyramidLayer object representing a single pyramid layer in the pyramid chart.
setSize | BaseChart | Sets the size of the chart, exclusive of the drop shadow (if any).
getWidth | BaseChart | Gets the width of the chart.
getHeight | BaseChart | Gets the height of the chart.
getAbsOffsetX | BaseChart | Gets the x offset of the chart relative to the outermost MultiChart container.
getAbsOffsetY | BaseChart | Gets the y offset of the chart relative to the outermost MultiChart container.
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.
setDropShadow | BaseChart | Adds a drop shadow to the chart.
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 file system search path for loading image files.
setSearchPath2 | BaseChart | Sets the ClassLoader for loading images.
setSearchPath3 | BaseChart | Search for image files using the ServletContext and ServletRequest.
setSearchPath4 | BaseChart | Search for image files using a URL as the base path.
setTransparentColor | BaseChart | Specifies a certain color to mean transparent when creating a raster 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.
addTable | BaseChart | Adds a CDML table 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.
adjustBrightness | BaseChart | Creates a color that is a darkened or brightened version of the given color.
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 axes (if any) and compute the positions of the various objects in the chart.
makeImage | BaseChart | Generates the chart as a java.awt.Image object.
enableVectorOutput | BaseChart | Enables true vector graphics output.
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.
initDynamicLayer | BaseChart | Initializes a dynamic layer for drawing text and shapes.
removeDynamicLayer | BaseChart | Removes the dynamic layer if any.
getHTMLImageMap | BaseChart | Generates an HTML image map for the chart.
getJsChartModel | BaseChart | Gets the Javascript Chart Model for passing to WebChartViewer.setChartModel for the purpose of supporting track cursors in a web application.
getChartMetrics | BaseChart | Gets the chart metrics for passing to WebChartViewer.setChartMetrics to support view ports for web applications.


PyramidChart.PyramidChart

PyramidChart.PyramidChart

Usage

public PyramidChart(int width, int height [, int bgColor [, int edgeColor [, int raisedEffect ]]])

Description

Creates a new PyramidChart 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 PyramidChart object created.


PyramidChart.setPyramidSize

PyramidChart.setPyramidSize

Usage

public void setPyramidSize(int cx, int cy, int radius, int height)

Description

Sets the position and size of the pyramid in a pyramid chart.

Arguments

Argument | Default | Description
cx | (Mandatory) | The x-coordinate of the center of the pyramid. The center of the pyramid is the midpoint of the vertical axis of the pyramid.
cy | (Mandatory) | The y-coordinate of the center of the pyramid. The center of the pyramid is the midpoint of the vertical axis of the pyramid.
radius | (Mandatory) | For a square pyramid, it is the length of the square. For a pyramid with other regular polygonal base, it is the radius of the circumcircle of the base.
height | (Mandatory) | The height of the pyramid.

Return Value

None


PyramidChart.setConeSize

PyramidChart.setConeSize

Usage

public void setConeSize(int cx, int cy, int radius, int height)

Description

Sets the position and size of the cone in a cone chart.

Arguments

Argument | Default | Description
cx | (Mandatory) | The x-coordinate of the center of the cone. The center of the cone is the midpoint of the vertical axis of the cone.
cy | (Mandatory) | The y-coordinate of the center of the cone. The center of the cone is the midpoint of the vertical axis of the cone.
radius | (Mandatory) | The radius of the base of the cone.
height | (Mandatory) | The height of the cone.

Return Value

None


PyramidChart.setFunnelSize

PyramidChart.setFunnelSize

Usage

public void void setFunnelSize(int cx, int cy, int radius, int height [, double tubeRadius [, double tubeHeight ]])

Description

Sets the position and size of the funnel in a funnel chart.

A funnel is similar to an inverted cone, except that the vertex of the cone is replaced by a tube.

Arguments

Argument | Default | Description
cx | (Mandatory) | The x-coordinate of the center of the funnel. The center of the funnel is the midpoint of the vertical axis of the funnel.
cy | (Mandatory) | The y-coordinate of the center of the funnel. The center of the funnel is the midpoint of the vertical axis of the funnel.
radius | (Mandatory) | The radius of the mouth of the funnel.
height | (Mandatory) | The height of the funnel, inclusive of the tube.
tubeRadius | 0.2 | The radius of the tube, as a ratio to the radius of the mouth of the funnel.
tubeHeight | 0.3 | The height (length) of the tube, as a ratio to the total height of the funnel. It must be between 0 to 1.

Return Value

None


PyramidChart.setViewAngle

PyramidChart.setViewAngle

Usage

public void setViewAngle(double elevation [, double rotation [, double twist ]])

Description

Sets the 3D view angles.

ChartDirector uses elevation, rotation and twist angles to specify the 3D view angles.

To explain the meaning of the angles, imagine the object being viewed is put at the center of a hollow sphere, and a camera (the view point) is put at the surface of the sphere, directed inwards to the center to look at the object.

The elevation angle refers to the "latitude" of the camera. An elevation angle of 0 degrees means the camera is at the "equator" pointing to the object from the side. An elevation angle of 90 degrees means the camera is at the "north pole" pointing down to the object. An angle elevation of -90 degrees means the camera is at the "south pole", pointing up to the object.

The rotation angle refers to the "longitude" of the camera. If the elevation is 0 degrees, and the rotation angle varies from 0 to 360 degrees, the camera will move around the "equator" in the easterly direction (counter-clockwise when viewed from the north pole).

The twist angle is for rotating the camera itself while still pointing to the object. For example, a twist angle of 90 degrees means you are holder the camera "vertically" instead of "horizontally". The rotation is clockwise from the view point of the person holding the camera.

Note that from the view point of the camera, the object will appear to be rotating in the opposite direction. For example, as the rotation angle rotates the camera counter-clockwise along the "equator", the object will appear to be rotating clockwise on the screen.

Arguments

Argument | Default | Description
elevation | (Mandatory) | The elevation angle in degrees.
rotation | 0 | The rotation angle in degrees.
twist | 0 | The twist angle in degrees.

Return Value

None


PyramidChart.setPyramidSides

PyramidChart.setPyramidSides

Usage

public void setPyramidSides(int noOfSides)

Description

Sets the number of sides of the base polygon in a pyramid chart.

By default, the base of a pyramid is a square. This method can be used to change it to other regular polygon.

Arguments

Argument | Default | Description
noOfSides | (Mandatory) | The number of sides of the base polygon in a pyramid chart.

Return Value

None


PyramidChart.setCenterLabel

PyramidChart.setCenterLabel

Usage

public TextBox setCenterLabel([ String template [, String font [, double fontSize [, int fontColor ]]]])

Description

Adds labels to the center of the pyramid layers.

This method affects all pyramid layers. To apply this method to one particular pyramid layer only, use PyramidLayer.setCenterLabel.

See Parameter Substitution and Formatting on available format parameters for the template.

See Font Specification for details on various font attributes.

Arguments

Argument | Default | Description
template | "{skip}" | The label template. "{skip}" means to keep the existing value unchanged.
font | "{skip}" | The font style. "{skip}" means to keep the existing value unchanged.
fontSize | -1 | The font size in points. -1 means to keep the existing value unchanged.
fontColor | -1 | The font color. -1 means to keep the existing value unchanged.

Return Value

A TextBox object representing the prototype of the labels. This may be used to fine-tune the appearance of the labels.


PyramidChart.setRightLabel

PyramidChart.setRightLabel

Usage

public TextBox setRightLabel([ String template [, String font [, double fontSize [, int fontColor ]]]])

Description

Adds labels to the right of the pyramid layers.

This method affects all pyramid layers. To apply this method to one particular pyramid layer only, use PyramidLayer.setRightLabel.

See Parameter Substitution and Formatting on available format parameters for the template.

See Font Specification for details on various font attributes.

Arguments

Argument | Default | Description
template | "{skip}" | The label template. "{skip}" means to keep the existing value unchanged.
font | "{skip}" | The font style. "{skip}" means to keep the existing value unchanged.
fontSize | -1 | The font size in points. -1 means to keep the existing value unchanged.
fontColor | -1 | The font color. -1 means to keep the existing value unchanged.

Return Value

A TextBox object representing the prototype of the labels. This may be used to fine-tune the appearance of the labels.


PyramidChart.setLeftLabel

PyramidChart.setLeftLabel

Usage

public TextBox setLeftLabel([ String template [, String font [, double fontSize [, int fontColor ]]]])

Description

Adds labels to the left of the pyramid layers.

This method affects all pyramid layers. To apply this method to one particular pyramid layer only, use PyramidLayer.setLeftLabel.

See Parameter Substitution and Formatting on available format parameters for the template.

See Font Specification for details on various font attributes.

Arguments

Argument | Default | Description
template | "{skip}" | The label template. "{skip}" means to keep the existing value unchanged.
font | "{skip}" | The font style. "{skip}" means to keep the existing value unchanged.
fontSize | -1 | The font size in points. -1 means to keep the existing value unchanged.
fontColor | -1 | The font color. -1 means to keep the existing value unchanged.

Return Value

A TextBox object representing the prototype of the labels. This may be used to fine-tune the appearance of the labels.


PyramidChart.setJoinLine

PyramidChart.setJoinLine

Usage

public void setJoinLine(int color [, int width ])

Description

Sets the color and line width of the join lines that join the pyramid layers with the left and right labels.

This method affects all pyramid layers. To apply this method to one particular pyramid layer only, use PyramidLayer.setJoinLine.

Arguments

Argument | Default | Description
color | (Mandatory) | The color of the join line. -1 means to keep the existing value unchanged.
width | -1 | The width of the line join. -1 means to keep the existing value unchanged.

Return Value

None


PyramidChart.setJoinLineGap

PyramidChart.setJoinLineGap

Usage

public void setJoinLineGap(int pyramidGap [, int pyramidMargin [, int textGap ]])

Description

Sets the gaps of the join lines that join the pyramid layers with the left and right labels.

This method affects all pyramid layers. To apply this method to one particular pyramid layer only, use PyramidLayer.setJoinLineGap.

By default, the starting point of the join line connects to the pyramid layer edge with a 3 pixels gap. The join line is horizontal, and its length is such that the ending point is 10 pixels outside the pyramid bounding box. The label text box connects to the ending point with a 3 pixels gap.

This method allows the gaps and positions of the join line end points to be configured to other values.

Arguments

Argument | Default | Description
pyramidGap | (Mandatory) | The gap in pixels between the starting point of the join line and the pyramid layer edge.
pyramidMargin | 10 | The distance in pixels between the ending point of the join line and the pyramid bounding box.
textGap | 3 | The gap in pixels between the label text box and the ending point of the join line.

Return Value

None


PyramidChart.setGradientShading

PyramidChart.setGradientShading

Usage

public void setGradientShading(double startBrightness, double endBrightness)

Description

Sets gradient shading mode.

Gradient shading only applies to 2D and 3D pyramids, and 2D cones and funnels. 3D cones and funnels always use Phong lighting (see PyramidChart.setLighting).

The gradient is specified with two brightness values at the gradient end points. A brightness less than 1 means the color is darkened, while a brightness greater than 1 means the color is brightened. For example, a brightness of 0.5 means the color is half as bright as the original color. If the original color is red, the color will become dark red. Conversely, a brightness of 2 means the color is twice as bright as the original color. If the original color is red, the color will become light red.

For a pyramid or cone layer, the gradient is from left edge to the right edge. For a funnel chart, the gradient is from the right edge to the left edge.

For a pyramid chart, this is the default coloring method. If this method is never called, the default brightness is from 0.75 to 2.

Arguments

Argument | Default | Description
startBrightness | (Mandatory) | The brightness at the starting point.
endBrightness | (Mandatory) | The brightness at the ending point.

Return Value

None


PyramidChart.setLighting

PyramidChart.setLighting

Usage

public void setLighting([ double ambientIntensity, double diffuseIntensity, double specularIntensity, double shininess ])

Description

Sets Phong lighting mode.

This method adjusts the brightness of the surfaces as according to the Phong lighting model, in which the light source is from the viewer direction and is far away.

For a cone or funnel chart, this is the default coloring method.

For a pyramid chart, only ambient and diffuse reflections are used.

Arguments

Argument | Default | Description
ambientIntensity | 0.5 | The ambient reflection coefficient of the Phong lighting model.
diffuseIntensity | 0.5 | The diffuse reflection coefficient of the Phong lighting model.
specularIntensity | 1 | The specular reflection coefficient of the Phong lighting model.
shininess | 8 | The shininess coefficient of the Phong lighting model.

Return Value

None


PyramidChart.setLayerGap

PyramidChart.setLayerGap

Usage

public void setLayerGap(double layerGap)

Description

Sets the gaps between pyramid layers.

This method affects all pyramid layers. To apply this method to one particular pyramid layer only, use PyramidLayer.setLayerGap.

Arguments

Argument | Default | Description
layerGap | (Mandatory) | The gap between layers as a ratio to the height of the pyramid. The gap must be greater than or equals 0. The sum of all gaps must be less than 1.

Return Value

None


PyramidChart.setLayerBorder

PyramidChart.setLayerBorder

Usage

public void setLayerBorder(int color [, int width ])

Description

Sets the color and line width of the layer border.

This method affects all pyramid layers. To apply this method to one particular pyramid layer only, use PyramidLayer.setLayerBorder.

Arguments

Argument | Default | Description
color | (Mandatory) | The color of the layer border. -1 means to keep the existing value unchanged.
width | -1 | The width of the layer border. -1 means to keep the existing value unchanged.

Return Value

None


PyramidChart.setData

PyramidChart.setData

Usage

public void setData(double[] data [, String[] labels ])

Description

Sets the data used to draw the pyramid chart.

Arguments

Argument | Default | Description
data | (Mandatory) | An array of numbers representing the data values.
labels | [Empty_Array] | An array of text strings representing the labels of the layers. An empty array means no layer label.

Return Value

None


PyramidChart.getLayer

PyramidChart.getLayer

Usage

public PyramidLayer getLayer(int layerNo)

Description

Retrieves the PyramidLayer object representing a single pyramid layer in the pyramid chart.

You must call PyramidChart.setData to create the layers first before calling this method.

Arguments

Argument | Default | Description
layerNo | (Mandatory) | The layer number of the pyramid layer to retrieve, starting from 0. The first pyramid layer is 0. The nth pyramid layer is (n-1).

Return Value

The requested PyramidLayer object.


PyramidLayer

PyramidLayer

The PyramidLayer class represents pyramid layers (including cone and funnel layers). The PyramidLayer object is obtained using PyramidChart.getLayer.

Method | Inherited | Description
setCenterLabel | (Self) | Adds a label to the center of the pyramid layer.
setRightLabel | (Self) | Adds a label to the right of the pyramid layer.
setLeftLabel | (Self) | Adds a label to the left of the pyramid layer.
setJoinLine | (Self) | Sets the color and line width of the join line that joins the pyramid layer with the left and right labels.
setJoinLineGap | (Self) | Sets the gaps of the join line that joins the pyramid layer with the left and right labels.
setColor | (Self) | Sets the color of the pyramid layer.
setLayerGap | (Self) | Sets the gap between this pyramid layer and the next pyramid layer.
setLayerBorder | (Self) | Sets the color and line width of the layer border.


PyramidLayer.setCenterLabel

PyramidLayer.setCenterLabel

Usage

public TextBox setCenterLabel([ String template [, String font [, double fontSize [, int fontColor ]]]])

Description

Adds a label to the center of the pyramid layer.

To apply this method to all pyramid layers, use PyramidChart.setCenterLabel.

See Parameter Substitution and Formatting on available format parameters for the template.

See Font Specification for details on various font attributes.

Arguments

Argument | Default | Description
template | "{skip}" | The label template. "{skip}" means to keep the existing value unchanged.
font | "{skip}" | The font style. "{skip}" means to keep the existing value unchanged.
fontSize | -1 | The font size in points. -1 means to keep the existing value unchanged.
fontColor | -1 | The font color. -1 means to keep the existing value unchanged.

Return Value

A TextBox object representing the prototype of the label. This may be used to fine-tune the appearance of the label.


PyramidLayer.setRightLabel

PyramidLayer.setRightLabel

Usage

public TextBox setRightLabel([ String template [, String font [, double fontSize [, int fontColor ]]]])

Description

Adds a label to the right of the pyramid layer.

To apply this method to all pyramid layers, use PyramidChart.setRightLabel.

See Parameter Substitution and Formatting on available format parameters for the template.

See Font Specification for details on various font attributes.

Arguments

Argument | Default | Description
template | "{skip}" | The label template. "{skip}" means to keep the existing value unchanged.
font | "{skip}" | The font style. "{skip}" means to keep the existing value unchanged.
fontSize | -1 | The font size in points. -1 means to keep the existing value unchanged.
fontColor | -1 | The font color. -1 means to keep the existing value unchanged.

Return Value

A TextBox object representing the prototype of the label. This may be used to fine-tune the appearance of the label.


PyramidLayer.setLeftLabel

PyramidLayer.setLeftLabel

Usage

public TextBox setLeftLabel([ String template [, String font [, double fontSize [, int fontColor ]]]])

Description

Adds a label to the left of the pyramid layer.

To apply this method to all pyramid layers, use PyramidChart.setLeftLabel.

See Parameter Substitution and Formatting on available format parameters for the template.

See Font Specification for details on various font attributes.

Arguments

Argument | Default | Description
template | "{skip}" | The label template. "{skip}" means to keep the existing value unchanged.
font | "{skip}" | The font style. "{skip}" means to keep the existing value unchanged.
fontSize | -1 | The font size in points. -1 means to keep the existing value unchanged.
fontColor | -1 | The font color. -1 means to keep the existing value unchanged.

Return Value

A TextBox object representing the prototype of the label. This may be used to fine-tune the appearance of the label.


PyramidLayer.setJoinLine

PyramidLayer.setJoinLine

Usage

public void setJoinLine(int color [, int width ])

Description

Sets the color and line width of the join line that joins the pyramid layer with the left and right labels.

To apply this method to all pyramid layers, use PyramidChart.setJoinLine.

Arguments

Argument | Default | Description
color | (Mandatory) | The color of the join line. -1 means to keep the existing value unchanged.
width | -1 | The width of the line join. -1 means to keep the existing value unchanged.

Return Value

None


PyramidLayer.setJoinLineGap

PyramidLayer.setJoinLineGap

Usage

public void setJoinLineGap(int pyramidGap [, int pyramidMargin [, int textGap ]])

Description

Sets the gaps of the join line that joins the pyramid layer with the left and right labels.

To apply this method to all pyramid layers, use PyramidChart.setJoinLineGap.

By default, the starting point of the join line connects to the pyramid layer edge with a 3 pixels gap. The join line is horizontal, and its length is such that the ending point is 10 pixels outside the pyramid bounding box. The label text box connects to the ending point with a 3 pixels gap.

This method allows the gaps and positions of the join line end points to be configured to other values.

Arguments

Argument | Default | Description
pyramidGap | (Mandatory) | The gap in pixels between the starting point of the join line and the pyramid layer edge.
pyramidMargin | 10 | The distance in pixels between the ending point of the join line and the pyramid bounding box.
textGap | 3 | The gap in pixels between the label text box and the ending point of the join line.

Return Value

None


PyramidLayer.setColor

PyramidLayer.setColor

Usage

public void setColor(int color)

Description

Sets the color of the pyramid layer.

Arguments

Argument | Default | Description
color | (Mandatory) | The color of the pyramid layer.

Return Value

None


PyramidLayer.setLayerGap

PyramidLayer.setLayerGap

Usage

public void setLayerGap(double layerGap)

Description

Sets the gap between this pyramid layer and the next pyramid layer.

To apply this method to all pyramid layers, use PyramidChart.setLayerGap.

Arguments

Argument | Default | Description
layerGap | (Mandatory) | The gap between layers as a ratio to the height of the pyramid. The gap must be greater than or equals 0. The sum of all gaps must be less than 1.

Return Value

None


PyramidLayer.setLayerBorder

PyramidLayer.setLayerBorder

Usage

public void setLayerBorder(int color [, int width ])

Description

Sets the color and line width of the layer border.

To apply this method to all pyramid layers, use PyramidChart.setLayerBorder.

Arguments

Argument | Default | Description
color | (Mandatory) | The color of the layer border. -1 means to keep the existing value unchanged.
width | -1 | The width of the layer border. -1 means to keep the existing value unchanged.

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, exclusive of the drop shadow (if any).
getWidth | BaseChart | Gets the width of the chart.
getHeight | BaseChart | Gets the height of the chart.
getAbsOffsetX | BaseChart | Gets the x offset of the chart relative to the outermost MultiChart container.
getAbsOffsetY | BaseChart | Gets the y offset of the chart relative to the outermost MultiChart container.
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.
setDropShadow | BaseChart | Adds a drop shadow to the chart.
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 file system search path for loading image files.
setSearchPath2 | BaseChart | Sets the ClassLoader for loading images.
setSearchPath3 | BaseChart | Search for image files using the ServletContext and ServletRequest.
setSearchPath4 | BaseChart | Search for image files using a URL as the base path.
setTransparentColor | BaseChart | Specifies a certain color to mean transparent when creating a raster 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.
addTable | BaseChart | Adds a CDML table 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.
adjustBrightness | BaseChart | Creates a color that is a darkened or brightened version of the given color.
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 axes (if any) and compute the positions of the various objects in the chart.
makeImage | BaseChart | Generates the chart as a java.awt.Image object.
enableVectorOutput | BaseChart | Enables true vector graphics output.
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.
initDynamicLayer | BaseChart | Initializes a dynamic layer for drawing text and shapes.
removeDynamicLayer | BaseChart | Removes the dynamic layer if any.
getHTMLImageMap | BaseChart | Generates an HTML image map for the chart.
getJsChartModel | BaseChart | Gets the Javascript Chart Model for passing to WebChartViewer.setChartModel for the purpose of supporting track cursors in a web application.
getChartMetrics | BaseChart | Gets the chart metrics for passing to WebChartViewer.setChartMetrics to support view ports for web applications.


BaseMeter.setScale

BaseMeter.setScale

Usage

public void setScale(double lowerLimit, double upperLimit [, double majorTickInc [, double minorTickInc [, double 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

public void setScale2(double lowerLimit, double upperLimit, String[] 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

public void setScale3(double lowerLimit, double upperLimit, double[] labels [, String 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

public MeterPointer addPointer(double value [, int fillColor [, int 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. -1 means the edge color is the same as the fill color.

Return Value

A MeterPointer object representing the pointer. You may use this object to fine-tune the appearance of the pointer.


BaseMeter.setLabelStyle

BaseMeter.setLabelStyle

Usage

public TextBox setLabelStyle([ String font [, double fontSize [, int fontColor [, double 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 meter labels. This may be used to fine-tune the appearance of the meter labels.


BaseMeter.setLabelFormat

BaseMeter.setLabelFormat

Usage

public void setLabelFormat(String 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

public void setLabelPos(boolean labelInside [, int labelOffset ])

Description

Sets the positions of the meter scale labels.

Arguments

Argument | Default | Description
labelInside | (Mandatory) | A true value means that the labels are on the 'inward' side of the meter scale. A false 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

public void setMeterColors(int axisColor [, int labelColor [, int 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

public void setLineWidth(int axisWidth [, int majorTickWidth [, int minorTickWidth [, int 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

public void setTickLength(int majorLen [, int minorLen [, int 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

public void addLabel(double pos, String 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

public String getLabel(double 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

public int getCoor(double 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

public double[] 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, exclusive of the drop shadow (if any).
getWidth | BaseChart | Gets the width of the chart.
getHeight | BaseChart | Gets the height of the chart.
getAbsOffsetX | BaseChart | Gets the x offset of the chart relative to the outermost MultiChart container.
getAbsOffsetY | BaseChart | Gets the y offset of the chart relative to the outermost MultiChart container.
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.
setDropShadow | BaseChart | Adds a drop shadow to the chart.
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 file system search path for loading image files.
setSearchPath2 | BaseChart | Sets the ClassLoader for loading images.
setSearchPath3 | BaseChart | Search for image files using the ServletContext and ServletRequest.
setSearchPath4 | BaseChart | Search for image files using a URL as the base path.
setTransparentColor | BaseChart | Specifies a certain color to mean transparent when creating a raster 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.
addTable | BaseChart | Adds a CDML table 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.
adjustBrightness | BaseChart | Creates a color that is a darkened or brightened version of the given color.
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 axes (if any) and compute the positions of the various objects in the chart.
makeImage | BaseChart | Generates the chart as a java.awt.Image object.
enableVectorOutput | BaseChart | Enables true vector graphics output.
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.
initDynamicLayer | BaseChart | Initializes a dynamic layer for drawing text and shapes.
removeDynamicLayer | BaseChart | Removes the dynamic layer if any.
getHTMLImageMap | BaseChart | Generates an HTML image map for the chart.
getJsChartModel | BaseChart | Gets the Javascript Chart Model for passing to WebChartViewer.setChartModel for the purpose of supporting track cursors in a web application.
getChartMetrics | BaseChart | Gets the chart metrics for passing to WebChartViewer.setChartMetrics to support view ports for web applications.


AngularMeter.AngularMeter

AngularMeter.AngularMeter

Usage

public AngularMeter(int width, int height [, int bgColor [, int edgeColor [, int 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.


AngularMeter.setMeter

AngularMeter.setMeter

Usage

public void setMeter(int cx, int cy, int radius, double startAngle, double 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

public void addZone(double startValue, double endValue, int startRadius, int endRadius, int fillColor [, int 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

public void addZone2(double startValue, double endValue, int fillColor [, int 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

public void addRing(int startRadius, int endRadius, int fillColor [, int 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

public void addRingSector(int startRadius, int endRadius, double a1, double a2, int fillColor [, int 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

public void setCap(int radius, int fillColor [, int 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, exclusive of the drop shadow (if any).
getWidth | BaseChart | Gets the width of the chart.
getHeight | BaseChart | Gets the height of the chart.
getAbsOffsetX | BaseChart | Gets the x offset of the chart relative to the outermost MultiChart container.
getAbsOffsetY | BaseChart | Gets the y offset of the chart relative to the outermost MultiChart container.
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.
setDropShadow | BaseChart | Adds a drop shadow to the chart.
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 file system search path for loading image files.
setSearchPath2 | BaseChart | Sets the ClassLoader for loading images.
setSearchPath3 | BaseChart | Search for image files using the ServletContext and ServletRequest.
setSearchPath4 | BaseChart | Search for image files using a URL as the base path.
setTransparentColor | BaseChart | Specifies a certain color to mean transparent when creating a raster 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.
addTable | BaseChart | Adds a CDML table 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.
adjustBrightness | BaseChart | Creates a color that is a darkened or brightened version of the given color.
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 axes (if any) and compute the positions of the various objects in the chart.
makeImage | BaseChart | Generates the chart as a java.awt.Image object.
enableVectorOutput | BaseChart | Enables true vector graphics output.
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.
initDynamicLayer | BaseChart | Initializes a dynamic layer for drawing text and shapes.
removeDynamicLayer | BaseChart | Removes the dynamic layer if any.
getHTMLImageMap | BaseChart | Generates an HTML image map for the chart.
getJsChartModel | BaseChart | Gets the Javascript Chart Model for passing to WebChartViewer.setChartModel for the purpose of supporting track cursors in a web application.
getChartMetrics | BaseChart | Gets the chart metrics for passing to WebChartViewer.setChartMetrics to support view ports for web applications.


LinearMeter.LinearMeter

LinearMeter.LinearMeter

Usage

public LinearMeter(int width, int height [, int bgColor [, int edgeColor [, int 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.


LinearMeter.setMeter

LinearMeter.setMeter

Usage

public void setMeter(int leftX, int topY, int width, int height [, int axisPos [, boolean 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 | 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, the meter scale will be reversed.

Return Value

None


LinearMeter.setRail

LinearMeter.setRail

Usage

public void setRail(int railColor [, int railWidth [, int 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

public TextBox addZone(double startValue, double endValue, int color [, String 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

public void setPos(double 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

public void setColor(int fillColor [, int 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. -1 means it is the same as the fill color.

Return Value

None


MeterPointer.setShape

MeterPointer.setShape

Usage

public void setShape(int pointerType [, double lengthRatio [, double 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

public void setShape2(int[] pointerCoor [, double lengthRatio [, double 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

public void setZOrder(int 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.

  • Main Chart Layers: Add additional data series (eg. series of other stock prices, or a market index) for comparison with the closing price.

  • Moving Averages: Chart can include arbitrary number of moving average lines of configurable types and periods. Supports simple, exponential, triangular and weighted moving averages.

  • Parabolic SAR: A parabolic SAR indicator can be added to the main price chart.

  • 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 additional data series (eg. series of other stock prices, or a market index) for comparison with the closing price.(FinanceChart.addComparison)

  • Add moving average lines of different types and periods (addSimpleMovingAvg, addExpMovingAvg, addTriMovingAvg, addWeightedMovingAvg)

  • Add Parabolic SAR (addParabolicSAR)

  • 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 Source Code

To serve as an example of how to build an application specific chart library on top of ChartDirector, the source code of FinanceChart is opened. It is in the "[ChartDirector]/javaFinanceChart" directory.

The source code will put FinanceChart in the "Custom" package, so it will become "Custom.FinanceChart" instead of "ChartDirector.FinanceChart". If you change the name, please do not use "ChartDirector" as the package name. This is to avoid conflicting with current or future versions of ChartDirector.

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. The default is 40 pixels for the left and right margins, and 30 pixels for the top and bottom margins.
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 background and grid colors. The default is a white background with light grey (DDDDDD) grid lines.
setPlotAreaBorder | (Self) | Sets the plot area border color and the gap distance between charts. The default is a grey (888888) border with two 2 pixels gap between charts.
setLegendStyle | (Self) | Sets legend font style and background color. The default is Arial 8 pt black font on a semi-transparent light grey (80CCCCCC) 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 14 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.
setPercentageAxis | (Self) | Label the axis of the main chart in percentage unit.
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.
addComparison | (Self) | Adds a data series to the main chart for comparison with the closing price.
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.
addParabolicSAR | (Self) | Adds a parabolic SAR indicator to 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 to the main chart.
addDonchianChannel | (Self) | Adds a Donchian channel to the main chart.
addEnvelop | (Self) | Adds a price envelop to 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.
getChart | MultiChart | Gets the specified chart in the MultiChart.
getChartCount | MultiChart | Gets the number of charts in the MultiChart.
setMainChart | MultiChart | Sets the chart that receives view port mouse actions (for zooming and scrolling support).
setSize | BaseChart | Sets the size of the chart, exclusive of the drop shadow (if any).
getWidth | BaseChart | Gets the width of the chart.
getHeight | BaseChart | Gets the height of the chart.
getAbsOffsetX | BaseChart | Gets the x offset of the chart relative to the outermost MultiChart container.
getAbsOffsetY | BaseChart | Gets the y offset of the chart relative to the outermost MultiChart container.
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.
setDropShadow | BaseChart | Adds a drop shadow to the chart.
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 file system search path for loading image files.
setSearchPath2 | BaseChart | Sets the ClassLoader for loading images.
setSearchPath3 | BaseChart | Search for image files using the ServletContext and ServletRequest.
setSearchPath4 | BaseChart | Search for image files using a URL as the base path.
setTransparentColor | BaseChart | Specifies a certain color to mean transparent when creating a raster 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.
addTable | BaseChart | Adds a CDML table 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.
adjustBrightness | BaseChart | Creates a color that is a darkened or brightened version of the given color.
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 axes (if any) and compute the positions of the various objects in the chart.
makeImage | BaseChart | Generates the chart as a java.awt.Image object.
enableVectorOutput | BaseChart | Enables true vector graphics output.
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.
initDynamicLayer | BaseChart | Initializes a dynamic layer for drawing text and shapes.
removeDynamicLayer | BaseChart | Removes the dynamic layer if any.
getHTMLImageMap | BaseChart | Generates an HTML image map for the chart.
getJsChartModel | BaseChart | Gets the Javascript Chart Model for passing to WebChartViewer.setChartModel for the purpose of supporting track cursors in a web application.
getChartMetrics | BaseChart | Gets the chart metrics for passing to WebChartViewer.setChartMetrics to support view ports for web applications.


FinanceChart.FinanceChart

FinanceChart.FinanceChart

Usage

public FinanceChart(int 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.


FinanceChart.enableAntiAlias

FinanceChart.enableAntiAlias

Usage

public void enableAntiAlias(boolean 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

public void setMargins(int leftMargin, int topMargin, int rightMargin, int bottomMargin)

Description

Sets the margins around the plot area. The default is 40 pixels for the left and right margins, and 30 pixels for the top and bottom margins.

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

public TextBox addPlotAreaTitle(int alignment, String 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

public void setPlotAreaStyle(int bgColor, int majorHGridColor, int majorVGridColor, int minorHGridColor, int minorVGridColor)

Description

Sets the plot area background and grid colors. The default is a white background with light grey (DDDDDD) 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.setPlotAreaBorder

FinanceChart.setPlotAreaBorder

Usage

public void setPlotAreaBorder(int borderColor, int borderGap)

Description

Sets the plot area border color and the gap distance between charts. The default is a grey (888888) border with two 2 pixels gap between charts.

Arguments

Argument | Default | Description
borderColor | (Mandatory) | The plot area border color.
borderGap | (Mandatory) | The distance between charts.

Return Value

None


FinanceChart.setLegendStyle

FinanceChart.setLegendStyle

Usage

public void setLegendStyle(String font, double fontSize, int fontColor, int bgColor)

Description

Sets legend font style and background color. The default is Arial 8 pt black font on a semi-transparent light grey (80CCCCCC) 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

public void setXAxisStyle(String font, double fontSize, int fontColor, double 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

public void setYAxisStyle(String font, double fontSize, int fontColor, int axisMargin)

Description

Sets y-axis label style. The default is Arial 8 pt black color, with 14 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

public void setAxisOnRight(boolean 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 value means the y-axis is on right. A false value means the y-axis is on left.

Return Value

None


FinanceChart.setLogScale

FinanceChart.setLogScale

Usage

public void setLogScale(boolean 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 value means using log scale. A false value means using linear scale.

Return Value

None


FinanceChart.setPercentageAxis

FinanceChart.setPercentageAxis

Usage

public void setPercentageAxis()

Description

Label the axis of the main chart in percentage unit.

By default, the axis of the main chart will be labelled in price unit. If a percentage axis is used, the axis will be labelled in percentage unit, with the first visible point of the closing price being 100%.

Arguments

None

Return Value

None


FinanceChart.setDateLabelFormat

FinanceChart.setDateLabelFormat

Usage

public void setDateLabelFormat(String yearFormat, String firstMonthFormat, String otherMonthFormat, String firstDayFormat, String otherDayFormat, String firstHourFormat, String 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

public void setDateLabelSpacing(int 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

public void setToolTipDateFormat(String monthFormat, String dayFormat, String 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

public String 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

public void setNumberLabelFormat(String formatString)

Description

Sets the number format to use.

The default number format in FinanceChart is "P3". 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

public void setData(java.util.Date[] timeStamps, double[] highData, double[] lowData, double[] openData, double[] closeData, double[] volData, int 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

public XYChart addMainChart(int 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

public CandleStickLayer addCandleStick(int upColor, int 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

public HLOCLayer addHLOC(int upColor, int 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

public LineLayer addCloseLine(int 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

public LineLayer addWeightedClose(int 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

public LineLayer addTypicalPrice(int 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

public LineLayer addMedianPrice(int 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.addComparison

FinanceChart.addComparison

Usage

public LineLayer addComparison(double[] data, int color, String name)

Description

Adds a data series to the main chart for comparison with the closing price.

The data series added will be scaled so that the first visible point in the data series will coincide the first visible point of the main closing price. This facilitate comparing the performance of the closing price with the data series. The data series typically is the closing price of another stock, or the value of a market index.

Arguments

Argument | Default | Description
data | (Mandatory) | An array of numbers representing the data series.
color | (Mandatory) | The color of the line.
name | (Mandatory) | The name of the data series.

Return Value

A LineLayer object representing the comparison line created.


FinanceChart.addSimpleMovingAvg

FinanceChart.addSimpleMovingAvg

Usage

public LineLayer addSimpleMovingAvg(int period, int 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

public LineLayer addExpMovingAvg(int period, int 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

public LineLayer addTriMovingAvg(int period, int 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

public LineLayer addWeightedMovingAvg(int period, int 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.addParabolicSAR

FinanceChart.addParabolicSAR

Usage

public LineLayer addParabolicSAR(double accInitial, double accIncrement, double accMaximum, int symbolType, int symbolSize, int fillColor, int edgeColor)

Description

Adds a parabolic SAR indicator to the main chart.

Arguments

Argument | Default | Description
accInitial | (Mandatory) | The initial acceleration. A common value to use is 0.02.
accIncrement | (Mandatory) | The incremental acceleration. A common value to use is 0.02.
accMaximum | (Mandatory) | The maximum acceleration. A common value to use is 0.2.
symbolType | (Mandatory) | The symbol used to plot the parabolic SAR. One of the predefined shape constants representing the symbol shape. See Shape Specification for the available built-in shapes.
symbolSize | (Mandatory) | The width and height of the symbol in pixels
fillColor | (Mandatory) | The color used to fill the symbol.
edgeColor | (Mandatory) | The edge color used to draw the edge of the symbol.

Return Value

A LineLayer object representing the parabolic SAR created.


FinanceChart.addBand

FinanceChart.addBand

Usage

public InterLineLayer addBand(double[] upperLine, double[] lowerLine, int lineColor, int fillColor, String 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

public InterLineLayer addBollingerBand(int period, double bandWidth, int lineColor, int fillColor)

Description

Adds a Bollinger band to 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

public InterLineLayer addDonchianChannel(int period, int lineColor, int fillColor)

Description

Adds a Donchian channel to 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

public InterLineLayer addEnvelop(int period, double range, int lineColor, int fillColor)

Description

Adds a price envelop to 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

public BarLayer addVolBars(int height, int upColor, int downColor, int 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

public XYChart addIndicator(int 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

public XYChart addLineIndicator(int height, double[] data, int color, String 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

public LineLayer addLineIndicator2(XYChart c, double[] data, int color, String 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

public XYChart addBarIndicator(int height, double[] data, int color, String 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

public BarLayer addBarIndicator2(XYChart c, double[] data, int color, String 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

public void addThreshold(XYChart c, LineLayer layer, double topRange, int topColor, double bottomRange, int 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

public XYChart addAccDist(int height, int 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

public XYChart addAroon(int height, int period, int upColor, int 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

public XYChart addAroonOsc(int height, int period, int 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

public XYChart addADX(int height, int period, int posColor, int negColor, int 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

public XYChart addATR(int height, int period, int color1, int 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

public XYChart addBollingerWidth(int height, int period, double width, int 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

public XYChart addCCI(int height, int period, int color, double range, int upColor, int 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

public XYChart addChaikinMoneyFlow(int height, int period, int 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

public XYChart addChaikinOscillator(int height, int 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

public XYChart addChaikinVolatility(int height, int period1, int period2, int 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

public XYChart addCLV(int height, int 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

public XYChart addDPO(int height, int period, int 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

public XYChart addDonchianWidth(int height, int period, int 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

public XYChart addEaseOfMovement(int height, int period, int color1, int 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

public XYChart addFastStochastic(int height, int period1, int period2, int color1, int 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

public XYChart addMACD(int height, int period1, int period2, int period3, int color, int signalColor, int 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

public XYChart addMassIndex(int height, int color, int upColor, int 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

public XYChart addMFI(int height, int period, int color, double range, int upColor, int 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

public XYChart addMomentum(int height, int period, int 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

public XYChart addNVI(int height, int period, int color, int 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

public XYChart addOBV(int height, int 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

public XYChart addPerformance(int height, int 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

public XYChart addPPO(int height, int period1, int period2, int period3, int color, int signalColor, int 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

public XYChart addPVI(int height, int period, int color, int 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

public XYChart addPVO(int height, int period1, int period2, int period3, int color, int signalColor, int 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

public XYChart addPVT(int height, int 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

public XYChart addROC(int height, int period, int 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

public XYChart addRSI(int height, int period, int color, double range, int upColor, int 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

public XYChart addSlowStochastic(int height, int period1, int period2, int color1, int 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

public XYChart addStdDev(int height, int period, int 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

public XYChart addStochRSI(int height, int period, int color, double range, int upColor, int 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

public XYChart addTRIX(int height, int period, int 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

public XYChart addUltimateOscillator(int height, int period1, int period2, int period3, int color, double range, int upColor, int 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

public XYChart addVolIndicator(int height, int upColor, int downColor, int 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

public XYChart addWilliamR(int height, int period, int color, double range, int upColor, int 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 file system search path for loading image files.
setSearchPath2 | (Self) | Sets the ClassLoader for loading images.
setSearchPath3 | (Self) | Search for image files using the ServletContext and ServletRequest.
setSearchPath4 | (Self) | Search for image files using a URL as the base path.
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.
enableVectorOutput | (Self) | Enables true vector graphics output.
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.
outSVG | (Self) | Writes the DrawArea to a SVG or SVGZ image file.
outSVG2 | (Self) | Writes the DrawArea as a SVG or SVGZ 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 a raster 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.
adjustBrightness | (Self) | Creates a color that is a darkened or brightened version of the given 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

public DrawArea()

Description

Creates a DrawArea object.

Arguments

None

Return Value

The DrawArea object created.


DrawArea.setSize

DrawArea.setSize

Usage

public void setSize(int width, int height [, int 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

public void resize(int newWidth, int newHeight [, int filter [, double 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

public int 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

public int 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

public void setClipRect(int left, int top, int right, int 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

public void setBgColor(int 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

public void move(double xOffset, double yOffset [, int bgColor [, int filter [, double 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

public void rotate(double angle [, int bgColor [, double cx [, double cy [, int filter [, double 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

public void hFlip()

Description

Flip the drawing surface along the central horizontal line.

Arguments

None

Return Value

None


DrawArea.vFlip

DrawArea.vFlip

Usage

public void vFlip()

Description

Flip the drawing surface along the central vertical line.

Arguments

None

Return Value

None


DrawArea.clone

DrawArea.clone

Usage

public void clone(DrawArea d, int x, int y, int align [, int newWidth [, int newHeight [, int filter [, double 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. -1 means no resizing.
newHeight | -1 | The new height to which the current DrawArea will be resized to before copying. -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

public void pixel(int x, int y, int 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

public int getPixel(int x, int 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

public void line(double x1, double y1, double x2, double y2, int c [, int 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

public void hline(int x1, int x2, int y, int 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

public void vline(int y1, int y2, int x, int 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

public void arc(int cx, int cy, int rx, int ry, double a1, double a2, int 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

public void rect(int x1, int y1, int x2, int y2, int edgeColor, int fillColor [, int 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 Chart.glassEffect, Chart.softLighting and Chart.cylinderEffect effects.

Return Value

None


DrawArea.polygon

DrawArea.polygon

Usage

public void polygon(int[] x, int[] y, int edgeColor, int 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

public void surface(double x1, double y1, double x2, double y2, int depthX, int depthY, int edgeColor, int 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

public void sector(int cx, int cy, int rx, int ry, double a1, double a2, int edgeColor, int 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

public void cylinder(int cx, int cy, int rx, int ry, double a1, double a2, int depthX, int depthY, int edgeColor, int 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

public void circle(int cx, int cy, int rx, int ry, int edgeColor, int 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

public void fill(int x, int y, int 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

public void fill2(int x, int y, int color, int 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

public void text(String str, String font, double fontSize, int x, int y, int 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

public void text2(String str, String font, int fontIndex, double fontHeight, double fontWidth, double angle, boolean vertical, int x, int y, int color [, int 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 is ignored in the Java edition of ChartDirector and should be set to 0. It is solely for consistency and compatibility with other editions of ChartDirector.
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 value means the text is layout vertically (from top to bottom). A false 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

public TTFText text3(String str, String font, double 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

public TTFText text4(String text, String font, int fontIndex, double fontHeight, double fontWidth, double angle, boolean 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 is ignored in the Java edition of ChartDirector and should be set to 0. It is solely for consistency and compatibility with other editions of ChartDirector.
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 value means the text is layout vertically (from top to bottom). A false value means the is layout horizontally (from left to right).

Return Value

The TTFText object created.


DrawArea.setDefaultFonts

DrawArea.setDefaultFonts

Usage

public void setDefaultFonts(String normal [, String bold [, String italic [, String 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

public void setFontTable(int index, String 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

public void merge(DrawArea d, int x, int y, int align, int 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

public void tile(DrawArea d, int 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

public void setSearchPath(String path)

Description

Sets the file system 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, if a relative path name is used for an image file, ChartDirector will search for the image file using a ClassLoader (see DrawArea.setSearchPath2 for details), and also in the "current directory".

The setSearchPath method allows you to specify a search path instead of using the "current directory". Multiple directories are supported by separating them with the path separator (";" for Windows and ":" for Linux/UNIX).

If you are using ChartDirector in a web server, you may want to search for the images relative to the current servlet context. Please refer to DrawArea.setSearchPath3 for details.

If you are using ChartDirector in an applet environment, you may want to search for the images based on the "code base" or "document base" of the Applet. Please refer to DrawArea.setSearchPath4 for details.

Arguments

Argument | Default | Description
path | (Mandatory) | A list of directories, separated with the path separator (java.io.File.pathSeparator) of your operating system (";" for Windows, ":" for Linux/UNIX).

Return Value

None


DrawArea.setSearchPath2

DrawArea.setSearchPath2

Usage

public void setSearchPath2(ClassLoader loader[, String path])

Description

Sets the ClassLoader for loading images.

Please refer to DrawArea.setSearchPath for the various methods ChartDirector uses to search for images.

By default, ChartDirector will use a ClassLoader (java.lang.ClassLoader) to search for image files. A ClassLoader will search its class path, using the same method for locating a Java class. A ClassLoader can load the images even if they are inside a JAR file.

In some systems, there are multiple ClassLoaders with different class paths. An example is a JSP web server with multiple servlet contexts. The setSearchPath2 method allows you to specify the ClassLoader to use for loading the images. If you do not specify the ClassLoader to use, ChartDirector will use the ClassLoader that loads ChartDirector itself.

Note that a ClassLoader loads images as Java resources. The image path will be handled as a Java resource path, that is, the path needs to be delimited by "/", and there must be no leading "/".

The setSearchPath2 accepts an optional argument for specifying a search path for searching the image under the class path. Multiple directories are supported by separating them with semi-colons.

To disable searching using the ClassLoader, set the ClassLoader to null.

Arguments

Argument | Default | Description
loader | (Mandatory) | The ClassLoader used to load the resource.
path | null | The package path(s) to prepend to the image path. Multiple directories are supported by separating them with semi-colons.

Return Value

None


DrawArea.setSearchPath3

DrawArea.setSearchPath3

Usage

public void setSearchPath3(ServletContext context[, ServletRequest request[, String path ]])

Description

Search for image files using the ServletContext and ServletRequest.

Please refer to DrawArea.setSearchPath for the various methods ChartDirector uses to search for images.

With setSearchPath3, ChartDirector will use the "servlet context" (that is, the path to the web application) as the root of the image path. For example, if the web application is called "myWebApp", and the image path is "/mydir/imagefile.gif", ChartDirector will locate the image assuming it is a resource at:

http://aaa.bbb.ccc.ddd/myWebApp/mydir/imagefile.gif

If the image path is a relative path, it will be interpreted as relative to the current servlet request path.

The setSearchPath3 accepts an optional argument for specifying a search path for the image. Multiple directories are supported by separating them with semi-colons.

For example, a common practice for many web applications is to put all images files in an "/images" subdirectory. In these cases, you can set the search path to "/images".

Arguments

Argument | Default | Description
context | (Mandatory) | The ServletContext used to resolve absolute paths. This object is usually obtained by using "getServletConfig().getServletContext()" in the Servlet.
request | null | The ServletRequest used to resolve relative paths. In JSP, this is the predefined variable "request". In a servlet, this object is available as the parameter passed in from the doGet or doPost method. null means all paths (relative or absolute) will be resolved using the ServletContext.
path | null | The search path to use. Multiple directories are supported by separating them with semi-colons.

Return Value

None


DrawArea.setSearchPath4

DrawArea.setSearchPath4

Usage

public void setSearchPath4(URL path)

Description

Search for image files using a URL as the base path.

Please refer to DrawArea.setSearchPath for the various methods ChartDirector uses to search for images.

With setSearchPath4, ChartDirector will use the given URL as the base path to load images. This is commonly used in applet applications, in which the applet is running in client machines, but the images are located on server machines.

For example, the following code uses the document base of the applet as the base path for loading images.

c.setSearchPath(getDocumentBase());

Note that in using setSearchPath4, the image path is assumed to be a URL, and the base path is used to resolve the parts of the URL not specified in the image path. This is similar to the paths used in <IMG> tags in web pages.

Arguments

Argument | Default | Description
path | (Mandatory) | An URL acting as the base path for loading images.

Return Value

None


DrawArea.load

DrawArea.load

Usage

public boolean load(String 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 value indicates no error. A false value indicates the operation is unsuccessful.


DrawArea.loadPNG

DrawArea.loadPNG

Usage

public boolean loadPNG(String 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 value indicates no error. A false value indicates the operation is unsuccessful.


DrawArea.loadGIF

DrawArea.loadGIF

Usage

public boolean loadGIF(String 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 value indicates no error. A false value indicates the operation is unsuccessful.


DrawArea.loadJPG

DrawArea.loadJPG

Usage

public boolean loadJPG(String 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 value indicates no error. A false value indicates the operation is unsuccessful.


DrawArea.loadWMP

DrawArea.loadWMP

Usage

public boolean loadWMP(String 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 value indicates no error. A false value indicates the operation is unsuccessful.


DrawArea.rAffineTransform

DrawArea.rAffineTransform

Usage

public void rAffineTransform(double a, double b, double c, double d, double e, double f [, int bgColor [, int filter [, double 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

public void affineTransform(double a, double b, double c, double d, double e, double f [, int bgColor [, int filter [, double 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

public void sphereTransform(int xDiameter, int yDiameter [, int bgColor [, int filter [, double 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

public void hCylinderTransform(int yDiameter [, int bgColor [, int filter [, double 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

public void vCylinderTransform(int xDiameter [, int bgColor [, int filter [, double 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

public void hTriangleTransform([ int tWidth [, int bgColor [, int filter [, double 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

public void vTriangleTransform([ int tHeight [, int bgColor [, int filter [, double 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

public void shearTransform(double xShear [, double yShear [, int bgColor [, int filter [, double 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

public void waveTransform(int period, double amplitude [, double direction [, double startAngle [, boolean longitudinal [, int bgColor [, int filter [, double 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 | Determine if the wave is transversal or longitudinal. true means transversal. false 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.enableVectorOutput

DrawArea.enableVectorOutput

Usage

public void enableVectorOutput()

Description

Enables true vector graphics output.

By default, when creating the output image, ChartDirector draws directly onto an output buffer representing the bitmap of the image. For example, for a chart 800 x 600 pixels in size, the output buffer may represent a 800 x 600 bitmap. The output buffer size is unchanged no matter how many items are drawn onto it. Even if the output contains 1 million elements (eg. 1 million symbols), the size of the output buffer is still the same.

On the other hand, a true vector output is indefinitely scalable and can be considered as having infinite resolution. To produce a true vector output, it is necessary to remember the graphics operations for every element in the output buffer. The output buffer size is therefore proportional to the number of elements to draw.

This method tells ChartDirector that it needs to remember the graphics operations to prepare for true vector output. If true vector output is needed, this method should be called immediately after creating the DrawArea object.

If this method is not called, and a vector graphics output format is used (such as SVG), instead of a true vector output, ChartDirector will output a raster image using the vector graphics format. (Most vector graphics formats support embedded raster images.)

Arguments

None

Return Value

None


DrawArea.out

DrawArea.out

Usage

public boolean out(String 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 value indicates no error. A false value indicates the operation is unsuccessful.


DrawArea.outPNG

DrawArea.outPNG

Usage

public boolean outPNG(String 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 value indicates no error. A false value indicates the operation is unsuccessful.


DrawArea.outPNG2

DrawArea.outPNG2

Usage

public byte[] 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

public boolean outGIF(String 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 value indicates no error. A false value indicates the operation is unsuccessful.


DrawArea.outGIF2

DrawArea.outGIF2

Usage

public byte[] 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

public boolean outJPG(String filename [, int 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 value indicates no error. A false value indicates the operation is unsuccessful.


DrawArea.outJPG2

DrawArea.outJPG2

Usage

public byte[] outJPG2([ int 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

public boolean outBMP(String 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 value indicates no error. A false value indicates the operation is unsuccessful.


DrawArea.outBMP2

DrawArea.outBMP2

Usage

public byte[] 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

public boolean outWMP(String 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 value indicates no error. A false value indicates the operation is unsuccessful.


DrawArea.outWMP2

DrawArea.outWMP2

Usage

public byte[] 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.outSVG

DrawArea.outSVG

Usage

public boolean outSVG(String filename [, String options ])

Description

Writes the DrawArea to a SVG or SVGZ image file.

Note: To output true vector graphics in SVG or SVGZ format, please ensure DrawArea.enableVectorOutput is called immediately after creating the DrawArea object. Otherwise the output will be a bitmap image embedded in SVG or SVGZ.

Arguments

Argument | Default | Description
filename | (Mandatory) | The filename of the output image file.
options | "" | A text string specifying optional parameters for the SVG output. Currently, the only supported text string is "compress", which means to create a SVGZ (compressed SVG) instead of a regular SVG.

Return Value

A true value indicates no error. A false value indicates the operation is unsuccessful.


DrawArea.outSVG2

DrawArea.outSVG2

Usage

public byte[] outSVG2([ String options ])

Description

Writes the DrawArea as a SVG or SVGZ image to memory.

Note: To output true vector graphics in SVG or SVGZ format, please ensure DrawArea.enableVectorOutput is called immediately after creating the DrawArea object. Otherwise the output will be a bitmap image embedded in SVG or SVGZ.

Arguments

Argument | Default | Description
options | "" | A text string specifying optional parameters for the SVG output. Currently, the only supported text string is "compress", which means to create a SVGZ (compressed SVG) instead of a regular SVG.

Return Value

A byte array containing the SVG or SVGZ image.


DrawArea.setPaletteMode

DrawArea.setPaletteMode

Usage

public void setPaletteMode(int 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

public void setDitherMethod(int 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

public void setTransparentColor(int c)

Description

Specifies a certain color to mean transparent when creating a raster 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

public void setAntiAlias([ boolean shapeAntiAlias [, int 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 | A true value enables anti-alias when drawing lines and shapes. A false 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

public void setInterlace(boolean 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 value means the image is interlaced. A false value means the image is non-interlaced.

Return Value

None


DrawArea.setColorTable

DrawArea.setColorTable

Usage

public void setColorTable(int[] colors, int 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

public int getARGBColor(int 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.adjustBrightness

DrawArea.adjustBrightness

Usage

public int adjustBrightness(int c, double brightness)

Description

Creates a color that is a darkened or brightened version of the given color.

A brightness less than 1 means the color is darkened, while a brightness greater than 1 means the color is brightened. For example, a brightness of 0.5 means the color is half as bright as the original color. If the original color is red, the color will become dark red. Conversely, a brightness of 2 means the color is twice as bright as the original color. If the original color is red, the color will become light red.

Arguments

Argument | Default | Description
c | (Mandatory) | The given color.
brightness | (Mandatory) | A non-negative number represent the factor to darken or brighten the color.

Return Value

A 32-bit integer representing the darkened or brightened color.


DrawArea.halfColor

DrawArea.halfColor

Usage

public int halfColor(int 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

public int dashLineColor(int color [, int 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

public int patternColor(int[] colorArray, int height [, int startX, int 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

public int patternColor2(String filename [, int startX, int 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

public int linearGradientColor(int startX, int startY, int endX, int endY, int startColor, int endColor [, boolean 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

public int linearGradientColor2(int startX, int startY, int endX, int endY, int[] colorArray [, boolean 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

public int radialGradientColor(int cx, int cy, int rx, int ry, int startColor, int endColor [, boolean 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

public int radialGradientColor2(int cx, int cy, int rx, int ry, int[] colorArray [, boolean 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

public int gradientColor(int startX, int startY, int endX, int endY, int startColor, int 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

public int gradientColor2(int[] colorArray [, double angle [, double scale [, int startX, int 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

public int reduceColors(int colorCount [, boolean 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 | A true value means the image will be converted to black and white (with grey levels). A false 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

public int 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

public int 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

public int 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

public int 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

public void draw(int x, int y, int color [, int 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

public ArrayMath(double[] 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.


ArrayMath.add

ArrayMath.add

Usage

public ArrayMath add(double[] 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

public ArrayMath add2(double 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

public ArrayMath sub(double[] 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

public ArrayMath sub2(double 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

public ArrayMath mul(double[] 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

public ArrayMath mul2(double 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

public ArrayMath div(double[] 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

public ArrayMath div2(double 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

public ArrayMath financeDiv(double[] b, double 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

public ArrayMath shift([ int offset [, double 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

public ArrayMath delta([ int 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

public ArrayMath rate([ int 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

public ArrayMath 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

public ArrayMath 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

public ArrayMath selectGTZ([ double[] decisionArray [, double 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

public ArrayMath selectGEZ([ double[] decisionArray [, double 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

public ArrayMath selectLTZ([ double[] decisionArray [, double 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

public ArrayMath selectLEZ([ double[] decisionArray [, double 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

public ArrayMath selectEQZ([ double[] decisionArray [, double 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

public ArrayMath selectNEZ([ double[] decisionArray [, double 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

public ArrayMath selectStartOfHour([ int majorTickStep [, double 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. 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

public ArrayMath selectStartOfDay([ int majorTickStep [, double 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. 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

public ArrayMath selectStartOfWeek([ int majorTickStep [, double 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. 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

public ArrayMath selectStartOfMonth([ int majorTickStep [, double 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. 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

public ArrayMath selectStartOfYear([ int majorTickStep [, double 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. 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

public ArrayMath selectRegularSpacing(int majorTickStep [, int minorTickStep [, int 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. 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

public ArrayMath trim([ int startIndex [, int 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

public ArrayMath insert(double[] a [, int 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

public ArrayMath insert2(double c, int len [, int 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

public ArrayMath replace(double a, double 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

public ArrayMath movAvg(int 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

public ArrayMath expAvg(double 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

public ArrayMath movMed(int 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

public ArrayMath movPercentile(int interval, double 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

public ArrayMath movMax(int 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

public ArrayMath movMin(int 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

public ArrayMath movStdDev(int 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

public ArrayMath movCorr(int interval [, double[] 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

public ArrayMath lowess([ double smoothness [, int 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

public ArrayMath lowess2(double[] b [, double smoothness [, int 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

public double[] 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

public double 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

public double 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

public double 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

public double 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

public double 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

public double percentile(double 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

public double 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

public int 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

public int 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

public {double | java.util.Date}[] aggregate({double | java.util.Date}[] srcArray, int aggregateMethod [, double 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.


DBTable

DBTable

DBTable is a utility class for converting database tables into arrays. It retrieves data using a java.sql.ResultSet object, and allows the columns of the data tables to be retrieved as arrays. The data arrays can be used to generate charts or be manipulated further using the ArrayMath class.

Method | Inherited | Description
DBTable | (Self) | Creates a DBTable object and fills the data table with data from a java.sql.ResultSet object.
getCol | (Self) | Gets the requested column of the table as an array of numbers.
getColAsString | (Self) | Gets the requested column of the table as an array of strings.
getColAsDate | (Self) | Gets the requested column of the table as an array of java.util.Date objects.
getColAsObj | (Self) | Gets the requested column of the table as an array of java.lang.Object objects.


DBTable.DBTable

DBTable.DBTable

Usage

public DBTable(java.sql.ResultSet rs) throws java.sql.SQLException

Description

Creates a DBTable object and fills the data table with data from a java.sql.ResultSet object.

Arguments

Argument | Default | Description
table | (Mandatory) | A java.sql.ResultSet object representing the query result.

Return Value

None


DBTable.getCol

DBTable.getCol

Usage

public double[] getCol(int i)

Description

Gets the requested column of the table as an array of numbers.

If the column is actually of type java.util.Date, it will be converted to a number using ChartDirector's date/time representation. The array can then be used directly in ChartDirector APIs.

Arguments

Argument | Default | Description
i | (Mandatory) | The column number. The first column is 0. The nth column is (n - 1).

Return Value

An array of double precision numbers representing the column.


DBTable.getColAsString

DBTable.getColAsString

Usage

public String[] getColAsString(int i)

Description

Gets the requested column of the table as an array of strings.

Arguments

Argument | Default | Description
i | (Mandatory) | The column number. The first column is 0. The nth column is (n - 1).

Return Value

An array of strings representing the column.


DBTable.getColAsDate

DBTable.getColAsDate

Usage

public Date[] getColAsDate(int i)

Description

Gets the requested column of the table as an array of java.util.Date objects.

Arguments

Argument | Default | Description
i | (Mandatory) | The column number. The first column is 0. The nth column is (n - 1).

Return Value

An array of java.util.Date objects representing the column.


DBTable.getColAsObj

DBTable.getColAsObj

Usage

public Object[] getColAsObj(int i)

Description

Gets the requested column of the table as an array of java.lang.Object objects.

Arguments

Argument | Default | Description
i | (Mandatory) | The column number. The first column is 0. The nth column is (n - 1).

Return Value

An array of java.lang.Object objects representing the column.


RanSeries

RanSeries

RanSeries is a utility class to produce random series. It facilitates testing and demonstrating ChartDirector programs without needing a real data source.

Method | Inherited | Description
RanSeries | (Self) | Creates a RanSeries object.
getSeries | (Self) | Gets an array of random number.
getSeries2 | (Self) | Gets an array of numbers that fluctuate randomly.
getDateSeries | (Self) | Gets an array of date/time values.


RanSeries.RanSeries

RanSeries.RanSeries

Usage

public RanSeries(int seed)

Description

Creates a RanSeries object.

Arguments

Argument | Default | Description
seed | (Mandatory) | The seed to be used in the random number generator.

Return Value

The RanSeries object created.


RanSeries.getSeries

RanSeries.getSeries

Usage

public double[] getSeries(int len, double minValue, double maxValue)

Description

Gets an array of random number.

Arguments

Argument | Default | Description
len | (Mandatory) | The number of random values to get.
minValue | (Mandatory) | The minimum value of the random number.
maxValue | (Mandatory) | The maximum value of the random number.

Return Value

An array of random numbers.


RanSeries.getSeries2

RanSeries.getSeries2

Usage

public double[] getSeries2(int len, double startValue, double minDelta, double maxDelta [, double lowerLimit [, double upperLimit ]])

Description

Gets an array of numbers that fluctuate randomly.

Arguments

Argument | Default | Description
len | (Mandatory) | The number of random values to get.
startValue | (Mandatory) | The first value in the sequence.
minDelta | (Mandatory) | The minimum change between two consecutive numbers.
maxDelta | (Mandatory) | The maximum change between two consecutive numbers.
lowerLimit | [-Infinity] | The minimum allowed value of the numbers.
upperLimit | [+Infinity] | The maximum allowed value of the numbers.

Return Value

An array of numbers that fluctuate randomly.


RanSeries.getDateSeries

RanSeries.getDateSeries

Usage

public {java.util.Date | double}[] getDateSeries(int len, {java.util.Date | double} startTime, double tickInc[, boolean weekDayOnly])

Description

Gets an array of date/time values.

Arguments

Argument | Default | Description
len | (Mandatory) | The number of random values to get.
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 | A true value means skipping dates that are not weekdays (Saturday and Sunday). A %F value means no skipping.

Return Value

An array of date/time values.


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.
setCol2 | (Self) | Fill the given column in the RanTable with numbers that fluctuate randomly.
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

public RanTable(int seed, int noOfCols, int 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.


RanTable.setCol

RanTable.setCol

Usage

public void setCol(int colNo, double minValue, double maxValue)

Description

Fill the given column in the RanTable with random numbers.

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

public void setCol2(int colNo, double startValue, double minDelta, double maxDelta [, double lowerLimit [, double upperLimit ]])

Description

Fill the given column in the RanTable with numbers that fluctuate randomly.

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 between two consecutive numbers.
maxDelta | (Mandatory) | The maximum change between two consecutive numbers.
lowerLimit | [-Infinity] | The minimum allowed value of the numbers.
upperLimit | [+Infinity] | The maximum allowed value of the numbers.

Return Value

None


RanTable.setDateCol

RanTable.setDateCol

Usage

public void setDateCol(int i, {double | java.util.Date} startTime, double tickInc [, boolean 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 | A true 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

public void setHLOCCols(int i, double startValue, double minDelta, double maxDelta [, double lowerLimit [, double 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

public int selectDate(int colNo, {double | java.util.Date} minDate, {double | java.util.Date} 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

public double[] getCol(int 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

public FinanceSimulator({int | String} seed, java.util.Date startTime, java.util.Date endTime, int resolution)

Description

Creates a FinanceSimulator object.

Arguments

Argument | Default | Description
seed | (Mandatory) | The seed to be used in the random number generator. It can be an integer or a non-empty text string.
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

public java.util.Date[] 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

public double[] double[] getHighData()

Description

Gets the high data series.

Arguments

None

Return Value

An array containing the high data series.


FinanceSimulator.getLowData

FinanceSimulator.getLowData

Usage

public double[] double[] getLowData()

Description

Gets the low data series.

Arguments

None

Return Value

An array containing the low data series.


FinanceSimulator.getOpenData

FinanceSimulator.getOpenData

Usage

public double[] double[] getOpenData()

Description

Gets the open data series.

Arguments

None

Return Value

An array containing the open data series.


FinanceSimulator.getCloseData

FinanceSimulator.getCloseData

Usage

public double[] double[] getCloseData()

Description

Gets the close data series.

Arguments

None

Return Value

An array containing the close data series.


FinanceSimulator.getVolData

FinanceSimulator.getVolData

Usage

public double[] 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

ChartViewer
ChartViewer is a Java Bean and a SWING component the extends the SWING JLabel control. It is for viewing ChartDirector charts and for providing tool tips, hot spots and view port support. It is primarily used in standalone Java applications or in Applets.

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.


ChartViewer

ChartViewer

The ChartViewer control is a SWING control for viewing ChartDirector charts. It is a subclass of the JLabel control. Apart from displaying the charts, its main functions are to support advanced user interactions with the charts, including:

  • Hot Spot Support

    The ChartViewer control displays tooltips and fires "hot spot mouse events" for hot spots when the mouse is moving or clicking on the hot spot. In the event handler, it provides information about the hot spot that triggers the event.

    The hot spots, with attributes and tool tips, are defined using standard HTML image map format. The BaseChart.getHTMLImageMap method can be used to automatically generate image maps for charts. You may also add your own custom hot spots by appending additional image map to the image map generated by BaseChart.getHTMLImageMap.

  • Programmable Track Cursor Support

    The ChartViewer control includes special methods and events for supporting programmable track cursors. It also manages the dynamic layer for drawing track cursors and other dynamic contents on the chart image.

  • Zoom and Scroll Support

    The ChartViewer control includes special methods and events for supporting using mouse clicks and drags to control the "view port". There are also methods for synchronizing the axis scales with the view port.

ChartViewer Members

The followings are members specific to the ChartViewer control. Members inherited from the JLabel control are omitted. Please refer to Java documentation for members of the JLabel control.

Method | Inherited | Description
ChartViewer | (Self) | Constructor for the ChartViewer component.
setChart | (Self) | Sets a BaseChart object for display.
getChart | (Self) | Gets the BaseChart pointer provided by the previous ChartViewer.setChart method call.
setImage | (Self) | Sets the chart image to view.
getImage | (Self) | Gets the chart image that is being viewed.
setImageMap | (Self) | Sets the image map that defines the hot spots on the chart image.
getImageMap | (Self) | Gets the image map that is currently in use for defining the hot spots.
disposeReference | (Self) | Remove the stored reference to the BaseChart object and image map string set using ChartViewer.setChart and ChartViewer.setImageMap.
getChartMouseX | (Self) | Gets the mouse cursor x-coordinate in the chart pixel coordinate system.
getChartMouseY | (Self) | Gets the mouse cursor y-coordinate in the chart pixel coordinate system.
getPlotAreaMouseX | (Self) | Gets the mouse cursor x-coordinate on the plot area in the chart pixel coordinate system.
getPlotAreaMouseY | (Self) | Gets the mouse cursor y-coordinate on the plot area in the chart pixel coordinate system.
setPlotAreaMouseMargin | (Self) | Sets all margins (left, right, top, and bottom) of the plot area mouse event region to the same value.
setPlotAreaMouseMargin2 | (Self) | Sets the margins of the plot area mouse event region.
removeDynamicLayer | (Self) | Calls BaseChart.removeDynamicLayer when the specified event occurs.
updateDisplay | (Self) | Updates the display.
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.
validateViewPort | (Self) | Ensures the view port left, top, width and height are within valid ranges and adjusts them if necessary.
setMouseUsage | (Self) | Sets the mouse usage mode.
getMouseUsage | (Self) | Gets the mouse usage mode.
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 a java.awt.Color.
getSelectionBorderColor | (Self) | Gets the border color of the zoom selection box.
setHotSpotCursor | (Self) | Sets the cursor that is displayed when the mouse cursor is over a normal hot spot.
getHotSpotCursor | (Self) | Gets the cursor that is displayed when the mouse cursor is over a normal hot spot.
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.
setUpdateInterval | (Self) | Sets the minimum gap interval between two ViewPortChanged events in milliseconds.
getUpdateInterval | (Self) | Gets the minimum gap interval between two ViewPortChanged events in milliseconds.
updateViewPort | (Self) | Triggers the ViewPortChanged event.
setFullRange | (Self) | Defines the full range of a view port data scale.
getValueAtViewPort | (Self) | Converts a view port coordinate to a value of the specified data scale.
getViewPortAtValue | (Self) | Converts a value of the specified data scale to a view port coordinate.
syncLinearAxisWithViewPort | (Self) | Synchronizes a linear Axis with the part of the data scale in view port.
syncLogAxisWithViewPort | (Self) | Synchronizes a logarithmic Axis with the part of the data scale in view port.
syncDateAxisWithViewPort | (Self) | Synchronizes a date/time Axis with the part of the data scale in view port.
isMouseOnPlotArea | (Self) | Checks if the mouse cursor is on the extended plot area.
isInMouseMoveEvent | (Self) | Checks if the current code is executing in a MouseMovedChart or MouseMovedPlotArea event.
isInViewPortChangedEvent | (Self) | Checks if the current code is executing in a ViewPortChanged event.
addTrackCursorListener | (Self) | Adds the specified TrackCursorListener to receive track cursor related events.
removeTrackCursorListener | (Self) | Remove the specified TrackCursorListener so that it no longer receives track cursor related events.
addHotSpotListener | (Self) | Adds the specified HotSpotListener to receive hot spot mouse events.
removeHotSpotListener | (Self) | Remove the specified HotSpotListener so that it no longer receives hot spot mouse events.
addHotSpotMotionListener | (Self) | Adds the specified HotSpotMotionListener to receive hot spot mouse motion events.
removeHotSpotMotionListener | (Self) | Remove the specified HotSpotMotionListener so that it no longer receives hot spot mouse motion events.
addViewPortListener | (Self) | Adds the specified ViewPortListener to receive view port events.
removeViewPortListener | (Self) | Remove the specified ViewPortListener so that it no longer receives view port events.
processHotSpotEvent | (Self) | Process hot spot mouse events.
processHotSpotMotionEvent | (Self) | Process hot spot mouse motion events.
Note: Methods inherited from JLabel are omitted.


ChartViewer.ChartViewer

ChartViewer.ChartViewer

Usage

public ChartViewer()

Description

Constructor for the ChartViewer component.

Arguments

None

Return Value

The ChartViewer object created.


ChartViewer.setChart

ChartViewer.setChart

Usage

public void setChart(BaseChart c)

Description

Sets a BaseChart object for display.

When a BaseChart object is set into the ChartViewer, the ChartViewer will display the chart image, and also collect various chart metrics for supporting view ports. A reference to the BaseChart object will be stored internally, so that it can be retrieved later using this property.

ChartViewer internally does not need the stored BaseChart reference after the chart image is displayed. In systems with very limited memory (such as embedded systems), if the stored BaseChart reference is not needed, the ChartViewer.disposeReference may be used to dispose the reference, so that it may be garbage collected.

Arguments

Argument | Default | Description
c | (Mandatory) | The BaseChart object to be displayed.

Return Value

None


ChartViewer.getChart

ChartViewer.getChart

Usage

public BaseChart getChart()

Description

Gets the BaseChart pointer provided by the previous ChartViewer.setChart method call.

Arguments

None

Return Value

The BaseChart object.


ChartViewer.setImage

ChartViewer.setImage

Usage

public void setImage(Image img)

Description

Sets the chart image to view.

The chart image is usually created using BaseChart.makeImage.

Arguments

Argument | Default | Description
img | (Mandatory) | The image to view.

Return Value

None


ChartViewer.getImage

ChartViewer.getImage

Usage

public Image getImage()

Description

Gets the chart image that is being viewed.

Arguments

None

Return Value

The image being viewed.


ChartViewer.setImageMap

ChartViewer.setImageMap

Usage

public void setImageMap(Strimg imageMap)

Description

Sets the image map that defines the hot spots on the chart image.

The ChartViewer control expects the image map to be in HTML image map format comprising of HTML <AREA> tags. The BaseChart.getHTMLImageMap method can be used to automatically generate image maps for charts.

The advantages of using HTML image map format is that it is easy for developers to customize the hot spots.

For example, one can create custom buttons in the chart image by drawing custom text boxes, and then create custom image maps to define the text boxes as hot spots. These custom image maps can be appended to the image maps generated by BaseChart.getHTMLImageMap using simple string concatenation.

The ChartViewer control will process the various attributes of the HTML <AREA> tags as follows:

Attribute | Description
coords | This attribute defines the position and shape of the hot spot.
href | The URL specified in this attribute will become the attributes of the hot spot. The path portion of the URL will become the path attribute, and the attributes/values of the query parameters will become the attributes/values of the hot spot. When a hot spot event occurs (eg. mouse click), the hot spot attributes will be passed to the event listener as a Hashtable.
title | This attribute defines the tool tip text to display when the mouse moves over and stops on the hot spot. If the mouse is not on top of any hot spot, the default SWING tool tip (set using setToolTipText of the JLabel class).

When the mouse pointer moves over a hot spot, it can change shape to provide user feedback. For example, it can change from an "arrow" to a "hand". The mouse pointers are configured using ChartViewer.setHotSpotCursor.

It is possible to define some hot spots as "silent" hot spots. For these hot spots, the the mouse pointer will not change shape. These are useful if the hot spots are for displaying tool tips only and not clickable.

A hot spot is considered as silent if its <AREA> tag that has no href attribute, or an href attribute with an empty path (but can still contain query parameters), or the path starts with the "~" character.

This method stores a reference to the image map string so that it can be retrieved later using ChartViewer.getImageMap. However, ChartViewer internally does not need the image map string after parsing it with this method. In systems with very limited memory (such as embedded systems), if the image map string is not needed, the ChartViewer.disposeReference may be used to dispose the reference, so that it may be garbage collected.

Arguments

Argument | Default | Description
imageMap | (Mandatory) | The image map that defines the hot spots.

Return Value

None


ChartViewer.getImageMap

ChartViewer.getImageMap

Usage

public String getImageMap()

Description

Gets the image map that is currently in use for defining the hot spots.

Arguments

None

Return Value

The image map currently in use.


ChartViewer.disposeReference

ChartViewer.disposeReference

Usage

public void disposeReference()

Description

Remove the stored reference to the BaseChart object and image map string set using ChartViewer.setChart and ChartViewer.setImageMap.

After calling this method, subsequent calls to ChartViewer.getChart and ChartViewer.getImageMap will return null until another BaseChart or image map is set into the ChartViewer.

This method has no visible effect other than removing the stored references, allowing the BaseChart object and image map string to be garbage collected while the chart is still being displayed. This may be useful in systems with very limited memory (such as embedded systems).

Arguments

None

Return Value

None


ChartViewer.getChartMouseX

ChartViewer.getChartMouseX

Usage

public void getChartMouseX()

Description

Gets the mouse cursor x-coordinate in the chart pixel coordinate system.

This method is only valid when called inside the TrackCursorListener events. events.

Arguments

None

Return Value

The mouse cursor x-coordinate in the chart pixel coordinate system.


ChartViewer.getChartMouseY

ChartViewer.getChartMouseY

Usage

public void getChartMouseY()

Description

Gets the mouse cursor y-coordinate in the chart pixel coordinate system.

This method is only valid when called inside the TrackCursorListener events. events.

Arguments

None

Return Value

The mouse cursor y-coordinate in the chart pixel coordinate system.


ChartViewer.getPlotAreaMouseX

ChartViewer.getPlotAreaMouseX

Usage

public void getPlotAreaMouseX()

Description

Gets the mouse cursor x-coordinate on the plot area in the chart pixel coordinate system.

If the mouse cursor is not on the plot area, but is on the extended plot area (see ChartViewer.setPlotAreaMouseMargin), this method will behave as if the mouse cursor is on the nearest plot area edge.

If the mouse cursor is not even on the extended plot area mouse region, this method will return the last coordinate when the mouse was still on the extended plot area.

This method is only valid when called inside the TrackCursorListener events. events.

Arguments

None

Return Value

The mouse cursor x-coordinate in the chart pixel coordinate system.


ChartViewer.getPlotAreaMouseY

ChartViewer.getPlotAreaMouseY

Usage

public void getPlotAreaMouseY()

Description

Gets the mouse cursor y-coordinate on the plot area in the chart pixel coordinate system.

If the mouse cursor is not on the plot area, but is on the extended plot area (see ChartViewer.setPlotAreaMouseMargin), this method will behave as if the mouse cursor is on the nearest plot area edge.

If the mouse cursor is not even on the extended plot area mouse region, this method will return the last coordinate when the mouse was still on the extended plot area.

This method is only valid when called inside the TrackCursorListener events. events.

Arguments

None

Return Value

The mouse cursor y-coordinate in the chart pixel coordinate system.


ChartViewer.setPlotAreaMouseMargin

ChartViewer.setPlotAreaMouseMargin

Usage

public void setPlotAreaMouseMargin(int m)

Description

Sets all margins (left, right, top, and bottom) of the plot area mouse event region to the same value.

Plot area mouse events are often used for implementing track cursors. For example, a track line can be drawn that follows the mouse cursor when the mouse cursor is moving on the plot area. For these usages, it is important to be able to put the mouse cursor at the edge of the plot area, because the latest data points are usually plotted at the edge.

In practice, it is difficult to put the mouse cursor exactly on the edge, as it is hard to move the mouse cursor precisely. To address this issue, ChartDirector supports extending the plot area mouse event region by a configuration margin. A mouse cursor on that extended region will be treated as if it is on the nearest edge of the plot area for the purpose of trigger plot area mouse events.

By default, the left, right, top and bottom margins of the plot area mouse event region are 5 pixels.

Arguments

Argument | Default | Description
m | (Mandatory) | The left, right, top and bottom margins in pixels.

Return Value

None


ChartViewer.setPlotAreaMouseMargin2

ChartViewer.setPlotAreaMouseMargin2

Usage

public void setPlotAreaMouseMargin2(int leftMargin, int rightMargin, int topMargin, int bottomMargin)

Description

Sets the margins of the plot area mouse event region.

Plot area mouse events are often used for implementing track cursors. For example, a track line can be drawn that follows the mouse cursor when the mouse cursor is moving on the plot area. For these usages, it is important to be able to put the mouse cursor at the edge of the plot area, because the latest data points are usually plotted at the edge.

In practice, it is difficult to put the mouse cursor exactly on the edge, as it is hard to move the mouse cursor precisely. To address this issue, ChartDirector supports extending the plot area mouse event region by a configuration margin. A mouse cursor on that extended region will be treated as if it is on the nearest edge of the plot area for the purpose of trigger plot area mouse events.

By default, the left, right, top and bottom margins of the plot area mouse event region are 5 pixels.

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


ChartViewer.isMouseOnPlotArea

ChartViewer.isMouseOnPlotArea

Usage

public boolean isMouseOnPlotArea()

Description

Checks if the mouse cursor is on the extended plot area.

See ChartViewer.setPlotAreaMouseMargin on what is the extended plot area.

Arguments

None

Return Value

True if the mouse is on the extended plot area, otherwise false.


ChartViewer.removeDynamicLayer

ChartViewer.removeDynamicLayer

Usage

public void removeDynamicLayer(String eventId)

Description

Calls BaseChart.removeDynamicLayer when the specified event occurs.

The dynamic layer (see BaseChart.initDynamicLayer) is commonly used for drawing track cursors. For these type of usages, it is often necessary to clear the dynamic layer when the mouse cursor leaves the plot area. The removeDynamicLayer method can be used in the dynamic layer drawing code to automatically clear the dynamic layer when the specified event occurs. This avoids the need to set up a separate event handler to call BaseChart.removeDynamicLayer.

In the current version of ChartDirector, this method only supports the eventId "MouseExitedChart" and "MouseExitedPlotArea".

This method only applies to the first occurrence of the specified event after calling this method. If this method is called multiple times before the event occurs, only the last call has effect. To cancel this method, use an empty string as the eventId.

Arguments

Argument | Default | Description
eventId | (Mandatory) | The event that causes BaseChart.removeDynamicLayer to be called.

Return Value

None


ChartViewer.updateDisplay

ChartViewer.updateDisplay

Usage

public void updateDisplay()

Description

Updates the display.

If a chart is assigned to a ChartViewer for display, the ChartViewer will automatically display it. If the chart is subsequently modified (eg. by drawing additional things in its dynamic layer - see BaseChart.initDynamicLayer), this method can be used to notify the ChartViewer that the modification has been completed so that it can update the display.

Arguments

None

Return Value

None


ChartViewer.setViewPortLeft

ChartViewer.setViewPortLeft

Usage

public void setViewPortLeft(double 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


ChartViewer.getViewPortLeft

ChartViewer.getViewPortLeft

Usage

public double 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.


ChartViewer.setViewPortTop

ChartViewer.setViewPortTop

Usage

public void setViewPortTop(double 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


ChartViewer.getViewPortTop

ChartViewer.getViewPortTop

Usage

public double 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.


ChartViewer.setViewPortWidth

ChartViewer.setViewPortWidth

Usage

public void setViewPortWidth(double 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


ChartViewer.getViewPortWidth

ChartViewer.getViewPortWidth

Usage

public double 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.


ChartViewer.setViewPortHeight

ChartViewer.setViewPortHeight

Usage

public void setViewPortHeight(double 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


ChartViewer.getViewPortHeight

ChartViewer.getViewPortHeight

Usage

public double 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.


ChartViewer.validateViewPort

ChartViewer.validateViewPort

Usage

public void validateViewPort()

Description

Ensures the view port left, top, width and height are within valid ranges and adjusts them if necessary.

The valid ranges of the view port width and height should be 0 to 1. The view port left should be in between 0 and (1 - view port width). The view port top should be in between 0 and (1 - view port height).

Arguments

None

Return Value

None


ChartViewer.updateViewPort

ChartViewer.updateViewPort

Usage

public void updateViewPort(boolean needUpdateChart, boolean needUpdateImageMap)

Description

Triggers the ViewPortChanged event.

ChartViewer may fire ViewPortChanged events when the mouse clicks or drags on the plot area (see ChartViewer.setMouseUsage). ChartViewer also allows external objects (such as scroll bars, navigation buttons, timers, etc) to modify the view port. This method allows external objects to request ChartViewer to fire ViewPortChanged events.

Many controls are able to update the view port continuously as they are used. For example, a scroll bar may update the view port continuously as the mouse drags on it. For these cases, the chart display may be updated continuously as the view port changes. However, the image map does not need to update until the scrolling is completed (when the mouse button is released on the scroll bar and the mouse moves over the chart surface).

The needUpdateChart argument and needUpdateImageMap argument allows one to specify if the event requires a chart update, and/or an image map update.

For charts with a lot of hot spots and tool tips, the CPU power needed to handle the image map may not be negligible. Removing unnecessary image map updates may increase the update rate when the chart is being updated continuously.

Arguments

Argument | Default | Description
needUpdateChart | (Mandatory) | A boolean value to indicate if the chart needs to be updated.
needUpdateImageMap | (Mandatory) | A boolean value to indicate if the image map needs to be updated.

Return Value

None


ChartViewer.setFullRange

ChartViewer.setFullRange

Usage

public void setFullRange(String id, {double | java.util.Date} minValue, {double | java.util.Date} maxValue)

Description

Defines the full range of a view port data scale.

In the ChartDirector zooming and scrolling framework, the view port coordinates are expressed as the visible fractions of the "full data scale". For example, if the "full data scale" is 10 years horizontally, a view port width of 0.1 means that 1 year of data are visible.

The setFullRange method defines the full range of a data scale and gives it a name. As ChartDirector supports multiple x-axes and y-axes, so there can be multiple data scales with different names. The name can be used in other ChartDirector APIs to convert between the view port coordinates and data scale (see ChartViewer.getValueAtViewPort, ChartViewer.getViewPortAtValue), and to configure an Axis to reflect the visible data scale (see ChartViewer.syncLinearAxisWithViewPort, ChartViewer.syncLogAxisWithViewPort and ChartViewer.syncDateAxisWithViewPort).

Arguments

Argument | Default | Description
id | (Mandatory) | The name of the data scale.
minValue | (Mandatory) | The minimum value of the data scale.
maxValue | (Mandatory) | The maximum value of the data scale.

Return Value

None


ChartViewer.getValueAtViewPort

ChartViewer.getValueAtViewPort

Usage

public double getValueAtViewPort(String id, double vpCoor [, boolean isLogScale ])

Description

Converts a view port coordinate to a value of the specified data scale.

Please refer to ChartViewer.setFullRange on how to define a data scale.

This method always returns a numeric value. If the axis scale is a date/time scale, and you are expecting a java.util.Date data type, please use Chart.NTime to convert the number to the java.util.Date data type.

Arguments

Argument | Default | Description
id | (Mandatory) | The name of the data scale.
vpCoor | (Mandatory) | The view port coordinate.
isLogScale | false | true if the conversion is based on a logarithmic scale. false if the conversion is based on a non-logarithmic scale.

Return Value

The value of the specified data scale at the view port coordinate.


ChartViewer.getViewPortAtValue

ChartViewer.getViewPortAtValue

Usage

public double getViewPortAtValue(String id, double value [, boolean isLogScale ])

Description

Converts a value of the specified data scale to a view port coordinate.

Please refer to ChartViewer.setFullRange on how to define a data scale.

This method only accepts numeric values as input. If the axis scale is a date/time scale, and you are using a java.util.Date value, please use Chart.CTime to convert it to a number.

Arguments

Argument | Default | Description
id | (Mandatory) | The name of the data scale.
value | (Mandatory) | The value to be converted.
isLogScale | false | true if the conversion is based on a logarithmic scale. false if the conversion is based on a non-logarithmic scale.

Return Value

The view port coordinate at the value of the specified data scale.


ChartViewer.syncLinearAxisWithViewPort

ChartViewer.syncLinearAxisWithViewPort

Usage

public void syncLinearAxisWithViewPort(String id, Axis axis)

Description

Synchronizes a linear Axis with the part of the data scale in view port.

If the data scale has already been defined (see ChartViewer.setFullRange on how to define a data scale), this method will compute the visible data scale based on the view port coordinates using linear interpolation, and then sets the axis to that linear scale.

If the data scale has not been defined, this method will define the data scale based on the axis scale and the the view port coordinates using linear extrapolation. Because the axis scale may not be known at the time of calling this method (the axis could be auto-scaled by ChartDirector, which may not occur until the chart is rendered), the definition of the data scale will not occur immediately, but will be pending until the chart is to be displayed.

If your charting code calls this method but never defines the full data scale or the view port coordinates (in which case the view port defaults to showing the complete data scale), then the first time the code is executed, the data scale will be defined to be equal to the axis scale. Subsequently, when the user zooms into the chart (which means the view port coordinates are changed), the same charting code will set up the axis scale to the range that the user has zoomed to.

Arguments

Argument | Default | Description
id | (Mandatory) | The name of the data scale.
axis | (Mandatory) | The Axis object to synchronize with.

Return Value

None


ChartViewer.syncLogAxisWithViewPort

ChartViewer.syncLogAxisWithViewPort

Usage

public void syncLogAxisWithViewPort(String id, Axis axis)

Description

Synchronizes a logarithmic Axis with the part of the data scale in view port.

If the data scale has already been defined (see ChartViewer.setFullRange on how to define a data scale), this method will compute the visible data scale based on the view port coordinates using logarithmic interpolation, and then sets the axis to that logarithmic scale.

If the data scale has not been defined, this method will define the data scale based on the axis scale and the the view port coordinates using logarithmic extrapolation. Because the axis scale may not be known at the time of calling this method (the axis could be auto-scaled by ChartDirector, which may not occur until the chart is rendered), the definition of the data scale will not occur immediately, but will be pending until the chart is to be displayed.

If your charting code calls this method but never defines the full data scale or the view port coordinates (in which case the view port defaults to showing the complete data scale), then the first time the code is executed, the data scale will be defined to be equal to the axis scale. Subsequently, when the user zooms into the chart (which means the view port coordinates are changed), the same charting code will set up the axis scale to the range that the user has zoomed to.

Arguments

Argument | Default | Description
id | (Mandatory) | The name of the data scale.
axis | (Mandatory) | The Axis object to synchronize with.

Return Value

None


ChartViewer.syncDateAxisWithViewPort

ChartViewer.syncDateAxisWithViewPort

Usage

public void syncDateAxisWithViewPort(String id, Axis axis)

Description

Synchronizes a date/time Axis with the part of the data scale in view port.

If the data scale has already been defined (see ChartViewer.setFullRange on how to define a data scale), this method will compute the visible data scale based on the view port coordinates using date/time interpolation, and then sets the axis to that date/time scale.

If the data scale has not been defined, this method will define the data scale based on the axis scale and the the view port coordinates using date/time extrapolation. Because the axis scale may not be known at the time of calling this method (the axis could be auto-scaled by ChartDirector, which may not occur until the chart is rendered), the definition of the data scale will not occur immediately, but will be pending until the chart is to be displayed.

If your charting code calls this method but never defines the full data scale or the view port coordinates (in which case the view port defaults to showing the complete data scale), then the first time the code is executed, the data scale will be defined to be equal to the axis scale. Subsequently, when the user zooms into the chart (which means the view port coordinates are changed), the same charting code will set up the axis scale to the range that the user has zoomed to.

Arguments

Argument | Default | Description
id | (Mandatory) | The name of the data scale.
axis | (Mandatory) | The Axis object to synchronize with.

Return Value

None


ChartViewer.setMouseUsage

ChartViewer.setMouseUsage

Usage

public void setMouseUsage(int mouseUsage)

Description

Sets the mouse usage mode.

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 ChartViewer.setImageMap on how to define an image map for a chart.
MouseUsageScrollOnDrag1The mouse is used for drag scrolling the chart.

In addition to the default mouse behaviour, when the mouse drags on the plot area, the mouse cursor will change to a scroll cursor, the view port coordinates will shift to reflect the amount dragged, and ViewPortChanged events will be fired.
MouseUsageScrollOnDrop2The mouse is used for drag scrolling the chart.

In addition to the default mouse behaviour, 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 ViewPortChanged event will be fired.
MouseUsageZoomIn3The mouse is used for zoom in actions.

In addition to the default mouse behaviour, 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 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 ChartViewer.setZoomInRatio, and a ViewPortChanged event will be fired.
MouseUsageZoomOut4The mouse is used for zoom out actions.

In addition to the default mouse behaviour, 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 ChartViewer.setZoomOutRatio, and a ViewPortChanged event will be fired.

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


ChartViewer.getMouseUsage

ChartViewer.getMouseUsage

Usage

public int getMouseUsage()

Description

Gets the mouse usage mode.

Arguments

None

Return Value

An integer representing the mouse usage mode. See ChartViewer.setMouseUsage for the meaning of this value.


ChartViewer.setZoomDirection

ChartViewer.setZoomDirection

Usage

public void setZoomDirection(int 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 ChartViewer.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


ChartViewer.getZoomDirection

ChartViewer.getZoomDirection

Usage

public int getZoomDirection()

Description

Gets the zoom direction for mouse zoom in/out actions.

Please refer to ChartViewer.setZoomDirection for the supported directions.

Arguments

None

Return Value

An integer representing the zoom direction.


ChartViewer.setScrollDirection

ChartViewer.setScrollDirection

Usage

public void setScrollDirection(int direction)

Description

Sets the scroll direction for mouse scroll actions.

Please refer to ChartViewer.setZoomDirection for the supported directions.

Arguments

Argument | Default | Description
direction | (Mandatory) | The scroll direction for mouse scroll actions.

Return Value

None


ChartViewer.getScrollDirection

ChartViewer.getScrollDirection

Usage

public int getScrollDirection()

Description

Gets the scroll direction for mouse scroll actions.

Please refer to ChartViewer.setZoomDirection for the supported directions.

Arguments

None

Return Value

An integer representing the scroll direction.


ChartViewer.setZoomInRatio

ChartViewer.setZoomInRatio

Usage

public void setZoomInRatio(double 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


ChartViewer.getZoomInRatio

ChartViewer.getZoomInRatio

Usage

public double 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.


ChartViewer.setZoomOutRatio

ChartViewer.setZoomOutRatio

Usage

public void setZoomOutRatio(double 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


ChartViewer.getZoomOutRatio

ChartViewer.getZoomOutRatio

Usage

public double 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.


ChartViewer.setZoomInWidthLimit

ChartViewer.setZoomInWidthLimit

Usage

public void setZoomInWidthLimit(double 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


ChartViewer.getZoomInWidthLimit

ChartViewer.getZoomInWidthLimit

Usage

public double 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 ChartViewer.setZoomInWidthLimit for the meaning of this value.


ChartViewer.setZoomOutWidthLimit

ChartViewer.setZoomOutWidthLimit

Usage

public void setZoomOutWidthLimit(double 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


ChartViewer.getZoomOutWidthLimit

ChartViewer.getZoomOutWidthLimit

Usage

public double 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 ChartViewer.setZoomOutWidthLimit for the meaning of this value.


ChartViewer.setZoomInHeightLimit

ChartViewer.setZoomInHeightLimit

Usage

public void setZoomInHeightLimit(double 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


ChartViewer.getZoomInHeightLimit

ChartViewer.getZoomInHeightLimit

Usage

public double 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 ChartViewer.setZoomInHeightLimit for the meaning of this value.


ChartViewer.setZoomOutHeightLimit

ChartViewer.setZoomOutHeightLimit

Usage

public void setZoomOutHeightLimit(double 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


ChartViewer.getZoomOutHeightLimit

ChartViewer.getZoomOutHeightLimit

Usage

public double 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 ChartViewer.setZoomOutHeightLimit for the meaning of this value.


ChartViewer.setMinimumDrag

ChartViewer.setMinimumDrag

Usage

public void setMinimumDrag(int 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


ChartViewer.getMinimumDrag

ChartViewer.getMinimumDrag

Usage

public int 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 ChartViewer.setMinimumDrag for the meaning of this value.


ChartViewer.setSelectionBorderWidth

ChartViewer.setSelectionBorderWidth

Usage

public void setSelectionBorderWidth(int 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


ChartViewer.getSelectionBorderWidth

ChartViewer.getSelectionBorderWidth

Usage

public int 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.


ChartViewer.setSelectionBorderColor

ChartViewer.setSelectionBorderColor

Usage

public void setSelectionBorderColor(java.awt.Color color)

Description

Sets the border color of the zoom selection box as a java.awt.Color.

Arguments

Argument | Default | Description
color | (Mandatory) | The border color as a java.awt.Color.

Return Value

None


ChartViewer.getSelectionBorderColor

ChartViewer.getSelectionBorderColor

Usage

public java.awt.Color getSelectionBorderColor()

Description

Gets the border color of the zoom selection box.

Arguments

None

Return Value

The border color of the zoom selection box as a java.awt.Color.


ChartViewer.setHotSpotCursor

ChartViewer.setHotSpotCursor

Usage

public void setHotSpotCursor(Cursor cursor)

Description

Sets the cursor that is displayed when the mouse cursor is over a normal hot spot.

Arguments

Argument | Default | Description
cursor | (Mandatory) | The java.awt.Cursor object to display when the mouse is over a normal hot spot.

Return Value

None


ChartViewer.getHotSpotCursor

ChartViewer.getHotSpotCursor

Usage

public void getHotSpotCursor(Cursor cursor)

Description

Gets the cursor that is displayed when the mouse cursor is over a normal hot spot.

Arguments

None

Return Value

The java.awt.Cursor object to display when the mouse is over a normal hot spot.


ChartViewer.setZoomInCursor

ChartViewer.setZoomInCursor

Usage

public void setZoomInCursor(Cursor cursor)

Description

Sets the mouse cursor to be used when the mouse is used for zoom in.

Arguments

Argument | Default | Description
cursor | (Mandatory) | The mouse cursor to be used when the mouse is used for zoom in.

Return Value

None


ChartViewer.getZoomInCursor

ChartViewer.getZoomInCursor

Usage

public Cursor 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.


ChartViewer.setZoomOutCursor

ChartViewer.setZoomOutCursor

Usage

public void setZoomOutCursor(Cursor cursor)

Description

Sets the mouse cursor to be used when the mouse is used for zoom out.

Arguments

Argument | Default | Description
cursor | (Mandatory) | The mouse cursor to be used when the mouse is used for zoom out.

Return Value

None


ChartViewer.getZoomOutCursor

ChartViewer.getZoomOutCursor

Usage

public Cursor 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.


ChartViewer.setNoZoomCursor

ChartViewer.setNoZoomCursor

Usage

public void setNoZoomCursor(Cursor 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.

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


ChartViewer.getNoZoomCursor

ChartViewer.getNoZoomCursor

Usage

public Cursor 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.


ChartViewer.setScrollCursor

ChartViewer.setScrollCursor

Usage

public void setScrollCursor(Cursor cursor)

Description

Sets the mouse cursor to be used when the mouse is used for scrolling.

Arguments

Argument | Default | Description
cursor | (Mandatory) | The mouse cursor to be used when the mouse is used for scrolling.

Return Value

None


ChartViewer.getScrollCursor

ChartViewer.getScrollCursor

Usage

public Cursor 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.


ChartViewer.setUpdateInterval

ChartViewer.setUpdateInterval

Usage

public void setUpdateInterval(int interval)

Description

Sets the minimum gap interval between two ViewPortChanged events in milliseconds.

Some GUI designs may be capable of generate a lot of ViewPortListener.viewPortChanged events rapidly. For example, an external scroll bar may update the view port and call ChartViewer.updateViewPort rapidly and repeatedly when it is scrolling. As the chart is usually updated in the main GUI thread, updating too rapidly without a gap interval in between may cause other GUI elements to become sluggish.

This method specifies the minimum gap interval between two ViewPortChanged events. The default is 20ms.

If a ViewPortChanged event needs to be fired during the gap interval, the event will be delayed and fired after the gap interval.

If multiple ViewPortChanged events needs to be fired during the gap interval, they will be merged into one event, and be fired after the gap interval.

Arguments

Argument | Default | Description
interval | (Mandatory) | The minimum gap interval between two ViewPortChanged events in milliseconds.

Return Value

None


ChartViewer.getUpdateInterval

ChartViewer.getUpdateInterval

Usage

public int getUpdateInterval()

Description

Gets the minimum gap interval between two ViewPortChanged events in milliseconds.

Arguments

None

Return Value

The minimum gap interval between two ViewPortChanged events in milliseconds. See ChartViewer.setUpdateInterval for the meaning of this value.


ChartViewer.addTrackCursorListener

ChartViewer.addTrackCursorListener

Usage

public void addTrackCursorListener(TrackCursorListener listener)

Description

Adds the specified TrackCursorListener to receive track cursor related events.

Arguments

Argument | Default | Description
listener | (Mandatory) | The TrackCursorListener object to receive track cursor related events.

Return Value

None


ChartViewer.removeTrackCursorListener

ChartViewer.removeTrackCursorListener

Usage

public void removeTrackCursorListener(TrackCursorListener listener)

Description

Remove the specified TrackCursorListener so that it no longer receives track cursor related events.

Arguments

Argument | Default | Description
listener | (Mandatory) | The TrackCursorListener object to remove.

Return Value

None


ChartViewer.addHotSpotListener

ChartViewer.addHotSpotListener

Usage

public void addHotSpotListener(HotSpotListener listener)

Description

Adds the specified HotSpotListener to receive hot spot mouse events.

The HotSpotListener is similar to java.awt.event.MouseListener. Instead of listening to general mouse events, the HotSpotListener listens to mouse events occurred on the hot spots only, and supply the event listener with hot spot attributes.

Arguments

Argument | Default | Description
listener | (Mandatory) | The HotSpotListener object to receive hot spot mouse events.

Return Value

None


ChartViewer.removeHotSpotListener

ChartViewer.removeHotSpotListener

Usage

public void removeHotSpotListener(HotSpotListener listener)

Description

Remove the specified HotSpotListener so that it no longer receives hot spot mouse events.

Arguments

Argument | Default | Description
listener | (Mandatory) | The HotSpotListener object to remove.

Return Value

None


ChartViewer.addHotSpotMotionListener

ChartViewer.addHotSpotMotionListener

Usage

public void addHotSpotMotionListener(HotSpotMotionListener listener)

Description

Adds the specified HotSpotMotionListener to receive hot spot mouse motion events.

The HotSpotMotionListener is similar to java.awt.event.MouseMotionListener. Instead of listening to general mouse motion events, the HotSpotListener listens to mouse motion events occurred over the hot spots only, and supply the event listener with hot spot attributes.

Arguments

Argument | Default | Description
listener | (Mandatory) | The HotSpotMotionListener object to receive hot spot mouse events.

Return Value

None


ChartViewer.removeHotSpotMotionListener

ChartViewer.removeHotSpotMotionListener

Usage

public void removeHotSpotMotionListener(HotSpotMotionListener listener)

Description

Remove the specified HotSpotMotionListener so that it no longer receives hot spot mouse motion events.

Arguments

Argument | Default | Description
listener | (Mandatory) | The HotSpotMotionListener object to remove.

Return Value

None


ChartViewer.addViewPortListener

ChartViewer.addViewPortListener

Usage

public void addViewPortListener(ViewPortListener listener)

Description

Adds the specified ViewPortListener to receive view port events.

Currently, view port events include the "view port changed" event and the "selection changed" event. The "view port changed" event occurs when the view port is changed by mouse actions (see ChartViewer.setMouseUsage), or ChartViewer.updateViewPort is called. The "selection changed" event occurs when the selection box is changed (becomes visible or invisible or change in size) by "drag to select" mouse actions.

Arguments

Argument | Default | Description
listener | (Mandatory) | The ViewPortListener object to receive view port events.

Return Value

None


ChartViewer.removeViewPortListener

ChartViewer.removeViewPortListener

Usage

public void removeViewPortListener(ViewPortListener listener)

Description

Remove the specified ViewPortListener so that it no longer receives view port events.

Arguments

Argument | Default | Description
listener | (Mandatory) | The ViewPortListener object to remove.

Return Value

None


ChartViewer.processHotSpotEvent

ChartViewer.processHotSpotEvent

Usage

protected void processHotSpotEvent(HotSpotEvent e)

Description

Process hot spot mouse events.

The system will call this method whenever a hot spot mouse event occurs. If you override this method, remember to invoke the superclass's processHotSpotEvent method for proper functioning of hot spot user interactions.

Arguments

Argument | Default | Description
e | (Mandatory) | The HotSpotEvent object containing data for the hot spot mouse event.

Return Value

None


ChartViewer.processHotSpotMotionEvent

ChartViewer.processHotSpotMotionEvent

Usage

protected void processHotSpotMotionEvent(HotSpotEvent e)

Description

Process hot spot mouse motion events.

The system will call this method whenever a hot spot mouse motion event occur. If you override this method, remember to invoke the superclass's processHotSpotMotionEvent method for proper functioning of hot spot user interactions.

Arguments

Argument | Default | Description
e | (Mandatory) | The HotSpotEvent object containing data for the hot spot mouse motion event.

Return Value

None


ChartViewer.isInMouseMoveEvent

ChartViewer.isInMouseMoveEvent

Usage

public boolean isInMouseMoveEvent()

Description

Checks if the current code is executing in a MouseMovedChart or MouseMovedPlotArea event.

Arguments

None

Return Value

True if the current code is executing in a TrackCursorListener.mouseMovedChart event or TrackCursorListener.mouseMovedPlotArea event , otherwise false.


ChartViewer.isInViewPortChangedEvent

ChartViewer.isInViewPortChangedEvent

Usage

public boolean isInViewPortChangedEvent()

Description

Checks if the current code is executing in a ViewPortChanged event.

This is to help preventing "event looping" in complicated GUI designs in which multiple controls can update the view port and indirectly update each others.

For example, suppose in a scrollable chart design, the x-axis can be scrolled by both a scroll bar control and a date/time picker control. That means both scroll bar and date/time picker events may update the view port

The following sequence of events may happen:

  • User changes the start date on the x-axis using the date/time picker control.

  • The view port is updated, so ChartViewer.updateViewPort is called, triggering a ViewPortListener.viewPortChanged event.

  • In the ViewPortChanged event handler, the scroll bar position needs to be updated to reflect that the view port has moved.

  • As the scroll bar has changed, a scroll bar event occurs. The scroll bar event handler may update the view port and call ChartViewer.updateViewPort again.

The above is potentially an infinite loop as the ViewPortChanged event will keep firing again and again. To avoid this, ChartViewer.updateViewPort will perform no action if it is called within ViewPortChanged event. So the last step above cannot actually trigger another ViewPortChanged event. This avoids the infinite loop.

Internally, ChartViewer.updateViewPort use this method to checks if it is called within a ViewPortChanged event, and ignores the request if it is already in the event. This method allows external code to also change behaviour in a ViewPortChanged event.

Arguments

None

Return Value

True if the current code is executing in a ViewPortListener.viewPortChanged event, otherwise false.


TrackCursorListener

TrackCursorListener

TrackCursorListener is an interface for receiving mouse events related to programming track cursors.

To handle these events, either implement this interface, or extend the abstract class TrackCursorAdapter overriding only the methods of interest. ChartViewer.addTrackCursorListener can then be used to register the handler object to the ChartViewer.

Method | Inherited | Description
mouseMovedPlotArea | (Self) | The system will call this method when the mouse moves over the extended plot area.
mouseExitedPlotArea | (Self) | The system will call this method when the mouse leaves the extended plot area.
mouseMovedChart | (Self) | The system will call this method when the mouse moves over the chart.
mouseExitedChart | (Self) | The system will call this method when the mouse leaves the chart.


TrackCursorListener.mouseMovedChart

TrackCursorListener.mouseMovedChart

Usage

public void mouseMovedChart(MouseEvent e)

Description

The system will call this method when the mouse moves over the chart.

When handling this event, ChartViewer.getChartMouseX, ChartViewer.getChartMouseY, ChartViewer.getPlotAreaMouseX and ChartViewer.getChartMouseY can be used to obtain the mouse cursor position in the chart pixel coordinate system.

Arguments

Argument | Default | Description
e | (Mandatory) | A standard java.awt.event.MouseEvent object containing information about the mouse events.

Return Value

None


TrackCursorListener.mouseExitedChart

TrackCursorListener.mouseExitedChart

Usage

public void mouseExitedChart(MouseEvent e)

Description

The system will call this method when the mouse leaves the chart.

When handling this event, ChartViewer.getChartMouseX, ChartViewer.getChartMouseY, ChartViewer.getPlotAreaMouseX and ChartViewer.getChartMouseY can be used to obtain the mouse cursor position in the chart pixel coordinate system.

Arguments

Argument | Default | Description
e | (Mandatory) | A standard java.awt.event.MouseEvent object containing information about the mouse events.

Return Value

None


TrackCursorListener.mouseMovedPlotArea

TrackCursorListener.mouseMovedPlotArea

Usage

public void mouseMovedPlotArea(MouseEvent e)

Description

The system will call this method when the mouse moves over the extended plot area.

See ChartViewer.setPlotAreaMouseMargin on what is the extended plot area.

When handling this event, ChartViewer.getChartMouseX, ChartViewer.getChartMouseY, ChartViewer.getPlotAreaMouseX and ChartViewer.getChartMouseY can be used to obtain the mouse cursor position in the chart pixel coordinate system.

Arguments

Argument | Default | Description
e | (Mandatory) | A standard java.awt.event.MouseEvent object containing information about the mouse events.

Return Value

None


TrackCursorListener.mouseExitedPlotArea

TrackCursorListener.mouseExitedPlotArea

Usage

public void mouseExitedPlotArea(MouseEvent e)

Description

The system will call this method when the mouse leaves the extended plot area.

See ChartViewer.setPlotAreaMouseMargin on what is the extended plot area.

When handling this event, ChartViewer.getChartMouseX, ChartViewer.getChartMouseY, ChartViewer.getPlotAreaMouseX and ChartViewer.getChartMouseY can be used to obtain the mouse cursor position in the chart pixel coordinate system.

Arguments

Argument | Default | Description
e | (Mandatory) | A standard java.awt.event.MouseEvent object containing information about the mouse events.

Return Value

None


TrackCursorAdapter

TrackCursorAdapter

%class is an abstract class that provides a default implementation of the TrackCursorListener interface with empty methods. This class allows TrackCursorListener objects to be created conveniently, as only the methods for the events of interest need to be overridden.

Method | Inherited | Description
mouseMovedPlotArea | (Self) | The system will call this method when the mouse moves over the extended plot area.
mouseExitedPlotArea | (Self) | The system will call this method when the mouse leaves the extended plot area.
mouseMovedChart | (Self) | The system will call this method when the mouse moves over the chart.
mouseExitedChart | (Self) | The system will call this method when the mouse leaves the chart.


TrackCursorAdapter.mouseMovedChart

TrackCursorAdapter.mouseMovedChart

Usage

public void mouseMovedChart(MouseEvent e)

Description

The system will call this method when the mouse moves over the chart.

The default implementation does nothing. Override to process this event.

Arguments

None

Return Value

None


TrackCursorAdapter.mouseExitedChart

TrackCursorAdapter.mouseExitedChart

Usage

public void mouseExitedChart(MouseEvent e)

Description

The system will call this method when the mouse leaves the chart.

The default implementation does nothing. Override to process this event.

Arguments

None

Return Value

None


TrackCursorAdapter.mouseMovedPlotArea

TrackCursorAdapter.mouseMovedPlotArea

Usage

public void mouseMovedPlotArea(MouseEvent e)

Description

The system will call this method when the mouse moves over the extended plot area.

The default implementation does nothing. Override to process this event.

Arguments

None

Return Value

None


TrackCursorAdapter.mouseExitedPlotArea

TrackCursorAdapter.mouseExitedPlotArea

Usage

public void mouseExitedPlotArea(MouseEvent e)

Description

The system will call this method when the mouse leaves the extended plot area.

The default implementation does nothing. Override to process this event.

Arguments

None

Return Value

None


HotSpotListener

HotSpotListener

HotSpotListener is an interface for receiving hot spot mouse events (press, release, click, enter, and exit). It is similar to java.awt.event.MouseListener, except that it applies to mouse events that occur over hot spots.

(To track hot spot mouse moves and drags, use the HotSpotMotionListener.)

To handle these events, either implement this interface, or extend the abstract class HotSpotAdapter overriding only the methods of interest. ChartViewer.addHotSpotListener can then be used to register the handler object to the ChartViewer.

Method | Inherited | Description
hotSpotClicked | (Self) | The system will call this method when the mouse clicks on a hot spot.
hotSpotEntered | (Self) | The system will call this method when the mouse enters a hot spot region.
hotSpotExited | (Self) | The system will call this method when the mouse leaves a hot spot region.
hotSpotPressed | (Self) | The system will call this method when the mouse is over a hot spot region and a mouse button is pressed.
hotSpotReleased | (Self) | The system will call this method when the mouse is over a hot spot region and a mouse button is released.


HotSpotListener.hotSpotClicked

HotSpotListener.hotSpotClicked

Usage

public void hotSpotClicked(HotSpotEvent e)

Description

The system will call this method when the mouse clicks on a hot spot.

Arguments

Argument | Default | Description
e | (Mandatory) | A HotSpotEvent object containing data of the hot spot event.

Return Value

None


HotSpotListener.hotSpotEntered

HotSpotListener.hotSpotEntered

Usage

public void hotSpotEntered(HotSpotEvent e)

Description

The system will call this method when the mouse enters a hot spot region.

Arguments

Argument | Default | Description
e | (Mandatory) | A HotSpotEvent object containing data of the hot spot event.

Return Value

None


HotSpotListener.hotSpotExited

HotSpotListener.hotSpotExited

Usage

public void hotSpotExited(HotSpotEvent e)

Description

The system will call this method when the mouse leaves a hot spot region.

Arguments

Argument | Default | Description
e | (Mandatory) | A HotSpotEvent object containing data of the hot spot event.

Return Value

None


HotSpotListener.hotSpotPressed

HotSpotListener.hotSpotPressed

Usage

public void hotSpotPressed(HotSpotEvent e)

Description

The system will call this method when the mouse is over a hot spot region and a mouse button is pressed.

Arguments

Argument | Default | Description
e | (Mandatory) | A HotSpotEvent object containing data of the hot spot event.

Return Value

None


HotSpotListener.hotSpotReleased

HotSpotListener.hotSpotReleased

Usage

public void hotSpotReleased(HotSpotEvent e)

Description

The system will call this method when the mouse is over a hot spot region and a mouse button is released.

Arguments

Argument | Default | Description
e | (Mandatory) | A HotSpotEvent object containing data of the hot spot event.

Return Value

None


HotSpotAdapter

HotSpotAdapter

%class is an abstract class that provides a default implementation of the HotSpotListener interface with empty methods. This class allows HotSpotListener objects to be created conveniently, as only the methods for the events of interest need to be overridden.

Method | Inherited | Description
hotSpotClicked | (Self) | The system will call this method when the mouse clicks on a hot spot.
hotSpotEntered | (Self) | The system will call this method when the mouse enters a hot spot region.
hotSpotExited | (Self) | The system will call this method when the mouse leaves a hot spot region.
hotSpotPressed | (Self) | The system will call this method when the mouse is over a hot spot region and a mouse button is pressed.
hotSpotReleased | (Self) | The system will call this method when the mouse is over a hot spot region and a mouse button is released.


HotSpotAdapter.hotSpotClicked

HotSpotAdapter.hotSpotClicked

Usage

public void hotSpotClicked(HotSpotEvent e)

Description

The system will call this method when the mouse clicks on a hot spot.

The default implementation does nothing. Override to process this event.

Arguments

Argument | Default | Description
e | (Mandatory) | A HotSpotEvent object containing data of the hot spot event.

Return Value

None


HotSpotAdapter.hotSpotEntered

HotSpotAdapter.hotSpotEntered

Usage

public void hotSpotEntered(HotSpotEvent e)

Description

The system will call this method when the mouse enters a hot spot region.

The default implementation does nothing. Override to process this event.

Arguments

Argument | Default | Description
e | (Mandatory) | A HotSpotEvent object containing data of the hot spot event.

Return Value

None


HotSpotAdapter.hotSpotExited

HotSpotAdapter.hotSpotExited

Usage

public void hotSpotExited(HotSpotEvent e)

Description

The system will call this method when the mouse leaves a hot spot region.

The default implementation does nothing. Override to process this event.

Arguments

Argument | Default | Description
e | (Mandatory) | A HotSpotEvent object containing data of the hot spot event.

Return Value

None


HotSpotAdapter.hotSpotPressed

HotSpotAdapter.hotSpotPressed

Usage

public void hotSpotPressed(HotSpotEvent e)

Description

The system will call this method when the mouse is over a hot spot region and a mouse button is pressed.

The default implementation does nothing. Override to process this event.

Arguments

Argument | Default | Description
e | (Mandatory) | A HotSpotEvent object containing data of the hot spot event.

Return Value

None


HotSpotAdapter.hotSpotReleased

HotSpotAdapter.hotSpotReleased

Usage

public void hotSpotReleased(HotSpotEvent e)

Description

The system will call this method when the mouse is over a hot spot region and a mouse button is released.

The default implementation does nothing. Override to process this event.

Arguments

Argument | Default | Description
e | (Mandatory) | A HotSpotEvent object containing data of the hot spot event.

Return Value

None


HotSpotMotionListener

HotSpotMotionListener

HotSpotMotionListener is an interface for receiving hot spot mouse motion events (moves and drags). It is similar to java.awt.event.MouseMotionListener, except that it applies to mouse motion events that occur over hot spots.

(For other hot spot events, see HotSpotListener.)

To handle these events, either implement this interface, or extend the abstract class HotSpotMotionAdapter overriding only the methods of interest. ChartViewer.addHotSpotMotionListener can then be used to register the handler object to the ChartViewer.

Method | Inherited | Description
hotSpotMoved | (Self) | The system will call this method when the mouse moves over a hot spot.
hotSpotDragged | (Self) | The system will call this method when the mouse button is pressed and the mouse moves over a hot spot.


HotSpotMotionListener.hotSpotMoved

HotSpotMotionListener.hotSpotMoved

Usage

public void hotSpotMoved(HotSpotEvent e)

Description

The system will call this method when the mouse moves over a hot spot.

Arguments

Argument | Default | Description
e | (Mandatory) | A HotSpotEvent object containing data of the hot spot event.

Return Value

None


HotSpotMotionListener.hotSpotDragged

HotSpotMotionListener.hotSpotDragged

Usage

public void hotSpotDragged(HotSpotEvent e)

Description

The system will call this method when the mouse button is pressed and the mouse moves over a hot spot.

Arguments

Argument | Default | Description
e | (Mandatory) | A HotSpotEvent object containing data of the hot spot event.

Return Value

None


HotSpotMotionAdapter

HotSpotMotionAdapter

%class is an abstract class that provides a default implementation of the HotSpotMotionListener interface with empty methods. This class allows HotSpotMotionListener objects to be created conveniently, as only the methods for the events of interest need to be overridden.

Method | Inherited | Description
hotSpotMoved | (Self) | The system will call this method when the mouse moves over a hot spot.
hotSpotDragged | (Self) | The system will call this method when the mouse button is pressed and the mouse moves over a hot spot.


HotSpotMotionAdapter.hotSpotMoved

HotSpotMotionAdapter.hotSpotMoved

Usage

public void hotSpotMoved(HotSpotEvent e)

Description

The system will call this method when the mouse moves over a hot spot.

The default implementation does nothing. Override to process this event.

Arguments

Argument | Default | Description
e | (Mandatory) | A HotSpotEvent object containing data of the hot spot event.

Return Value

None


HotSpotMotionAdapter.hotSpotDragged

HotSpotMotionAdapter.hotSpotDragged

Usage

public void hotSpotDragged(HotSpotEvent e)

Description

The system will call this method when the mouse button is pressed and the mouse moves over a hot spot.

The default implementation does nothing. Override to process this event.

Arguments

Argument | Default | Description
e | (Mandatory) | A HotSpotEvent object containing data of the hot spot event.

Return Value

None


HotSpotEvent

HotSpotEvent

HotSpotEvent is a subclass of java.awt.event.MouseEvent. It provides information about hot spot events that occurred in a component. This includes both hot spot mouse events (click, enter, exit) and hot spot mouse motion events (moves and drags).

In addition to the information included in a MouseEvent, the HotSpotEvent includes attributes associated with the hot spot. These attributes come from query parameters in the image map that defines the hot spot.

For example, suppose the query parameters for the hot spot is:

x=0&xLabel=Mon&dataSet=0&dataSetName=Revenue&value=100

The HotSpotEvent object will contain the following attributes.

Attribute | Value
x | 0
xLabel | Mon
dataSet | 0
dataSetName | Revenue
value | 100

If there are two attributes with the same name in the query parameters, they will be merged into one attribute, with the values appended together, delimited using the ASCII unit separator character (ASCII code 31).

In addition to the attributes due to query parameters, the HotSpotEvent object contains three additional attributes as follows:

  • The path attribute reflecting the path portion of the URL in the <AREA> tag that defines the hot spot.

  • The coords attribute reflecting the coords attribute of the <AREA> tag that defines the hot spot.

  • The title attribute reflecting the title attribute of the <AREA> tag that defines the hot spot.

Method | Inherited | Description
get | (Self) | Gets a named attribute associated with the hot spot.
getAttrValues | (Self) | Gets a Hashtable containing the attributes associated with the hot spot.
Note: Methods inherited from MouseEvent are omitted.


HotSpotEvent.get

HotSpotEvent.get

Usage

public String get(String attr)

Description

Gets a named attribute associated with the hot spot.

Arguments

Argument | Default | Description
attr | (Mandatory) | The name of the attribute.

Return Value

The value of the attribute.


HotSpotEvent.getAttrValues

HotSpotEvent.getAttrValues

Usage

public Hashtable getAttrValues()

Description

Gets a Hashtable containing the attributes associated with the hot spot.

Arguments

None

Return Value

A Hashtable containing the attributes associcated with the hot spot.


ViewPortListener

ViewPortListener

ViewPortListener is an interface for receiving view port events, including selection changed event, and view port changed event.

To handle these events, either implement this interface, or extend the abstract class ViewPortAdapter overriding only the methods of interest. ChartViewer.addViewPortListener can then be used to register the handler object to the ChartViewer.

Method | Inherited | Description
viewPortChanged | (Self) | The system will call this method when the view port is changed through mouse actions, or when ChartViewer.updateViewPort is called.
selectionChanged | (Self) | The system will call this method when the user is selecting a region on the chart using "drag to select" mouse actions.


ViewPortListener.viewPortChanged

ViewPortListener.viewPortChanged

Usage

public void viewPortChanged(ViewPortChangedEvent e)

Description

The system will call this method when the view port is changed through mouse actions, or when ChartViewer.updateViewPort is called.

Arguments

Argument | Default | Description
e | (Mandatory) | A ViewPortChangedEvent object containing data of the selection changed event.

Return Value

None


ViewPortListener.selectionChanged

ViewPortListener.selectionChanged

Usage

public void selectionChanged(SelectionEvent e)

Description

The system will call this method when the user is selecting a region on the chart using "drag to select" mouse actions.

Arguments

Argument | Default | Description
e | (Mandatory) | A SelectionEvent object containing data of the selection changed event.

Return Value

None


ViewPortAdapter

ViewPortAdapter

%class is an abstract class that provides a default implementation of the ViewPortListener interface with empty methods. This class allows ViewPortListener objects to be created conveniently, as only the methods for the events of interest need to be overridden.

Method | Inherited | Description
viewPortChanged | (Self) | The system will call this method when the view port is changed through mouse actions, or when ChartViewer.updateViewPort is called.
selectionChanged | (Self) | The system will call this method when the user is selecting a region on the chart using "drag to select" mouse actions.


ViewPortAdapter.viewPortChanged

ViewPortAdapter.viewPortChanged

Usage

public void viewPortChanged(ViewPortChangedEvent e)

Description

The system will call this method when the view port is changed through mouse actions, or when ChartViewer.updateViewPort is called.

The default implementation does nothing. Override to process this event.

Arguments

Argument | Default | Description
e | (Mandatory) | A ViewPortChangedEvent object containing data of the selection changed event.

Return Value

None


ViewPortAdapter.selectionChanged

ViewPortAdapter.selectionChanged

Usage

public void selectionChanged(SelectionEvent e)

Description

The system will call this method when the user is selecting a region on the chart using "drag to select" mouse actions.

The default implementation does nothing. Override to process this event.

Arguments

Argument | Default | Description
e | (Mandatory) | A SelectionEvent object containing data of the selection changed event.

Return Value

None


ViewPortChangedEvent

ViewPortChangedEvent

ViewPortChangedEvent is a subclass of java.util.EventObject. It provides information about view port changed events.

Method | Inherited | Description
needUpdateChart | (Self) | Determines if the chart needs to be updated.
needUpdateImageMap | (Self) | Determines if the image map needs to be updated.
Note: Methods inherited from EventObject are omitted.


ViewPortChangedEvent.needUpdateChart

ViewPortChangedEvent.needUpdateChart

Usage

public bool needUpdateChart()

Description

Determines if the chart needs to be updated.

Arguments

None

Return Value

True if the chart needs to be updated, otherwise false.


ViewPortChangedEvent.needUpdateImageMap

ViewPortChangedEvent.needUpdateImageMap

Usage

public bool needUpdateImageMap()

Description

Determines if the image map needs to be updated.

Arguments

None

Return Value

True if the image map needs to be updated, otherwise false.


SelectionEvent

SelectionEvent

SelectionEvent is a subclass of java.awt.event.MouseEvent. It provides information about the current selection rectangle on the chart during a drag to select operation.

Method | Inherited | Description
isVisible | (Self) | Determines if the selection rectangle is visible.
getViewPortLeft | (Self) | Gets the position of the left edge of the selection rectangle in view port units.
getViewPortTop | (Self) | Gets the position of the top edge of the selection rectangle in view port units.
getViewPortWidth | (Self) | Gets the width of the selection rectangle in view port units.
getViewPortHeight | (Self) | Gets the height of the selection rectangle in view port units.
Note: Methods inherited from MouseEvent are omitted.


SelectionEvent.isVisible

SelectionEvent.isVisible

Usage

public bool isVisible()

Description

Determines if the selection rectangle is visible.

Arguments

None

Return Value

True if the selection rectangle is visible, otherwise false.


SelectionEvent.getViewPortLeft

SelectionEvent.getViewPortLeft

Usage

public double getViewPortLeft()

Description

Gets the position of the left edge of the selection rectangle in view port units.

Arguments

None

Return Value

The position of the left edge of the selection rectangle in view port units.


SelectionEvent.getViewPortTop

SelectionEvent.getViewPortTop

Usage

public double getViewPortTop()

Description

Gets the position of the top edge of the selection rectangle in view port units.

Arguments

None

Return Value

The position of the top edge of the selection rectangle in view port units.


SelectionEvent.getViewPortWidth

SelectionEvent.getViewPortWidth

Usage

public double getViewPortWidth()

Description

Gets the width of the selection rectangle in view port units.

Arguments

None

Return Value

The width of the selection rectangle in view port units.


SelectionEvent.getViewPortHeight

SelectionEvent.getViewPortHeight

Usage

public double getViewPortHeight()

Description

Gets the height of the selection rectangle in view port units.

Arguments

None

Return Value

The height of the selection rectangle in view port units.


WebChartViewer

WebChartViewer

WebChartViewer is the server side counterpart to the browser side Javascript JsChartViewer. It generates the necessary HTML tags to allow the JsChartViewer to support programming track cursors and using mouse clicks and drags to control zooming and scrolling. Its accepts AJAX chart update requests from JsChartViewer and responses to it. Many of the JsChartViewer attributes can be set or get on the server side through WebChartViewer.

Method | Inherited | Description
WebChartViewer | (Self) | Creates a new WebChartViewer object.
getRequest | (Self) | Gets the HttpServletRequest object used to create the WebChartViewer.
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.
setChartModel | (Self) | Sets the Javascript Chart Model of the chart for the purpose of support track cursors.
getChartModel | (Self) | Gets the Javascript Chart Model of 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.
streamChart | (Self) | Sends the image out as a MIME stream of image type.
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.
getMouseUsage | (Self) | Gets the mouse usage mode.
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.
setFullRange | (Self) | Defines the full range of a view port data scale.
getValueAtViewPort | (Self) | Converts a view port coordinate to a value of the specified data scale.
getViewPortAtValue | (Self) | Converts a value of the specified data scale to a view port coordinate.
syncLinearAxisWithViewPort | (Self) | Synchronizes a linear Axis with the part of the data scale in view port.
syncLogAxisWithViewPort | (Self) | Synchronizes a logarithmic Axis with the part of the data scale in view port.
syncDateAxisWithViewPort | (Self) | Synchronizes a date/time Axis with the part of the data scale in view port.


WebChartViewer.WebChartViewer

WebChartViewer.WebChartViewer

Usage

public WebChartViewer(HttpServletRequest request, String id)

Description

Creates a new WebChartViewer object.

Arguments

Argument | Default | Description
request | (Mandatory) | The HttpServletRequest object representing the current request. This object is used to analyze the HTTP request to see if it is a partial update request and initialize the properties of the WebChartViewer properly.
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.getRequest

WebChartViewer.getRequest

Usage

public HttpServletRequest getRequest()

Description

Gets the HttpServletRequest object used to create the WebChartViewer.

Arguments

None

Return Value

None


WebChartViewer.getId

WebChartViewer.getId

Usage

public String getId()

Description

Gets the id of the WebChartViewer object.

Arguments

None

Return Value

The id of the WebChartViewer object.


WebChartViewer.setImageUrl

WebChartViewer.setImageUrl

Usage

public void setImageUrl(String 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

public String 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

public void setImageMap(String 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

public String 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.setChartModel

WebChartViewer.setChartModel

Usage

public void setChartModel(String jsChartModel)

Description

Sets the Javascript Chart Model of the chart for the purpose of support track cursors.

To support track cursors in a web application, the browser would need know certain details of the chart, its data, chart type and axis configuration. The Javascript Chart Model is a textual representation of those information. The WebChartViewer will send it to the browser to be used by the browser side Javascript ChartViewer (JsChartViewer).

The format of the Javascript Chart Model is not published.

Arguments

Argument | Default | Description
jsChartModel | (Mandatory) | A text string obtained from BaseChart.getJsChartModel that represents the Javascript Chart Model of the chart.

Return Value

None


WebChartViewer.getChartModel

WebChartViewer.getChartModel

Usage

public String getChartModel()

Description

Gets the Javascript Chart Model of the chart.

The method returns the same value set by a previous call to WebChartViewer.setChartModel.

Arguments

None

Return Value

A text string representing the Javascript Chart Model of the chart for the purpose of support track cursors.


WebChartViewer.setChartMetrics

WebChartViewer.setChartMetrics

Usage

public void setChartMetrics(String 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

public String 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

public String makeDelayedMap(String imageMap [, boolean 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.jsp". The URL for retrieving the delayed image map should be passed to WebChartViewer.setImageMap for transferring to the browser. For example:

viewer.setImageMap("getchart.jsp?" + viewer.makeDelayedMap(imageMap));

Note that the above assumes the "getchart.jsp" 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.jsp".

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.jsp" utility.


WebChartViewer.renderHTML

WebChartViewer.renderHTML

Usage

public String renderHTML(HttpServletResponse response [, String 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
response | (Mandatory) | An HttpServletResponse object used to encode the output.
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

public void partialUpdateChart(HttpServletResponse response [, String msg [, int 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
response | (Mandatory) | An HttpServletResponse object used to send out the response.
msg | "" | A pop up message to be displayed on the chart. "" 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. 0 means the pop up message will stay until the chart refreshes.

Return Value

None


WebChartViewer.streamChart

WebChartViewer.streamChart

Usage

public static boolean streamChart(HttpServletResponse response, byte[] image)

Description

Sends the image out as a MIME stream of image type.

Arguments

Argument | Default | Description
response | (Mandatory) | An HttpServletResponse object used to encode the output.
image | (Mandatory) | The in-memory image.

Return Value

This method always return true.


WebChartViewer.isPartialUpdateRequest

WebChartViewer.isPartialUpdateRequest

Usage

public boolean 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.

This method is also available as a static method of WebChartViewer. The static method requires one argument, which can be either the current ServletRequest or PageContext.

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

public boolean 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.

This method is also available as a static method of WebChartViewer. The static method requires one argument, which can be either the current ServletRequest or PageContext.

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

public boolean 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.

This method is also available as a static method of WebChartViewer. The static method requires one argument, which can be either the current ServletRequest or PageContext.

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

public boolean 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.

This method is also available as a static method of WebChartViewer. The static method requires one argument, which can be either the current ServletRequest or PageContext.

Arguments

None

Return Value

True if the JsChartViewer.ViewPortChanged event has occurred, otherwise false.


WebChartViewer.getSenderClientId

WebChartViewer.getSenderClientId

Usage

public String 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

public void setViewPortLeft(double 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

public double 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

public void setViewPortTop(double 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

public double 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

public void setViewPortWidth(double 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

public double 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

public void setViewPortHeight(double 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

public double 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

public void setMouseUsage(int mouseUsage)

Description

Sets the mouse usage mode.

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

public int getMouseUsage()

Description

Gets the mouse usage mode.

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

public void setZoomDirection(int 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

public int 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

public void setScrollDirection(int 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

public int 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

public void setZoomInRatio(double 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

public double 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

public void setZoomOutRatio(double 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

public double 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

public void setZoomInWidthLimit(double 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

public double 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

public void setZoomOutWidthLimit(double 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

public double 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

public void setZoomInHeightLimit(double 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

public double 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

public void setZoomOutHeightLimit(double 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

public double 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

public void setMinimumDrag(int 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

public int 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

public void setSelectionBorderWidth(int 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

public int 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

public void setSelectionBorderColor(String 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

public String 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

public void setZoomInCursor(String 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

public String 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

public void setZoomOutCursor(String 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

public String 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

public void setNoZoomCursor(String 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

public String 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

public void setScrollCursor(String 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

public String 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

public void setCustomAttr(String key, String 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

public String getCustomAttr(String 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.


WebChartViewer.setFullRange

WebChartViewer.setFullRange

Usage

public void setFullRange(String id, {double | java.util.Date} minValue, {double | java.util.Date} maxValue)

Description

Defines the full range of a view port data scale.

In the ChartDirector zooming and scrolling framework, the view port coordinates are expressed as the visible fractions of the "full data scale". For example, if the "full data scale" is 10 years horizontally, a view port width of 0.1 means that 1 year of data are visible.

The setFullRange method defines the full range of a data scale and gives it a name. As ChartDirector supports multiple x-axes and y-axes, so there can be multiple data scales with different names. The name can be used in other ChartDirector APIs to convert between the view port coordinates and data scale (see WebChartViewer.getValueAtViewPort, WebChartViewer.getViewPortAtValue), and to configure an Axis to reflect the visible data scale (see WebChartViewer.syncLinearAxisWithViewPort, WebChartViewer.syncLogAxisWithViewPort and WebChartViewer.syncDateAxisWithViewPort).

Arguments

Argument | Default | Description
id | (Mandatory) | The name of the data scale.
minValue | (Mandatory) | The minimum value of the data scale.
maxValue | (Mandatory) | The maximum value of the data scale.

Return Value

None


WebChartViewer.getValueAtViewPort

WebChartViewer.getValueAtViewPort

Usage

public double getValueAtViewPort(String id, double vpCoor [, boolean isLogScale ])

Description

Converts a view port coordinate to a value of the specified data scale.

Please refer to WebChartViewer.setFullRange on how to define a data scale.

This method always returns a numeric value. If the axis scale is a date/time scale, and you are expecting a java.util.Date data type, please use Chart.NTime to convert the number to the java.util.Date data type.

Arguments

Argument | Default | Description
id | (Mandatory) | The name of the data scale.
vpCoor | (Mandatory) | The view port coordinate.
isLogScale | false | true if the conversion is based on a logarithmic scale. false if the conversion is based on a non-logarithmic scale.

Return Value

The value of the specified data scale at the view port coordinate.


WebChartViewer.getViewPortAtValue

WebChartViewer.getViewPortAtValue

Usage

public double getViewPortAtValue(String id, double value [, boolean isLogScale ])

Description

Converts a value of the specified data scale to a view port coordinate.

Please refer to WebChartViewer.setFullRange on how to define a data scale.

This method only accepts numeric values as input. If the axis scale is a date/time scale, and you are using a java.util.Date value, please use Chart.CTime to convert it to a number.

Arguments

Argument | Default | Description
id | (Mandatory) | The name of the data scale.
value | (Mandatory) | The value to be converted.
isLogScale | false | true if the conversion is based on a logarithmic scale. false if the conversion is based on a non-logarithmic scale.

Return Value

The view port coordinate at the value of the specified data scale.


WebChartViewer.syncLinearAxisWithViewPort

WebChartViewer.syncLinearAxisWithViewPort

Usage

public void syncLinearAxisWithViewPort(String id, Axis axis)

Description

Synchronizes a linear Axis with the part of the data scale in view port.

If the data scale has already been defined (see WebChartViewer.setFullRange on how to define a data scale), this method will compute the visible data scale based on the view port coordinates using linear interpolation, and then sets the axis to that linear scale.

If the data scale has not been defined, this method will define the data scale based on the axis scale and the the view port coordinates using linear extrapolation. Because the axis scale may not be known at the time of calling this method (the axis could be auto-scaled by ChartDirector, which may not occur until the chart is rendered), the definition of the data scale will not occur immediately, but will be pending until the chart is to be displayed.

If your charting code calls this method but never defines the full data scale or the view port coordinates (in which case the view port defaults to showing the complete data scale), then the first time the code is executed, the data scale will be defined to be equal to the axis scale. Subsequently, when the user zooms into the chart (which means the view port coordinates are changed), the same charting code will set up the axis scale to the range that the user has zoomed to.

Arguments

Argument | Default | Description
id | (Mandatory) | The name of the data scale.
axis | (Mandatory) | The Axis object to synchronize with.

Return Value

None


WebChartViewer.syncLogAxisWithViewPort

WebChartViewer.syncLogAxisWithViewPort

Usage

public void syncLogAxisWithViewPort(String id, Axis axis)

Description

Synchronizes a logarithmic Axis with the part of the data scale in view port.

If the data scale has already been defined (see WebChartViewer.setFullRange on how to define a data scale), this method will compute the visible data scale based on the view port coordinates using logarithmic interpolation, and then sets the axis to that logarithmic scale.

If the data scale has not been defined, this method will define the data scale based on the axis scale and the the view port coordinates using logarithmic extrapolation. Because the axis scale may not be known at the time of calling this method (the axis could be auto-scaled by ChartDirector, which may not occur until the chart is rendered), the definition of the data scale will not occur immediately, but will be pending until the chart is to be displayed.

If your charting code calls this method but never defines the full data scale or the view port coordinates (in which case the view port defaults to showing the complete data scale), then the first time the code is executed, the data scale will be defined to be equal to the axis scale. Subsequently, when the user zooms into the chart (which means the view port coordinates are changed), the same charting code will set up the axis scale to the range that the user has zoomed to.

Arguments

Argument | Default | Description
id | (Mandatory) | The name of the data scale.
axis | (Mandatory) | The Axis object to synchronize with.

Return Value

None


WebChartViewer.syncDateAxisWithViewPort

WebChartViewer.syncDateAxisWithViewPort

Usage

public void syncDateAxisWithViewPort(String id, Axis axis)

Description

Synchronizes a date/time Axis with the part of the data scale in view port.

If the data scale has already been defined (see WebChartViewer.setFullRange on how to define a data scale), this method will compute the visible data scale based on the view port coordinates using date/time interpolation, and then sets the axis to that date/time scale.

If the data scale has not been defined, this method will define the data scale based on the axis scale and the the view port coordinates using date/time extrapolation. Because the axis scale may not be known at the time of calling this method (the axis could be auto-scaled by ChartDirector, which may not occur until the chart is rendered), the definition of the data scale will not occur immediately, but will be pending until the chart is to be displayed.

If your charting code calls this method but never defines the full data scale or the view port coordinates (in which case the view port defaults to showing the complete data scale), then the first time the code is executed, the data scale will be defined to be equal to the axis scale. Subsequently, when the user zooms into the chart (which means the view port coordinates are changed), the same charting code will set up the axis scale to the range that the user has zoomed to.

Arguments

Argument | Default | Description
id | (Mandatory) | The name of the data scale.
axis | (Mandatory) | The Axis object to synchronize with.

Return Value

None


JSP and Servlets

JSP and Servlets

This section describes JSP and Servlet utilities that come with ChartDirector.

In this section

getchart.jsp
A JSP utility for retrieving a chart image from a session variable and delivering it to the browser. The chart image is usually created using BaseChart.makeSession.

GetSessionImage
Performs the same function as getchart.jsp, but is implemented as a servlet. It is useful for servlet applications that do not use JSP.


getchart.jsp

getchart.jsp

"getchart.jsp" is a utility JSP that comes with ChartDirector. Its retrieves an image from a session variable, and returns the image to the browser.

"getchart.jsp" is typically used in the URL of an <IMG> tag, so that the <IMG> tag can reference an image in a session variable.

The name of the session variable is specify as a URL query parameter "img". For example, "getchart.jsp?img=chart1" will retrieve an image from the session variable "chart1".

"getchart.jsp" is usually used together with BaseChart.makeSession. The latter creates a chart image in a session variable, and returns an URL query string that can be used directly by "getchart.jsp".


GetSessionImage

GetSessionImage

ChartDirector.GetSessionImage is a utility servlet that retrieves an image from a session variable, and returns the image to the browser.

GetSessionImage is typically used in the URL of an <IMG> tag, so that the <IMG> tag can reference an image in a session variable.

The name of the session variable is specify as a URL query parameter "img". For example, "getchart.chart?img=chart1" will retrieve an image from the session variable "chart1", assuming URL "*.chart" maps to the GetSessionImage servlet.

For compatibility with previous versions of ChartDirector, GetSessionImage also supports specifying the session variable name as the name of the servlet. For example, "xyz.chart" will retrieve the image from the session variable "xyz". This syntax is now deprecated.

To use GetSessionImage, you need to set up the necessary URL to servlet mappings. Please refer to the Installation section for details.

GetSessionImage is usually used together with BaseChart.makeSession. The latter creates a chart image in a session variable, and returns an URL query string that can be used directly by GetSessionImage.

The GetSessionImage performs the same function as getchart.jsp. It is an alternative to getchart.jsp for servlet applications that do not use JSP.


Javascript Library

Javascript Library

This section describes the ChartDirector Javascript Library, which is used to support browser side user interactions with charts.

The ChartDirector Javascript Library includes two main parts:

  • Javascript Chart Viewer: A browser side Javascript control for supporting advanced chart user interactions, such as programmable track cursors, zooming and scrolling and AJAX chart updates.

  • Javascript Chart Model: An object model of ChartDirector charts, making chart data and configuration accessible on the browser side. This facilitates implementation of programmable track cursors and other advanced user interface features.

Files Required

The ChartDirector Javascript Library is implemented in the file "cdjcv.js". To use the ChartDirector Javascript Library, please include the following line 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" in turn may load the following files, which should be located in the same directory as "cdjcv.js".

Filename | Description
wait.gif | Rotating clock wait symbol.
spacer.gif | A 1-pixel transparent image.
zoomin.cur | Zoom in cursor.
zoomin.cur | Zoom out cursor.
nozoom.cur | No zoom cursor.

At runtime, "cdjcv.js" will detect the absolute URL of itself, and use it to load the above files. (It does use relative URL, because the browser will interpret it to be relative to the URL of the containing HTML web page, not the URL of the "cdjcv.js".) If you would like "cdjcv.js" to load the above files from an alternative directory, you may put the URL of the directory in a global Javascript variable "cdjcv_path". "cdjcv.js" will look for this variable first before deriving the path from its own URL.


JsChartViewer

JsChartViewer

As ChartDirector charts are in standard image formats, and the hot spots are in standard HTML formats, the browser by itself can display the charts and support the hot spot tooltips and events.

The JsChartViewer control is a browser side Javascript control to support other advanced chart user interactions, including:

  • Programmable Track Cursor Support

    The JsChartViewer control includes special methods and events for supporting programmable track cursors. It includes methods for drawing track cursors and other dynamic contents on the browser side.

  • Zoom and Scroll Support

    The JsChartViewer control includes special methods and events for supporting using mouse clicks and drags to control the "view port". There are also methods to facilitate using custom user interface to control the view port.

  • AJAX chart update

    The JsChartViewer allows the chart, including the associated image map and data for programmable track cursor, to be updated without refreshing the web page. Custom parameters can also be passed during the AJAX chart update between the browser and the server.

    In many applications, JsChartViewer needs to be used with WebChartViewer on the server side. For example, when JsChartViewer sends an AJAX chart update requests to the server, the server needs to use WebChartViewer to interpret the request and to send back the result.

    To use JsChartViewer in a web page, it is necessary to include the ChartDirector Javascript Library "cdjcv.js" and other supporting files in the web page. Please refer to ChartDirector Javascript Library for details.

    JsChartViewer is designed to work with IE 6.0 or above, FireFox 3.0 or above, Chrome 4.0 or above, and Safari 4.0 or above.

    Properties
    Name | Description
    Default | A constant equals to 0 to represent using the default mouse behaviour.
    Scroll | A constant equals to 2 to represent using the mouse for drag scrolling.
    ZoomIn | A constant equals to 3 to represent using the mouse for zoom in actions.
    ZoomOut | A constant equals to 4 to represent using the mouse for zoom out actions.
    Horizontal | A constant equals to 0 to represent that the zoom and/or scroll orientation is horizontal.
    Vertical | A constant equals to 1 to represent that the zoom and/or scroll orientation is vertical.
    HorizontalVertical | A constant equals to 2 to represent that the zoom and/or scroll orientation can be both horizontal and vertical.
    BottomLeft | A constant equals to 1 to represent the 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.
    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.
    TopCenter | A constant equals to 8 to represent the top center position.
    TopRight | A constant equals to 9 to represent the 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.
    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.
    getValueAtViewPort | Converts a view port coordinate to a value of the specified data scale.
    getViewPortAtValue | Converts a value of the specified data scale to a view port coordinate.
    setPlotAreaMouseMargin | Sets all margins (left, right, top, and bottom) of the plot area mouse event region to the same value.
    setPlotAreaMouseMargin2 | Sets the margins of the plot area mouse event region.
    isMouseOnPlotArea | Checks if the mouse cursor is on the extended plot area.
    getChartMouseX | Gets the mouse cursor x-coordinate in the chart pixel coordinate system.
    getChartMouseY | Gets the mouse cursor y-coordinate in the chart pixel coordinate system.
    getPlotAreaMouseX | Gets the mouse cursor x-coordinate on the plot area in the chart pixel coordinate system.
    getPlotAreaMouseY | Gets the mouse cursor y-coordinate on the plot area in the chart pixel coordinate system.
    setMouseUsage | Sets the mouse usage mode.
    getMouseUsage | Gets the mouse usage mode.
    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.
    raiseViewPortChangedEvent | Raises a JsChartViewer.ViewPortChanged event.
    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.
    getChart | Gets the specified chart in the Javascript Chart Model.
    getChartCount | Gets the number of charts in the Javascript Chart Model.
    drawHLine | Draws a horizontal line on the chart.
    drawVLine | Draws a vertical line on the chart.
    showCrossHair | Displays the crosshair cursor.
    showTextBox | Draws a textbox on the chart.
    hideObj | Hides one or more objects drawn by JsChartViewer.
    setAutoHide | Hides one or more objects drawn by JsChartViewer when a certain event occurs.
    removeAutoHide | Cancels the automatic action sets up by JsChartViewer.setAutoHide.
    htmlRect | Generates HTML code that represents an inline color box.
    addEventListener | A utility to attach an event handler to a Javascript event.
    removeEventListener | Removes an event handler attached via a previous call to JsChartViewer.addEventListener.
    NTime | Converts a date/time in ChartDirector's date/time format to a Javascript Date object.
    CTime | Converts a Javascript Date object to ChartDirector's date/time format.

    Events
    Name | Description
    MouseMoveChart | This event occurs when the mouse cursor moves on the chart.
    MouseOutChart | This event occurs when the mouse cursor leaves the chart.
    MouseMovePlotArea | This event occurs when the mouse cursor moves on the extended plot area.
    MouseOutPlotArea | This event occurs when the mouse cursor leaves the extended plot area.
    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.
    • © 2012 Advanced Software Engineering Limited. All rights reserved.


JsChartViewer.Default

JsChartViewer.Default

Description

A constant equals to 0 to represent using the default mouse behaviour.

This constant is used in JsChartViewer.setMouseUsage.

Note: This is a static property (class property). It should be accessed as JsChartViewer.Default, not objName.Default.


JsChartViewer.Scroll

JsChartViewer.Scroll

Description

A constant equals to 2 to represent using the mouse for drag scrolling.

This constant is used in JsChartViewer.setMouseUsage.

Note: This is a static property (class property). It should be accessed as JsChartViewer.Scroll, not objName.Scroll.


JsChartViewer.ZoomIn

JsChartViewer.ZoomIn

Description

A constant equals to 3 to represent using the mouse for zoom in actions.

This constant is used in JsChartViewer.setMouseUsage.

Note: This is a static property (class property). It should be accessed as JsChartViewer.ZoomIn, not objName.ZoomIn.


JsChartViewer.ZoomOut

JsChartViewer.ZoomOut

Description

A constant equals to 4 to represent using the mouse for zoom out actions.

This constant is used in JsChartViewer.setMouseUsage.

Note: This is a static property (class property). It should be accessed as JsChartViewer.ZoomOut, not objName.ZoomOut.


JsChartViewer.Horizontal

JsChartViewer.Horizontal

Description

A constant equals to 0 to represent that the zoom and/or scroll orientation is horizontal.

This constant is used in JsChartViewer.setZoomDirection and JsChartViewer.setScrollDirection.

Note: This is a static property (class property). It should be accessed as JsChartViewer.Horizontal, not objName.Horizontal.


JsChartViewer.Vertical

JsChartViewer.Vertical

Description

A constant equals to 1 to represent that the zoom and/or scroll orientation is vertical.

This constant is used in JsChartViewer.setZoomDirection and JsChartViewer.setScrollDirection.

Note: This is a static property (class property). It should be accessed as JsChartViewer.Vertical, not objName.Vertical.


JsChartViewer.HorizontalVertical

JsChartViewer.HorizontalVertical

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 JsChartViewer.setZoomDirection and JsChartViewer.setScrollDirection.

Note: This is a static property (class property). It should be accessed as JsChartViewer.HorizontalVertical, not objName.HorizontalVertical.


JsChartViewer.BottomLeft

JsChartViewer.BottomLeft

Description

A constant equals to 1 to represent the bottom left position.

See Alignment Specification for supported alignment types.

Note: This is a static property (class property). It should be accessed as JsChartViewer.BottomLeft, not objName.BottomLeft.


JsChartViewer.BottomCenter

JsChartViewer.BottomCenter

Description

A constant equals to 2 to represent the bottom center position.

See Alignment Specification for supported alignment types.

Note: This is a static property (class property). It should be accessed as JsChartViewer.BottomCenter, not objName.BottomCenter.


JsChartViewer.BottomRight

JsChartViewer.BottomRight

Description

A constant equals to 3 to represent the bottom right position.

See Alignment Specification for supported alignment types.

Note: This is a static property (class property). It should be accessed as JsChartViewer.BottomRight, not objName.BottomRight.


JsChartViewer.Left

JsChartViewer.Left

Description

A constant equals to 4 to represent the left position.

See Alignment Specification for supported alignment types.

Note: This is a static property (class property). It should be accessed as JsChartViewer.Left, not objName.Left.


JsChartViewer.Center

JsChartViewer.Center

Description

A constant equals to 5 to represent the center position.

See Alignment Specification for supported alignment types.

Note: This is a static property (class property). It should be accessed as JsChartViewer.Center, not objName.Center.


JsChartViewer.Right

JsChartViewer.Right

Description

A constant equals to 6 to represent the right position.

See Alignment Specification for supported alignment types.

Note: This is a static property (class property). It should be accessed as JsChartViewer.Right, not objName.Right.


JsChartViewer.TopLeft

JsChartViewer.TopLeft

Description

A constant equals to 7 to represent the top left position.

See Alignment Specification for supported alignment types.

Note: This is a static property (class property). It should be accessed as JsChartViewer.TopLeft, not objName.TopLeft.


JsChartViewer.TopCenter

JsChartViewer.TopCenter

Description

A constant equals to 8 to represent the top center position.

See Alignment Specification for supported alignment types.

Note: This is a static property (class property). It should be accessed as JsChartViewer.TopCenter, not objName.TopCenter.


JsChartViewer.TopRight

JsChartViewer.TopRight

Description

A constant equals to 9 to represent the top right position.

See Alignment Specification for supported alignment types.

Note: This is a static property (class property). It should be accessed as JsChartViewer.TopRight, not objName.TopRight.


JsChartViewer.Bottom

JsChartViewer.Bottom

Description

A constant equals to 2 to represent the bottom position.

See Alignment Specification for supported alignment types.

Note: This is a static property (class property). It should be accessed as JsChartViewer.Bottom, not objName.Bottom.


JsChartViewer.Top

JsChartViewer.Top

Description

A constant equals to 8 to represent the top position.

See Alignment Specification for supported alignment types.

Note: This is a static property (class property). It should be accessed as JsChartViewer.Top, not objName.Top.


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.


JsChartViewer.get

JsChartViewer.get

Usage

get(id)

Description

Gets a JsChartViewer object that binds to the given <IMG> tag for chart display.

Note: This is a static method (class method). It should be accessed as JsChartViewer.get, not objName.get.

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.getChartMouseX

JsChartViewer.getChartMouseX

Usage

getChartMouseX()

Description

Gets the mouse cursor x-coordinate in the chart pixel coordinate system.

This method is only valid when called inside the TrackCursorListener events. events.

Arguments

None

Return Value

The mouse cursor x-coordinate in the chart pixel coordinate system.


JsChartViewer.getChartMouseY

JsChartViewer.getChartMouseY

Usage

getChartMouseY()

Description

Gets the mouse cursor y-coordinate in the chart pixel coordinate system.

This method is only valid when called inside the TrackCursorListener events. events.

Arguments

None

Return Value

The mouse cursor y-coordinate in the chart pixel coordinate system.


JsChartViewer.getPlotAreaMouseX

JsChartViewer.getPlotAreaMouseX

Usage

getPlotAreaMouseX()

Description

Gets the mouse cursor x-coordinate on the plot area in the chart pixel coordinate system.

If the mouse cursor is not on the plot area, but is on the extended plot area (see JsChartViewer.setPlotAreaMouseMargin), this method will behave as if the mouse cursor is on the nearest plot area edge.

If the mouse cursor is not even on the extended plot area mouse region, this method will return the last coordinate when the mouse was still on the extended plot area.

This method is only valid when called inside the TrackCursorListener events. events.

Arguments

None

Return Value

The mouse cursor x-coordinate in the chart pixel coordinate system.


JsChartViewer.getPlotAreaMouseY

JsChartViewer.getPlotAreaMouseY

Usage

getPlotAreaMouseY()

Description

Gets the mouse cursor y-coordinate on the plot area in the chart pixel coordinate system.

If the mouse cursor is not on the plot area, but is on the extended plot area (see JsChartViewer.setPlotAreaMouseMargin), this method will behave as if the mouse cursor is on the nearest plot area edge.

If the mouse cursor is not even on the extended plot area mouse region, this method will return the last coordinate when the mouse was still on the extended plot area.

This method is only valid when called inside the TrackCursorListener events. events.

Arguments

None

Return Value

The mouse cursor y-coordinate in the chart pixel coordinate system.


JsChartViewer.setPlotAreaMouseMargin

JsChartViewer.setPlotAreaMouseMargin

Usage

setPlotAreaMouseMargin(m)

Description

Sets all margins (left, right, top, and bottom) of the plot area mouse event region to the same value.

Plot area mouse events are often used for implementing track cursors. For example, a track line can be drawn that follows the mouse cursor when the mouse cursor is moving on the plot area. For these usages, it is important to be able to put the mouse cursor at the edge of the plot area, because the latest data points are usually plotted at the edge.

In practice, it is difficult to put the mouse cursor exactly on the edge, as it is hard to move the mouse cursor precisely. To address this issue, ChartDirector supports extending the plot area mouse event region by a configuration margin. A mouse cursor on that extended region will be treated as if it is on the nearest edge of the plot area for the purpose of trigger plot area mouse events.

By default, the left, right, top and bottom margins of the plot area mouse event region are 5 pixels.

Arguments

Argument | Default | Description
m | (Mandatory) | The left, right, top and bottom margins in pixels.

Return Value

None


JsChartViewer.setPlotAreaMouseMargin2

JsChartViewer.setPlotAreaMouseMargin2

Usage

setPlotAreaMouseMargin2(leftMargin, rightMargin, topMargin, bottomMargin)

Description

Sets the margins of the plot area mouse event region.

Plot area mouse events are often used for implementing track cursors. For example, a track line can be drawn that follows the mouse cursor when the mouse cursor is moving on the plot area. For these usages, it is important to be able to put the mouse cursor at the edge of the plot area, because the latest data points are usually plotted at the edge.

In practice, it is difficult to put the mouse cursor exactly on the edge, as it is hard to move the mouse cursor precisely. To address this issue, ChartDirector supports extending the plot area mouse event region by a configuration margin. A mouse cursor on that extended region will be treated as if it is on the nearest edge of the plot area for the purpose of trigger plot area mouse events.

By default, the left, right, top and bottom margins of the plot area mouse event region are 5 pixels.

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


JsChartViewer.isMouseOnPlotArea

JsChartViewer.isMouseOnPlotArea

Usage

isMouseOnPlotArea()

Description

Checks if the mouse cursor is on the extended plot area.

See JsChartViewer.setPlotAreaMouseMargin on what is the extended plot area.

Arguments

None

Return Value

True if the mouse is on the extended plot area, otherwise false.


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.getValueAtViewPort

JsChartViewer.getValueAtViewPort

Usage

getValueAtViewPort(id, vpCoor [, isLogScale ])

Description

Converts a view port coordinate to a value of the specified data scale.

Please refer to WebChartViewer.setFullRange on how to define a data scale.

This method always returns a numeric value. If the axis scale is a date/time scale, and you are expecting a java.util.Date data type, please use Chart.NTime to convert the number to the java.util.Date data type.

Arguments

Argument | Default | Description
id | (Mandatory) | The name of the data scale.
vpCoor | (Mandatory) | The view port coordinate.
isLogScale | false | true if the conversion is based on a logarithmic scale. false if the conversion is based on a non-logarithmic scale.

Return Value

The value of the specified data scale at the view port coordinate.


JsChartViewer.getViewPortAtValue

JsChartViewer.getViewPortAtValue

Usage

getViewPortAtValue(id, value [, isLogScale ])

Description

Converts a value of the specified data scale to a view port coordinate.

Please refer to WebChartViewer.setFullRange on how to define a data scale.

This method only accepts numeric values as input. If the axis scale is a date/time scale, and you are using a java.util.Date value, please use Chart.CTime to convert it to a number.

Arguments

Argument | Default | Description
id | (Mandatory) | The name of the data scale.
value | (Mandatory) | The value to be converted.
isLogScale | false | true if the conversion is based on a logarithmic scale. false if the conversion is based on a non-logarithmic scale.

Return Value

The view port coordinate at the value of the specified data scale.


JsChartViewer.setMouseUsage

JsChartViewer.setMouseUsage

Usage

setMouseUsage(mouseUsage)

Description

Sets the mouse usage mode.

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.

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 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

  • Msxml2.XMLHTTP or Microsoft.XMLHTTP

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 already an existing update request in progress, the timeout value determines whether to abort the existing request and continue with the new request, or vice versa. If the existing request has been in progress for longer than the timeout value in seconds, it will be aborted, otherwise the new request will be aborted.

Return Value

True if a new streamUpdate request is sent out. False if the new streamUpdate request is aborted (due to an outstanding request).


JsChartViewer.raiseViewPortChangedEvent

JsChartViewer.raiseViewPortChangedEvent

Usage

void raiseViewPortChangedEvent()

Description

Raises a JsChartViewer.ViewPortChanged event.

A ViewPortChanged event is automatically raised if the view port is changed by mouse actions (see JsChartViewer.setMouseUsage). This method allows the event to be raised for other reasons.

For example, when a HTML button is pressed, the onclick handler can reset the view port to some default value, and then use this method to raise the ViewPortChanged event. This allows the button to manipulate the view port and update the chart.

Arguments

None

Return Value

None


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. An example is "ViewPortChanged" (for the JsChartViewer.ViewPortChanged event).

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.getChart

JsChartViewer.getChart

Usage

getChart([ index ])

Description

Gets the specified chart in the Javascript Chart Model.

If the underlying chart is a MultiChart (including a FinanceChart), this method returns a chart contained within the MultiChart. The index argument can be used to select which chart to return. If the underlying chart is not a MultiChart, this method returns the chart itself, and the index argument must be 0.

Arguments

Argument | Default | Description
index | 0 | The index of the chart. The index of the first chart set added to the MultiChart is 0. The index of the Nth data set added to the MultiChart is N - 1.

Return Value

The specified JsXYChart object.


JsChartViewer.getChartCount

JsChartViewer.getChartCount

Usage

getChartCount()

Description

Gets the number of charts in the Javascript Chart Model.

Arguments

None

Return Value

The number of charts in the Javascript Chart Model.


JsChartViewer.drawHLine

JsChartViewer.drawHLine

Usage

drawHLine(id, y, x1, x2, lineStyle)

Description

Draws a horizontal line on the chart.

The line will be drawn as an HTML element overlaid on top of the chart, with the specified HTML id attribute. The id argument should therefore comply to the HTML standard (eg. begin with A-Z or a-z, followed by letters from A-Z, a-z, 0-9, '-' and '_').

If the id is already used by an existing HTML element, JsChartViewer will assume the element is created earlier by drawHLine. In this case, instead of creating a new HTML element, it will move the existing element to the required position and sets its line style to lineStyle. Recalling this method with different coordinates will have the effect of moving the line around.

The line can be hidden using JsChartViewer.hideObj.

Arguments

Argument | Default | Description
id | (Mandatory) | The id of the HTML element representing the line.
y | (Mandatory) | The y pixel coordinate of the line, relative to the chart.
x1 | (Mandatory) | The x pixel coordinate of the first end point of the line, relative to the chart.
x2 | (Mandatory) | The x pixel coordinate of the second end point of the line, relative to the chart.
lineStyle | (Mandatory) | The line style in CSS border property format (eg. "1px solid black").

Return Value

A DOM element representing the line.


JsChartViewer.drawVLine

JsChartViewer.drawVLine

Usage

drawVLine(id, x, y1, y2, lineStyle)

Description

Draws a vertical line on the chart.

The line will be drawn as an HTML element overlaid on top of the chart, with the specified HTML id attribute. The id argument should therefore comply to the HTML standard (eg. begin with A-Z or a-z, followed by letters from A-Z, a-z, 0-9, '-' and '_').

If the id is already used by an existing HTML element, JsChartViewer will assume the element is created earlier by drawVLine. In this case, instead of creating a new HTML element, it will move the existing element to the required position and sets its line style to lineStyle. Recalling this method with different coordinates will have the effect of moving the line around.

The line can be hidden using JsChartViewer.hideObj.

Arguments

Argument | Default | Description
id | (Mandatory) | The id of the HTML element representing the line.
x | (Mandatory) | The x pixel coordinate of the line, relative to the chart.
y1 | (Mandatory) | The y pixel coordinate of the first end point of the line, relative to the chart.
y2 | (Mandatory) | The y pixel coordinate of the second end point of the line, relative to the chart.
lineStyle | (Mandatory) | The line style in CSS border property format (eg. "1px solid black").

Return Value

A DOM element representing the line.


JsChartViewer.showCrossHair

JsChartViewer.showCrossHair

Usage

showCrossHair(x, y[, lineStyle[, leftMargin[, rightMargin[, topMargin[, bottomMargin[, centerOffset]]]]]]);

Description

Displays the crosshair cursor.

The crosshair cursor is a horizontal line and a vertical line that intersects at (x, y). By default, the end points of these lines terminate at the edges of the plot area. The position of the end points are configurable with the leftMargin, rightMargin, topMargin and bottomMargin arguments.

By default, the horizontal and vertical lines are not continuous, but are broken near (x, y). So there is gap around (x, y) where the lines are broken. The gap size is configurable with the centerOffset argument.

The reason for the gap is because the crosshair cursor is frequently used to track the mouse cursor in a JsChartViewer.MouseMovePlotArea event, in which (x, y) is the mouse cursor position. By leaving a gap at (x, y), the underlying chart can receive mouse events. Without the gap, the horizontal or vertical lines will be under the mouse cursor. The browsers may then send mouse events to the horizontal or vertical lines (which are themselves HTML elements) instead of the chart.

The crosshair cursor can be hidden using JsChartViewer.hideObj.

Arguments

Argument | Default | Description
x | (Mandatory) | The x pixel coordinate of the crosshair, relative to the chart.
y | (Mandatory) | The y pixel coordinate of the crosshair, relative to the chart.
lineStyle | "1px | dotted black" The line style of the crosshair in CSS border property format, like "1px solid black" or "2px dotted #FF0000".
leftMargin | 0 | The number of pixels that the crosshair cursor will extend outside the left side of the plot area. A negative number means that the crosshair cursor will be shortened instead of extended.
rightMargin | 0 | The number of pixels that the crosshair cursor will extend outside the right side of the plot area. A negative number means that the crosshair cursor will be shortened instead of extended.
topMargin | 0 | The number of pixels that the crosshair cursor will extend outside the top side of the plot area. A negative number means that the crosshair cursor will be shortened instead of extended.
bottomMargin | 0 | The number of pixels that the crosshair cursor will extend outside the bottom side of the plot area. A negative number means that the crosshair cursor will be shortened instead of extended.
centerOffset | 5 | The radius in pixels of the region around (x, y) where the crosshair cursor lines should be broken.

Return Value

None


JsChartViewer.showTextBox

JsChartViewer.showTextBox

Usage

showTextBox(id, x, y, align, text [, boxStyle ])

Description

Draws a textbox on the chart.

The textbox will be drawn as an HTML element overlaid on top of the chart, with the specified HTML id attribute. The id argument should therefore comply to the HTML standard (eg. begin with A-Z or a-z, followed by letters from A-Z, a-z, 0-9, '-' and '_').

If the id is already used by an existing HTML element, JsChartViewer will assume the element is created earlier by showTextBox, and will reuse the same element instead of creating a new one.

The textbox can be hidden using JsChartViewer.hideObj.

Arguments

Argument | Default | Description
id | (Mandatory) | The id of the HTML element representing the textbox.
x | (Mandatory) | The x pixel coordinate of the reference point of the textbox, relative to the chart.
y | (Mandatory) | The y pixel coordinate of the reference point of the textbox, relative to the chart.
align | (Mandatory) | The alignment of the textbox relative to the reference point. It must be one of JsChartViewer.TopLeft, JsChartViewer.TopCenter, JsChartViewer.TopRight, JsChartViewer.Left, JsChartViewer.Center, JsChartViewer.Right, JsChartViewer.BottomLeft, JsChartViewer.BottomCenter or JsChartViewer.BottomRight. It specifies the point of the textbox that should be the reference point. For example, if TopLeft is used, it means the textbox should be positioned such that the top-left of the text box is at the reference point.
text | (Mandatory) | The text to be displayed.
boxStyle | "" | The box style in the same format used in the HTML "style" attribute. An example is "border:solid 1px black;background:#ffffcc;padding:3px;font:bold 11px Arial;".

Return Value

A DOM element representing the textbox.


JsChartViewer.hideObj

JsChartViewer.hideObj

Usage

hideObj(id)

Description

Hides one or more objects drawn by JsChartViewer.

Arguments

Argument | Default | Description
id | (Mandatory) | The HTML id of the element to be hidden. The special value "crosshair" means that the crosshair cursor will be hidden. The special value "all" means that all lines, text boxes and crosshair cursor drawn by the JsChartViewer object will be hidden.

Return Value

None


JsChartViewer.setAutoHide

JsChartViewer.setAutoHide

Usage

setAutoHide(id, eventId)

Description

Hides one or more objects drawn by JsChartViewer when a certain event occurs.

This method automatically calls JsChartViewer.hideObj when a certain event occurs. For example, it can be used to hide the crosshair cursor or all objects drawn by JsChartViewer when the JsChartViewer.MouseOutPlotArea event occurs. Using this method can avoid the need to create a separate event handler.

This method only applies to the first occurrence of the specified event after calling this method.

JsChartViewer.removeAutoHide can be used to cancel the automatic action set up by this method.

Arguments

Argument | Default | Description
id | (Mandatory) | The id argument to be used to call JsChartViewer.hideObj.
eventId | (Mandatory) | A text string representing the event that triggers the call to JsChartViewer.hideObj. An example is "MouseOutPlotArea" (for the JsChartViewer.MouseOutPlotArea event).

Return Value

None


JsChartViewer.removeAutoHide

JsChartViewer.removeAutoHide

Usage

removeAutoHide(id, eventId)

Description

Cancels the automatic action sets up by JsChartViewer.setAutoHide.

Arguments

Argument | Default | Description
id | (Mandatory) | The id argument used in the JsChartViewer.setAutoHide call that is to be cancelled.
eventId | (Mandatory) | The eventId argument used in the JsChartViewer.setAutoHide call that is to be cancelled.

Return Value

None


JsChartViewer.htmlRect

JsChartViewer.htmlRect

Usage

htmlRect(w, h, color [, border ])

Description

Generates HTML code that represents an inline color box.

Inline color boxes are useful as legend icons in creating legends dynamically. However, it is not easy to create inline color boxes (boxes that can flow with text similar to a character) that behaves consistently in all browsers.

This method returns an HTML inline color box that is designed to work consistently in all browsers supported by JsChartViewer. Note that to support IE 7 or below, this method requires the file "spacer.gif" to be in the same directory as the Javascript. (The "spacer.gif" is a file included in the ChartDirector distribution. It is a transparent GIF image 1 x 1 pixel in size.) Without this file, the box will always have a grey border in IE 7 or below.

Arguments

Argument | Default | Description
w | (Mandatory) | The width of the box in pixels.
h | (Mandatory) | The height of the box in pixels.
color | (Mandatory) | The color of the box in HTML color format (eg. "#FF0000" or "red")
border | "" | The border style of the box in CSS border property format (eg. "1px solid black").

Return Value

A text string containing HTML that represents an inline color box.


JsChartViewer.addEventListener

JsChartViewer.addEventListener

Usage

addEventListener(obj, evt, func[, useCapture])

Description

A utility to attach an event handler to a Javascript event.

A Javascript event refers to Javascript events generated by the browser (as opposed to JsChartViewer events). An example is the "onload" event of the <body> tag.

The classical way to attach an event handler to a Javascript event is to use an attribute. For example, the "onload" attribute can be used to attach a handler to the "onload" event. The disadvantage of this method is that only one event handler can be attached. It becomes difficult to manage if multiple scripts all want to programmatically attach event handlers to the same event of the same object.

Modern browsers have special methods that allow multiple event handlers to be attached to the same event of the same object. However, the methods are different for different browsers. Some browsers use the addEventListener method, while some browsers use the attachEvent method.

JsChartViewer.addEventListener is a utility method that calls the target object's addEventListener method if the method exists, or the attachEvent method if it does not exist. Using this method an avoid writing different code to handle different browsers.

Note: This is a static method (class method). It should be accessed as JsChartViewer.addEventListener, not objName.addEventListener.

Arguments

Argument | Default | Description
obj | (Mandatory) | The object to which the event handler is attached to.
evt | (Mandatory) | The name of the event, according to the Javascript addEventListener method. In this method, there is no "on" in front of the event name. For example, the event for the "onload" attribute should simply be called "load", not "onload".
func | (Mandatory) | A Javascript function that handles the event.
useCapture | (Optional) | The useCapture flag as used in the Javascript addEventListener method.

Return Value

None


JsChartViewer.removeEventListener

JsChartViewer.removeEventListener

Usage

removeEventListener(obj, evt, func[, useCapture])

Description

Removes an event handler attached via a previous call to JsChartViewer.addEventListener.

Note: This is a static method (class method). It should be accessed as JsChartViewer.removeEventListener, not objName.removeEventListener.

Arguments

Argument | Default | Description
obj | (Mandatory) | The same obj argument that was passed to the previous call to JsChartViewer.addEventListener.
evt | (Mandatory) | The same evt argument that was passed to the previous call to JsChartViewer.addEventListener.
func | (Mandatory) | The same func argument that was passed to the previous call to JsChartViewer.addEventListener.
useCapture | (Optional) | The same useCapture argument that was passed to the previous call to JsChartViewer.addEventListener.

Return Value

None


JsChartViewer.NTime

JsChartViewer.NTime

Usage

NTime(time)

Description

Converts a date/time in ChartDirector's date/time format to a Javascript Date object.

Note: This is a static method (class method). It should be accessed as JsChartViewer.NTime, not objName.NTime.

Arguments

Argument | Default | Description
time | (Mandatory) | A number representing date/time using ChartDirector's date/time format.

Return Value

A Javascript Date object.


JsChartViewer.CTime

JsChartViewer.CTime

Usage

CTime(time)

Description

Converts a Javascript Date object to ChartDirector's date/time format.

Note: This is a static method (class method). It should be accessed as JsChartViewer.CTime, not objName.CTime.

Arguments

Argument | Default | Description
time | (Mandatory) | A Javascript Date object.

Return Value

A number representing dates/time in ChartDirector's date/time format.


JsChartViewer.MouseMoveChart

JsChartViewer.MouseMoveChart

Description

This event occurs when the mouse cursor moves on the chart.

Use JsChartViewer.attachHandler with the event id "MouseMoveChart" to attach a handler to this event.

The JsChartViewer.getChartMouseX, JsChartViewer.getChartMouseY, JsChartViewer.getPlotAreaMouseX and JsChartViewer.getPlotAreaMouseY can be used to obtain the mouse cursor coordinates relative to the chart.


JsChartViewer.MouseOutChart

JsChartViewer.MouseOutChart

Description

This event occurs when the mouse cursor leaves the chart.

Use JsChartViewer.attachHandler with the event id "MouseOutChart" to attach a handler to this event.


JsChartViewer.MouseMovePlotArea

JsChartViewer.MouseMovePlotArea

Description

This event occurs when the mouse cursor moves on the extended plot area.

Use JsChartViewer.attachHandler with the event id "MouseMovePlotArea" to attach a handler to this event.

See JsChartViewer.setPlotAreaMouseMargin on what is the extended plot area.

The JsChartViewer.getChartMouseX, JsChartViewer.getChartMouseY, JsChartViewer.getPlotAreaMouseX and JsChartViewer.getPlotAreaMouseY can be used to obtain the mouse cursor coordinates relative to the chart.


JsChartViewer.MouseOutPlotArea

JsChartViewer.MouseOutPlotArea

Description

This event occurs when the mouse cursor leaves the extended plot area.

Use JsChartViewer.attachHandler with the event id "MouseOutPlotArea" to attach a handler to this event.

See JsChartViewer.setPlotAreaMouseMargin on what is the extended plot area.


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.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.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.


Javascript Chart Model

Javascript Chart Model

The ChartDirector Javascript Chart Model is a read-only representation of a ChartDirector chart as Javascript objects on the browser side. It is designed to facilitate implementing track cursors on the browser side.

To draw track cursors on the browser side, certain chart configuration (such as the position and size of the plot area, the axis scale of all axes, the data values, etc) needs to be accessible on the browser side. To do this, BaseChart.getJsChartModel can be used on the server side to generate a data structure containing the chart configuration. The data structure can then be passed to the WebChartViewer using WebChartViewer.setChartModel, which will send it to the browser. On the browser side, the Javascript Chart Viewer will use the data structure to construct Javascript objects representing the chart. These objects can be accessed using JsChartViewer.getChart.

Currently, the Javascript Chart Model only supports XYChart objects.

A chart can contain a huge amount of data. Sending all of them over the network to the browser can be slow, inefficient and unnecessary for the purpose of drawing track cursors. ChartDirector addresses this issue by sending only a subset of the chart configuration that are commonly used to draw track cursors.

For example, consider a line layer containing 50000 data points with the line flowing horizontally. If the plot area is 500 pixels wide, a track cursor "sweep line" that moves with the mouse can have at most 500 different coordinates. It is because the mouse coordinate must be an integer. In other words, even on average there can be 500 data points between two pixels, the "sweep line" must jump from one pixel directly to the next pixel, skipping all the data points in between. In this case, in generating the Javascript Chart Model, ChartDirector will omit the data points that cannot be addressed by a track cursor. In practice, this method limits the data for each data set to no more than 2 times the number of x pixels in the plot area.

Classes in Javascript Chart Model

Class | Description
JsXYChart | The JsXYChart class represents XY charts in the Javascript Chart Model. The corresponding server side class is XYChart. JsXYChart objects can be obtained using JsChartViewer.getChart.
JsPlotArea | The JsPlotArea class represents plot areas in the Javascript Chart Model. The corresponding server side class is PlotArea. JsPlotArea objects can be obtained using JsXYChart.getPlotArea.
JsAxis | The JsAxis class represents axes in the Javascript Chart Model. The corresponding server side class is Axis. JsAxis objects can be obtained using JsXYChart.xAxis, JsXYChart.xAxis2, JsXYChart.yAxis, JsXYChart.yAxis2 or JsDataSet.getUseYAxis.
JsLayer | The JsLayer class represents data layers in the Javascript Chart Model. The corresponding server side class is Layer. JsLayer objects can be obtained using JsXYChart.getLayer or JsXYChart.getLayerByZ.
JsDataSet | The JsDataSet class represents data sets in the Javascript Chart Model. The corresponding server side class is DataSet. JsDataSet objects can be obtained using JsLayer.getDataSet or JsLayer.getDataSetByZ.


JsXYChart

JsXYChart

The JsXYChart class represents XY charts in the Javascript Chart Model. The corresponding server side class is XYChart. JsXYChart objects can be obtained using JsChartViewer.getChart.

Method | Inherited | Description
getAbsOffsetX | (Self) | Gets the x offset of the chart relative to the outermost MultiChart container.
getAbsOffsetY | (Self) | Gets the y offset of the chart relative to the outermost MultiChart container.
getPlotArea | (Self) | Gets the JsPlotArea object representing the plot area of the XYChart.
getLayer | (Self) | Gets a JsLayer object based on the order in which it is being added to the chart.
getLayerByZ | (Self) | Gets a JsLayer object based on the order in which it is being drawn.
getLayerCount | (Self) | Gets the number of layers in the chart.
xAxis | (Self) | Gets the JsAxis object representing the primary x-axis of the XYChart.
xAxis2 | (Self) | Gets the JsAxis object representing the secondary x-axis of the XYChart.
yAxis | (Self) | Gets the JsAxis object representing the primary y-axis of the XYChart.
yAxis2 | (Self) | Gets the JsAxis object representing the secondary y-axis of the XYChart.
getXCoor | (Self) | Gets the x pixel coordinate given the x data value.
getYCoor | (Self) | Gets the y pixel coordinate given the y data value.
getXValue | (Self) | Gets the x data value given the x pixel coordinate.
getYValue | (Self) | Gets the y data value given the y pixel coordinate.
getNearestXValue | (Self) | Gets the x data value that is nearest to the specified x pixel coordinate.
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.


JsXYChart.getAbsOffsetX

JsXYChart.getAbsOffsetX

Usage

getAbsOffsetX()

Description

Gets the x offset of the chart relative to the outermost MultiChart container.

Arguments

None

Return Value

An integer representing the x offset in pixels relative to the outermost MultiChart container, or 0 if the chart is not within a MultiChart container.


JsXYChart.getAbsOffsetY

JsXYChart.getAbsOffsetY

Usage

getAbsOffsetY()

Description

Gets the y offset of the chart relative to the outermost MultiChart container.

Arguments

None

Return Value

An integer representing the y offset in pixels relative to the outermost MultiChart container, or 0 if the chart is not within a MultiChart container.


JsXYChart.getPlotArea

JsXYChart.getPlotArea

Usage

getPlotArea()

Description

Gets the JsPlotArea object representing the plot area of the XYChart.

Arguments

None

Return Value

The JsPlotArea object representing the plot area of the XYChart.


JsXYChart.getLayer

JsXYChart.getLayer

Usage

getLayer(i)

Description

Gets a JsLayer object based on the order in which it is being added to the chart.

Arguments

Argument | Default | Description
i | (Mandatory) | The index of the data layer. The index of the first layer added to the chart is 0. The index of the Nth layer added to the chart is N - 1.

Return Value

The specified JsLayer object.


JsXYChart.getLayerByZ

JsXYChart.getLayerByZ

Usage

getLayerByZ(zIndex)

Description

Gets a JsLayer object based on the order in which it is being drawn.

Arguments

Argument | Default | Description
zIndex | (Mandatory) | The z-index of the required layer. The z-index of the first layer drawn is 0. The z-index for the Nth layer drawn is N - 1.

Return Value

The JsLayer object at the specified z-order.


JsXYChart.getLayerCount

JsXYChart.getLayerCount

Usage

getLayerCount()

Description

Gets the number of layers in the chart.

Arguments

None

Return Value

The number of layers in the chart.


JsXYChart.xAxis

JsXYChart.xAxis

Usage

xAxis()

Description

Gets the JsAxis object representing the primary x-axis of the XYChart.

Arguments

None

Return Value

The JsAxis object representing the primary x-axis of the XYChart.


JsXYChart.xAxis2

JsXYChart.xAxis2

Usage

xAxis2()

Description

Gets the JsAxis object representing the secondary x-axis of the XYChart.

Arguments

None

Return Value

The JsAxis object representing the secondary x-axis of the XYChart.


JsXYChart.yAxis

JsXYChart.yAxis

Usage

yAxis()

Description

Gets the JsAxis object representing the primary y-axis of the XYChart.

Arguments

None

Return Value

The JsAxis object representing the primary y-axis of the XYChart.


JsXYChart.yAxis2

JsXYChart.yAxis2

Usage

yAxis2()

Description

Gets the JsAxis object representing the secondary y-axis of the XYChart.

Arguments

None

Return Value

The JsAxis object representing the secondary y-axis of the XYChart.


JsXYChart.getXCoor

JsXYChart.getXCoor

Usage

getXCoor(v)

Description

Gets the x pixel coordinate given the x data value.

Arguments

Argument | Default | Description
v | (Mandatory) | The x data value.

Return Value

The x pixel coordinate of the x data value.


JsXYChart.getYCoor

JsXYChart.getYCoor

Usage

getYCoor(v [, yAxis ])

Description

Gets the y pixel coordinate given the y data value.

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 JsXYChart.yAxis or JsXYChart.yAxis2. The default is to use the primary y-axis.

Return Value

The y pixel coordinate of the y data value.


JsXYChart.getXValue

JsXYChart.getXValue

Usage

getXValue(xCoor)

Description

Gets the x data value given the x pixel coordinate.

This method always returns a numeric value. If the axis scale is a date/time scale, and you are expecting a date data type, please use JsChartViewer.NTime to convert the number to a Javascript Date object.

Arguments

Argument | Default | Description
xCoor | (Mandatory) | The x pixel coordinate.

Return Value

The x data value at the x pixel coordinate.


JsXYChart.getYValue

JsXYChart.getYValue

Usage

getYValue(yCoor [, yAxis ])

Description

Gets the y data value given the y pixel coordinate.

This method always returns a numeric value. If the axis scale is a date/time scale, and you are expecting a date data type, please use JsChartViewer.NTime to convert the number to a Javascript Date object.

Arguments

Argument | Default | Description
yCoor | (Mandatory) | The y pixel coordinate.
yAxis | [Null] | The y-axis to use to determine the pixel coordinates of data values. The y-axis may be obtained using JsXYChart.yAxis or JsXYChart.yAxis2. The default is to use the primary y-axis.

Return Value

The y data value at the y pixel coordinate.


JsXYChart.getNearestXValue

JsXYChart.getNearestXValue

Usage

getNearestXValue(xCoor)

Description

Gets the x data value that is nearest to the specified x pixel coordinate.

This method will search all x data values in the JsXYChart to look for the x data value that is nearest to the given x coordinate. If there are two x data values equally near to the specified x pixel coordinate, this method will arbitrarily return one of the values.

Arguments

Argument | Default | Description
xCoor | (Mandatory) | The x pixel coordinate to search for.

Return Value

The x data value that is nearest to the specified x coordinate.


JsXYChart.formatValue

JsXYChart.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

A text string containing the formatted result.


JsXYChart.setNumberFormat

JsXYChart.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


JsXYChart.setMonthNames

JsXYChart.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


JsXYChart.setWeekDayNames

JsXYChart.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


JsXYChart.setAMPM

JsXYChart.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


JsPlotArea

JsPlotArea

The JsPlotArea class represents plot areas in the Javascript Chart Model. The corresponding server side class is PlotArea. JsPlotArea objects can be obtained using JsXYChart.getPlotArea.

Method | Inherited | Description
getLeftX | (Self) | Gets the left x pixel coordinate of the plot area.
getRightX | (Self) | Gets the right x pixel coordinate of the plot area.
getTopY | (Self) | Gets the top y pixel coordinate of the plot area.
getBottomY | (Self) | Gets the bottom y pixel coordinate of the plot area.
getWidth | (Self) | Gets the width of the plot area.
getHeight | (Self) | Gets the height of the plot area.


JsPlotArea.getLeftX

JsPlotArea.getLeftX

Usage

getLeftX()

Description

Gets the left x pixel coordinate of the plot area.

Arguments

None

Return Value

The left x pixel coordinate of the plot area.


JsPlotArea.getRightX

JsPlotArea.getRightX

Usage

getRightX()

Description

Gets the right x pixel coordinate of the plot area.

Arguments

None

Return Value

The right x pixel coordinate of the plot area.


JsPlotArea.getTopY

JsPlotArea.getTopY

Usage

getTopY()

Description

Gets the top y pixel coordinate of the plot area.

Arguments

None

Return Value

The top y pixel coordinate of the plot area.


JsPlotArea.getBottomY

JsPlotArea.getBottomY

Usage

getBottomY()

Description

Gets the bottom y pixel coordinate of the plot area.

Arguments

None

Return Value

The bottom y pixel coordinate of the plot area.


JsPlotArea.getWidth

JsPlotArea.getWidth

Usage

getWidth()

Description

Gets the width of the plot area.

Arguments

None

Return Value

The width of the plot area in pixels.


JsPlotArea.getHeight

JsPlotArea.getHeight

Usage

getHeight()

Description

Gets the height of the plot area.

Arguments

None

Return Value

The height of the plot area in pixels.


JsAxis

JsAxis

The JsAxis class represents axes in the Javascript Chart Model. The corresponding server side class is Axis. JsAxis objects can be obtained using JsXYChart.xAxis, JsXYChart.xAxis2, JsXYChart.yAxis, JsXYChart.yAxis2 or JsDataSet.getUseYAxis.

Method | Inherited | Description
getX | (Self) | Gets the x-coordinate of starting point of the axis.
getY | (Self) | Gets the y-coordinate of starting point of the axis.
getAlignment | (Self) | Gets the side of the plot area that the axis is associated with.
getMinValue | (Self) | Gets the lower bound of the axis.
getMaxValue | (Self) | Gets the upper bound of the axis.
getLabel | (Self) | Gets the label at the specified position on the axis.
getFormattedLabel | (Self) | Gets the label at the specified position on the axis, formatting one if necessary.


JsAxis.getX

JsAxis.getX

Usage

getX()

Description

Gets the x-coordinate of starting point of the axis.

For a horizontal axis, the starting point is its left end point. For a vertical axis, the starting point is its bottom end point.

Arguments

None

Return Value

The x-coordinate of starting point of the axis.


JsAxis.getY

JsAxis.getY

Usage

getY()

Description

Gets the y-coordinate of starting point of the axis.

For a horizontal axis, the starting point is its left end point. For a vertical axis, the starting point is its bottom end point.

Arguments

None

Return Value

The y-coordinate of starting point of the axis.


JsAxis.getAlignment

JsAxis.getAlignment

Usage

getAlignment()

Description

Gets the side of the plot area that the axis is associated with.

Arguments

None

Return Value

A constant equals to JsChartViewer.Left, JsChartViewer.Right, JsChartViewer.Top or JsChartViewer.Bottom, depending on the side of the plot area that the axis is associated with.


JsAxis.getMinValue

JsAxis.getMinValue

Usage

getMinValue()

Description

Gets the lower bound of the axis.

Arguments

None

Return Value

The lower bound of the axis.


JsAxis.getMaxValue

JsAxis.getMaxValue

Usage

getMaxValue()

Description

Gets the upper bound of the axis.

Arguments

None

Return Value

The upper bound of the axis.


JsAxis.getLabel

JsAxis.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.


JsAxis.getFormattedLabel

JsAxis.getFormattedLabel

Usage

getFormattedLabel(i [, formatString ])

Description

Gets the label at the specified position on the axis, formatting one if necessary.

Arguments

Argument | Default | Description
i | (Mandatory) | The position specified as a value on the axis scale.
formatString | "" | The format string used to format a label if necessary. Please refer to Axis.setLabelFormat for the syntax of the format string. An empty string means the format will be automatically determined.

Return Value

Returns the label at the specified position. If there is no axis label at that position, formats one using the format string.


JsLayer

JsLayer

The JsLayer class represents data layers in the Javascript Chart Model. The corresponding server side class is Layer. JsLayer objects can be obtained using JsXYChart.getLayer or JsXYChart.getLayerByZ.

Method | Inherited | Description
getDataSet | (Self) | Gets a JsDataSet object based on the order in which it is being added to the chart.
getDataSetByZ | (Self) | Gets a JsDataSet object based on the order in which it is being drawn.
getDataSetCount | (Self) | Gets the number of data sets in the layer.
getNearestXValue | (Self) | Gets the x data value that is nearest to the specified x pixel coordinate.
getXIndexOf | (Self) | Gets the data point index at the specified x data value.
getXPosition | (Self) | Gets the x positional value of a data point, as measured on the primary x-axis.


JsLayer.getDataSet

JsLayer.getDataSet

Usage

getDataSet(dataSetNo)

Description

Gets a JsDataSet object based on the order in which it is being added to the chart.

Arguments

Argument | Default | Description
dataSetNo | (Mandatory) | The index of the data set. The index of the first data set added to the layer is 0. The index of the Nth data set added to the layer is N - 1.

Return Value

The specified JsDataSet object.


JsLayer.getDataSetByZ

JsLayer.getDataSetByZ

Usage

getDataSetByZ(zIndex)

Description

Gets a JsDataSet object based on the order in which it is being drawn.

Arguments

Argument | Default | Description
zIndex | (Mandatory) | The z-index of the required data set. The z-index of the first data set drawn is 0. The z-index for the Nth data set drawn is N - 1.

Return Value

The JsDataSet object at the specified z-order.


JsLayer.getDataSetCount

JsLayer.getDataSetCount

Usage

getDataSetCount()

Description

Gets the number of data sets in the layer.

Arguments

None

Return Value

The number of data sets in the layer.


JsLayer.getNearestXValue

JsLayer.getNearestXValue

Usage

getNearestXValue(xCoor)

Description

Gets the x data value that is nearest to the specified x pixel coordinate.

This method will search all x data values in the JsLayer to look for the x data value that is nearest to the given x coordinate. If there are two x data values equally near to the specified x pixel coordinate, this method will arbitrarily return one of the values.

Arguments

Argument | Default | Description
xCoor | (Mandatory) | The x pixel coordinate to search for.

Return Value

The x data value that is nearest to the specified x coordinate.


JsLayer.getXIndexOf

JsLayer.getXIndexOf

Usage

getXIndexOf(xValue [, tolerance ])

Description

Gets the data point index at the specified x data value.

The index can be used in JsDataSet.getValue and JsDataSet.getPosition to obtain the y values and positions of the data points for all data sets in the layer.

The tolerance argument is to allow this method to consider data points that are not exactly at xValue, but are within tolerance from it.

If multiple data points at within tolerance, this method will return the index of the data point nearest to xValue. If multiple data points are equally near to xValue, this method will choose one arbitrarily and return its data point index. If no data points are found, this method will return -1.

Arguments

Argument | Default | Description
xValue | (Mandatory) | The x data value used to look for the data points in order to get the data point index of the nearest data point.
tolerance | 0 | The tolerance allowed for for data points that are not exactly at the specified xValue.

Return Value

The data point index of the data point nearest to the specified x data value up to the specified tolerance, or -1 if no data points are found.


JsLayer.getXPosition

JsLayer.getXPosition

Usage

getXPosition(i)

Description

Gets the x positional value of a data point, as measured on the primary x-axis.

Arguments

Argument | Default | Description
i | (Mandatory) | The data point index of the data point. The index is typically obtained using JsLayer.getXIndexOf.

Return Value

The x positional value of the data point.


JsDataSet

JsDataSet

The JsDataSet class represents data sets in the Javascript Chart Model. The corresponding server side class is DataSet. JsDataSet objects can be obtained using JsLayer.getDataSet or JsLayer.getDataSetByZ.

Method | Inherited | Description
getDataName | (Self) | Gets the name of the data set.
getDataColor | (Self) | Gets the main color used to draw the data set.
getUseYAxis | (Self) | Gets the y-axis to use when drawing the data set.
getValue | (Self) | Gets the value of a data point.
getPosition | (Self) | Gets the positional value of a data point.


JsDataSet.getDataName

JsDataSet.getDataName

Usage

getDataName()

Description

Gets the name of the data set.

Arguments

None

Return Value

The name of the data set.


JsDataSet.getDataColor

JsDataSet.getDataColor

Usage

getDataColor()

Description

Gets the main color used to draw the data set.

This method returns the color in HTML color format. For example, the pure red color FF0000 will be returned as a text string "#FF0000". The returned value can therefore be used as the color of HTML elements.

Because the HTML color format does not support semi-transparent colors, the alpha channel in the color will be removed. For example, the semi-transparent green color 80FF0000 will be returned as "#00FF00", with the alpha channel "80" removed. If the color is totally transparent (corresponding to the Transparent color in the server side), this method returns null.

Also, the HTML color format does not support dynamic colors (such as gradients), so non-RGB colors are not supported.

Arguments

None

Return Value

The main color used to draw the data set in HTML color format.


JsDataSet.getUseYAxis

JsDataSet.getUseYAxis

Usage

getUseYAxis()

Description

Gets the y-axis to use when drawing the data set.

Arguments

None

Return Value

An JsAxis object representing the y-axis to use when drawing the data set.


JsDataSet.getValue

JsDataSet.getValue

Usage

getValue(i)

Description

Gets the value of a data point.

Arguments

Argument | Default | Description
i | (Mandatory) | The data point index of the data point. The index is typically obtained using JsLayer.getXIndexOf.

Return Value

The value of the data point.


JsDataSet.getPosition

JsDataSet.getPosition

Usage

getPosition(i)

Description

Gets the positional value of a data point.

The positional value is the value used to position the data point. Usually, the positional value is equal to the data value. However, for chart types in which the data sets are combined using the Stack or Percentage method, the positional value can be different from the data value. For example, for stacked charts, the positional value of a data point is equal to the accumulative value of the corresponding data points from data sets added before the target data set.

Arguments

Argument | Default | Description
i | (Mandatory) | The data point index of the data point. The index is typically obtained using JsLayer.getXIndexOf.

Return Value

The positional value of the data point.


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.

Most programming language requires you to put special prefix in front of hexadecimal number. For Java , the prefix is "0x". For example, the syntax for the hexadecimal number 00FFFFFF is 0x00FFFFFF, or simply 0xFFFFFF.

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.

Note: Java has a class java.awt.Color that is sometimes used to represent colors. ChartDirector provides several functions for converting between java.awt.Color objects and ChartDirector colors. These include Chart.CColor, Chart.CColor2, Chart.NColor and Chart.NColor2.

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 Chart.metalColor, Chart.goldColor and Chart.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 Java, a font can be specified using the format:

{font name} [Bold] [Italic]

where "{font name}" is a Java compatible font name (that is, the font name that is used in java.awt.Font). The "[Bold]" and "[Italic]" are optional. The followings are some examples:

Arial Bold
Times New Roman
Courier Bold Italic
SansSerif

When using the above format, you may use all fonts that are known to the Java system.

ChartDirector also supports using true-type fonts that are unknown to the Java system. This is useful if you are using private fonts in your application. The method is by specifying the font using the font file name. ChartDirector will search the font file from the class path, and also will search using the java library path (java.library.path).

For example, if you are using ChartDirector on a web server, you can put the fonts files in the WEB-INF/classes inside your web application directory. In this way, you can use your own fonts without relying on the fonts provided by the web server.

Note: Private font files support require Java 1.3 or above.

Note: Using Java fonts or private font files requires your Java font system be functional (java.awt.Font is functional).

Java on Microsoft Windows, Mac OS X, and Java systems that interacts with a GUI (such as standalone Java programs and Java Applets) always have functional font systems. However, some server side Java systems, such as the Java for running JSP or servlets on Linux/UNIX servers, may not have a working font system.

It is because many Java systems on Linux/UNIX rely on X Window services to support fonts. On the other hand, many servers do not need a GUI and may not have X Window. In these cases, any attempt to use the Java font system (eg. simply create a java.awt.Font object) will cause Java to throw an Error.

To solve this problem, ChartDirector comes with its own internal font system. If the Java font system is not functional, ChartDirector will automatically use its internal font system, so the charts will still work. The internal font system only have 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.

If you are encounter the above problem but still want to use the Java font system, you may start Java in "headless" mode (requires Java 1.4 or above). Please refer to the link below on how to start Java in "headless" mode.

http://java.sun.com/j2se/1.4.2/docs/guide/awt/AWTChanges.html#headless

If you are using Java 1.3 or Java 1.2 and you want to use the Java font system, you may need to install a working GUI subsystem on your computer.

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 Java. 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 Java, 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 (5, 1) above.
DiamondShape | 2 | Diamond shape. See (6, 1) above.
TriangleShape | 3 | Triangle shape pointing upwards. See (1, 2) above.
RightTriangleShape | 4 | Triangle shape pointing rightwards. See (2, 2) above.
LeftTriangleShape | 5 | Triangle shape pointing leftwards. See (3, 2) above.
InvertedTriangleShape | 6 | Triangle shape pointing downwards. See (4, 2) above.
CircleShape | 7 | Circle shape. See (1, 1) above.
GlassSphereShape | 15 | Glass sphere shape. See (2, 1) above.
GlassSphere2Shape | 16 | Bright glass sphere shape. See (3, 1) above.
SolidSphereShape | 17 | Solid sphere shape. See (4, 1) above.
StarShape | [Method] | Star shapes of various points. See (5, 2), (6, 2), (1, 3), (2, 3), (3, 3), (4, 3), (5, 3), (6, 3) 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 (1, 4) and (3, 4) for polygons of 5 and 6 sides.
Polygon2Shape | [Method] | Polygon shapes symmetrical about a vertical axis but without any vertex at the top center position. See (2, 4), (4, 4) for polygons of 5 and 6 sides.
CrossShape | [Method] | '+' shapes. See (5, 4), (6, 4), (1, 5), (2, 5), (3, 5), (4, 5), (5, 5) for '+' shape with arm width of 0.1 - 0.7.
Cross2Shape | [Method] | 'X' shapes. See (6, 5), (1, 6), (2, 6), (3, 6), (4, 6), (5, 6), (6, 6) 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 represents dates/times as the number of seconds elapsed since 1-1-0001 00:00:00. The dates/times are numbers, so they can readily be used in ChartDirector APIs that expects numbers as arguments.

For example, in XY Charts, both the x values and y values are of "double" data type. You can use numeric values or ChartDirector dates/times as the x and y values, as both of them are numbers.

In Java, there is a class java.util.Date that is commonly used to represents date/time. Several ChartDirector APIs are overloaded to accept java.util.Date in addition to double precision numbers. These overloaded functions are provided to handle common date/time chart usages.

For example, in a typical time based chart, the independent variable (the x values) usually represents date/time, while the dependent variable (the y values) is numeric. So in ChartDirector, many x-values functions (eg. Layer.setXData, Layer.setXData2) and axis functions (eg. Axis.setLabels2, Axis.setDateScale) are overloaded to support java.util.Date as arguments.

ChartDirector also supports charts in which both x and y values are dates/times. However, because this type of chart is not common, ChartDirector does not provide overloaded functions to accept y values as java.util.Date. This is to avoid overcrowding the ChartDirector API with all possible combinations of date/time and numeric data types. For these cases, the y dates/times need to be supplied in ChartDirector's native format.

Chart.chartTime can be used to create a ChartDirector date/time given the year, month, day, hour, minutes and seconds. ChartDirector also provides several functions for converting to and from java.util.Date, including Chart.CTime, Chart.CTime2, Chart.NTime and Chart.NTime2.


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 by marking up the text with tags. It allows using different fonts and colors for different parts of the text, embedding images and symbols in the text, and customizing the text layout.

Font Styles

You can change the style of the text by using CDML tags. For example, the line:

<*font=Times New Roman Italic,size=16,color=FF0000*>Hello <*font=Arial,size=12,color=008000*>world!

will result in the following text rendered:

In general, all tags in CDML are enclosed by <* and *>. 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. Multiple font style attributes can be put in the same tag, separated by commas, or you may put each attribute in its own tag.

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. To terminate a style section, use "/font". This restores the style to the state before the style section.
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.

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:

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 and Symbols

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:

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.

Apart from using image files, the <*img*> also supports built-in symbols. An example is:

<*size=10*>Change: <*img=@Triangle,color=00CC00,width=7,height=10*>+50%

The above will result in the following:

To use built-in symbols, instead of a filename, a '@' character should be used, followed by the shape id. The available built-in shapes are described in Shape Specification. Note that in CDML, the shape id does not have the trailing "Shape" word. For example, the "DiamondShape" in the Shape Specification should be represented as "@Diamond" in CDML. If the shape requires a parameter, the parameter should be supplied by enclosing it in parentheses. The symbol width, height, fill color and edge color can be specified with the "width", "height", "color" and "edgeColor" attributes respectively.

The following table describes the supported attributes inside the <*img*> tag:

Attribute | Description
img | The image specification, which can be the path name for an image file, or a '@' character followed by the shape id for a built-in symbol.
width | The width of the image or symbol in pixels.
height | The height of the image or symbol in pixels.
size | A shortcut to set both the width and height of the image or symbol to the same value in pixels.
color | The color of the symbol.
edgeColor | The edgeColor of the symbol.

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 the <*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.
edgeColor | The edge color of the block in hex format.
margin | The margins between the content of the block to the edges of the block. If the margin is a single number, it will be applied to the left, right, top and bottom margins. If the margin is two to four numbers separated by spaces, they will be applied to the left, right, top and bottom margins, with the default value of 0. For example, "margin=3 5" will set the left and right margins to 3 and 5 pixels, and the top and bottom margins to 0.
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. 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 values 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, and {field1} means the second extra field. An extra field is an array of custom values 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 in linear regression analysis.
intercept | The y-intercept of the trend line in linear regression analysis.
corr | The correlation coefficient in regression analysis.
stderr | The standard error in regression analysis.
coeffN | The coefficient with index N in the regression formula. For example, coeff0 and coeff1 are the a0 and a1 in the regression formula. See TrendLayer for the supported regression formulas.

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 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 layer index 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 the axis.

Parameter | Description
value | The axis value at the tick position.
label | The axis label at the tick position.

Parameters for Pyramid Charts

The following table describes the parameters available for pyramid charts.

Parameter | Description
index | The index number of the pyramid layer. The first pyramid layer is 0. The nth pyramid layer is (n-1).
dataSet | Same as {index}. See above.
label | The text label of the pyramid layer.
dataSetName | Same as {label}. See above.
value | The data value of the pyramid layer.
percent | The percentage value of the pyramid layer.
fieldN | The (N + 1)th extra field. For example, {field0} means the first extra field. An extra field is an array of custom values added using BaseChart.addExtraField or BaseChart.addExtraField2.

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 n, the value will be formatted using scientific notation with n 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 n, the value will be formatted using the scientific notation only if the value is large and requires more than the n digits, or the value is less than 0.001. If scientific notation is used, n is the number of significant digits. 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 this field starts with "P" followed by a number n, the value will be formatted with no more than n decimal places. The result may contain less decimal places if they are not needed, or if the value already has more than n significant digits. If the "P" is not followed by a number, 3 is assumed.

    For example, if P3 is used, the value 1.234567 will be formatted to 1.235 (3 decimal points); the value 1.2 will be formatted to 1.2 (additional decimal places are not needed); the value 12.34567 will be formatted to 12.35 (already has more than 3 significant digits), and the value 123456.789 will be formatted to 123457 (already has more than 3 significant digits).

    The "P" format is useful to format a number to a given precision, without using more decimal places than needed or switching to scientific formatting.

  • For Axis label formatting, the special character "@" can be used. It means to use a fixed number of decimal places automatically determined by the Axis object. For example, if the axis labels are 0, 0.5, 1, 1.5, 2, the Axis object may decide to use 1 decimal place, in which case the labels will become 0.0, 0.5, 1.0, 1.5, 2.0.

If you skip this field, ChartDirector will display the exact value using at most 6 decimal places.
[b] | The thousand separator, which should be a non-alphanumeric character (not 0-9, A-Z, a-z). Use '~' for no thousand separator. If this character is not specified or is '?', the default is no thousand separator. The default is configurable using BaseChart.setNumberFormat.
[c] | The decimal separator. Use '~' for no decimal separator. If this character is not specified or is '?', the default is '.'. The default is configurable using BaseChart.setNumberFormat.
[d] | The negative sign character. Use '~' for no negative sign character. If this character is not specified or is '?', the default is '-'. The default is configurable using BaseChart.setNumberFormat.
[e] | The currency character. The currency character will appear before the digits of the number, but after the negative sign character for negative numbers.

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 a 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 a 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 a 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 1 - 12.
nn | The minute formatted as 2 digits from 00 - 59, adding a 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 a leading zero if necessary.
s | The second formatted using the minimum number of digits from 00 - 59.
fff | The millisecond formatted as 3 digits from 000 - 999.
ff | The hundredths of a second formatted as 2 digits from 00 - 99.
f | The tenths of a second formatted as 1 digit from 0 - 9.
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 "&#nn;" (eg. ">" will become "&#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, and should not be useful outside of ChartDirector (such as in browser tool tips).

In some cases, you may not want ChartDirector to escape 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. You may need to use the pageEncoding attribute of the @page directive to ensure your JSP understands your encoding. For example:

<%@page import="ChartDirector.*" pageEncoding="Big5"%>

For standalone applications, you may need to use the "-encoding" flag of the "javac" compiler to ensure the compiler understands your encoding.

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.