Why Chart FX?

Besides a powerful charting engine supporting the most complete collection of chart types, you may also want to consider Chart FX for its following attributes:

Multiplatform

Chart FX is the only charting and data visualization product capable of delivering native components for the most popular development and IT platforms, including Java, .NET, WPF, COM (ASP & ActiveX), Silverlight, SharePoint, PowerShell and SQL Server. Chart FX shares the same charting engine and API across all these platforms allowing developers to easily migrate their applications without the need to retrain or sacrifice the look and feel of the final product. This multiplatform capability is important considering the diverse and heterogeneous nature of IT infrastructures in the modern enterprise.

Extensibility

While some charting solutions are monolithic, slow and unreliable, Chart FX features a powerful extensibility mechanism. These Chart FX Extensions can be stitched together, allowing developers to quickly adapt to data sources enabling organizations to quickly and economically have access to specialized solutions that meet unique business needs. Chart FX Extensions are entire products targeting specific functionality while meeting the needs of specific markets. For example, adding interactive maps or vector images to your applications is as easy as integrating Chart FX Maps. Please visit the Extensions section in this manual or our online web site at: http://www.softwarefx.com/extensions/ for more detailed information.

End User Experience

Although Chart FX is a development product, it provides many runtime and end user features as well. The Chart FX end user interface significantly increases end users ability to analyze data. For example, end users can access most Chart FX functionality by clicking chart elements or using Toolbars and menus on demand. Also, through royalty free runtime components your users can export or reuse charts in most popular productivity applications, such as Microsoft Office.

Scalability & Performance

Integrating a charting solution to your application or web server could pose crucial server performance, scalability and security issues. Actually, many developers don’t become conscious of this until they do real-life stress testing and unveil serious performance and scalability issues that may jeopardize a successful or timely deployment of the final application. You will learn, Chart FX has been designed to work in intricate server architectures and you can expect a substantial increase in your Web server's throughput, commonly measured in requests per second and avoid security issues associated with generating and storing server side charts.

Elegant and professional presentation layer

Many vendors have focused on using the OS drawing capabilities to "beautify" or "animate" the charts, in most cases these drawing abuses not only have serious implications in server performance and scalability but also result in chart caricatures or mockeries that make your application look amateurish and provide little or no additional analysis capabilities to end users. Instead, Chart FX offers developers the ability to quickly and easily integrate impressive charts into their applications while retaining blazing speed and performance, making Chart FX the perfect data visualization solution for your application.

Seamless integration and Object-oriented API

Chart FX seamlessly integrates to the most popular development tools like Microsoft’s Visual Studio .NET, Visual Basic, Borland Delphi, NetBeans IDE and Eclipse, among others. Additionally, The Chart FX API is very powerful and intuitive, making it easier and more accessible to create and maintain applications

Unparallel Technical Support

When in need you can quickly search our integrated and centralized Resource Center or Support Site (http://support.softwarefx.com) for tutorials, samples and articles.

@2009 Software FX, Inc. All Rights Reserved. Grid FX and Chart FX are registered trademarks of Software FX, Inc.
All other names are trademarks or registered trademarks of their respective owners.


Getting Started with Chart FX 7 for Java Desktop

Requirements

Chart FX 7 for Java Desktop requires J2EE or J2SE 1.5 or higher.

Compatibility List

Chart FX 7 for Java Desktop will run on any Java VM running Java 1.5 or higher. This product is designed for Java applications running on desktops (client), not on Java servers.

Chart FX 7 for Java Desktop Installation

Installing Chart FX 7 for Java Desktop is easy. Simply run the installer and follow the on screen guide. After selecting an installation folder, all the necessary JAR files as well as some sample applications will be copied to your machine. A development license will also be created allowing you to develop and test with Chart FX before release. Additionally, the installation includes all the necessary resources for deployment of the application.

The Chart FX 7 for Java Desktop Samples

To help users get started with Chart FX 7 for Java Desktop, the installation package includes a collection of fully functional sample applications. The samples provided were created for both the NetBeans IDE and some of the most popular designer plugins for the Eclipse platform. Refer to

The Chart FX 7 for Java Desktop Samples section later in this Quick Start Guide for additional information.


Using Chart FX in Eclipse

You can add and configure your charts in eclipse by either working with the API through code or by manipulating the chart visually in your designer of choice.

  • Start by creating a new Java Project in Eclipse.

  • Then, from the toolbar, add a new Visual Class to the project.

  • Configure your Visual Class and click Finish.

  • Now that we have a form, we want to add a chart to it. To do that, right click the project name on the Package tab and select Build Path -> Add Library.

  • From the Add Library dialog box, select User Library and click Next.

  • Click the User Libraries… button.

  • Create a new user Library. Name it "ChartFX". Add all Chart FX jar files located in your installation folder.

  • Click OK to exit the User Libraries dialog and Finish to exit the Add Library dialog.
  • With Chart FX’s library now in your project, click Choose Bean in your Palette. Select Chart from the com.softwarefx.chartfx.desktop package.

  • Now click on your JFrame, name your object and click OK.

  • NOTE: If you are using WindowBuilder, the chart icon can be placed right on your palette. Just right click your Palette and go to Palette Manager. Click Add Category… and name it Chart FX. Then click Add Entry… and add Chart from the com.softwarefx.chartfx.desktop package.


Using Chart FX in NetBeans IDE 6.x

You can add and configure your charts in NetBeans by either working with the API through code or by manipulating the chart visually in the designer (matisse).Although this step-by-step guide was written specifically for NetBeans 6.X, the process for NetBeans 5.X is very similar.

  • Start by creating a new Java Desktop Application project in NetBeans.

  • After the project has been created, we need to add the Chart FX for Java Desktop jar files to it. We do so by right clicking on Libraries and selecting Add Library.

  • In the Add Library dialog, click on create.

  • For "Library Name", type ChartFX. For "Library Type", choose Class Libraries.

  • There are five .jar files inside the Libraries folder, located inside the installation folder. Add those .jar files to the library by clicking on "Add JAR/Folder" and selecting all the files.

  • Now that the library is added, we need to add the Chart to the Palette, for easy access. To do so, right click on the Palette and select "Palette Manager".

  • Add a new category by clicking "New Category…". Name it Chart FX. Add the ChartFX library to your new category by clicking "Add from Library…".

  • From the available libraries, select the newly created ChartFX library. Click Next.

  • From the available components, select Chart. Click Next.

  • From the palette categories, select the newly created Chart FX. Click Finish.

  • With a Chart now on your Palette, simply drag and drop one to your JPanel.


Licensing

Chart FX 7 for Java Desktop Licensing

Chart FX7 for Java Desktop is licensed on a per-developer basis and is royalty free for redistribution within the terms of the License Agreement. In other words, you will simply need to obtain a license for each development machine working with Chart FX and no additional licenses or deployment fees will be required for redistribution.

For a better idea of the licenses you will need when working with Chart FX 7 for Java desktop, please read below for some common licensing examples.

Licensing Example 1

Scenario: 1 developer working on 1 application.

Required Products:Only one license for development will be required. The recommended purchase would be:

1 Chart FX 7 for Java Desktop

Licensing Example 2

Scenario: 3 developers working on 2 different applications. All 3 developers will be using Chart FX.

Required Products:Each developer will need his/her own development license. The recommended purchase in this case would be the following:

1 Chart FX 7 for Java Desktop 2 Chart FX 7 for Java Desktop Additional Developer Licenses

Licensing Example 3

Scenario: 5 Developers working on 1 application, which will be packaged for redistribution to several of your own corporate customers.

Required Products:Each developer will need his/her own development license. The recommended purchase in this case would be the following:

1 Chart FX 7 for Java Desktop4 Chart FX 7 for Java Desktop Additional Developer Licenses


The Chart FX 7 for Java Desktop Samples

Using the Chart FX 7 for Java Desktop Samples

Your Chart FX 7 for Java installation provides a vast collection of sample applications showcasing the most popular features of Chart FX. To reach a broader range of users, these projects were created in Netbeans, Eclipse’s VisualEditor and Eclipse’s WindowBuilder. These applications are all located inside the Samples directory on your installation folder.

In NetBeans, just go to File -> Open Project and locate the desired project inside the samples folder.

In Eclipse, create a new Java Project, give it your own project name and in the Contents pane select "Create project from existing source". Then select the desired project inside the samples folder.


Technical Support

In case you need assistance while working with the Chart FX libraries, we provide you with three different resources to help you get the most out of the component:

Technical Support

If you have purchased technical support or if you are currently evaluating Chart FX, you can contact our technical Support team at support@softwarefx.com. Our friendly and knowledgeable staff of experts will be happy to guide you through any issues or help you with any questions. When contacting support, please make sure to include your serial number or support account number along with screenshots or code samples that better illustrate the reported issue or question.

The Chart FX for Java Tech support site

The Chart FX 7 for Java Desktop support website at HYPERLINK "http://support.softwarefx.com/ProductBase.aspx?Product=CfxJava70Desk"http://support.softwarefx.com/ProductBase.aspx?Product=CfxJava70Desk provides developers with technical demos, articles, sample applications and many other resources.

Please make sure to visit the support site periodically for updates on featured sample applications, service pack releases and new articles.

The Software FX Community Forums

The forums are a great way to provide and receive feedback to and from the Software FX Development team and the Chart FX community. You can access the Software FX Community at:

http://community.softwarefx.com


Overview

When you install Chart FX 7 for Java Desktop, your serial number is activated and the license information is saved locally in your system. In a development machine, Chart FX will look for this license information in order to create the charts. However, the application itself will not hold any license information by default, thus causing the charts to show an Invalid license message when deployed to systems with no Chart FX installation.

For this reason, the installation is equipped with a DeploymentAssistant application that will let you obtain a license that can be embedded in your code. Please consult the "Deployment Procedure" article later in this section for detailed instructions.

Note:

The DeploymentAssistant application is only provided with release versions of the product. If you need to test deployment while using the trial version of Chart FX, please contact support@softwarefx.com for assistance.


Deployment Procedure

In order to successfully deploy Chart FX with your application, you will need to use the static SetLicenseString call of the Chart class. Please follow these steps to obtain the correct license string:

  • Find the DeploymentAssistant application, typically located in the "Deployment" folder of your Chart FX 7 for Java Desktop installation directory. Run it by using the following command:

Java -jar DeploymentAssistant

  • Please read all Licensing considerations carefully and follow instructions to proceed. At the end, you will obtain a text box with the correct licensing call f your application. Copy the string as is.
  • Paste the code you received in step two and place it in inside your application. Please make sure the call is placed only once and before the first instance of a Chart is created.
  • You should now be able to build and redistribute your application without problems.


Bar

Bar Charts

Bar charts are the most common type of business chart and are especially useful for comparative analysis. You can use a bar chart to illustrate comparisons among individual items. Bar charts are also useful for comparing classes or groups of data. In bar charts, a class or group can have a single category (single series) of data, or they can be broken down further into multiple categories (multiple series) for greater depth of analysis.

Passing data to a bar chart is as simple as passing one or more data series and tags or labels accompanying each data series. These labels will be displayed in the categorical or time axis (X Axis).

When more than one series is passed to the chart, Chart FX will display, by default, the bars side by side in a 2D style. For example, if you want to represent projected vs. actual revenue for the different months of the year, the bar chart will be the best chart type to use. The following figure depicts several bar charts:

Bar and Column charts

Some charting vendors refer to column and bar terms in different ways. As a rule of thumb, a column chart is a chart displaying vertical bars while the bar chart term is commonly used for horizontal bars. However, to some people this difference is not decipherable. For this reason, Chart FX utilizes the term Bar chart in the same way for both vertical and horizontal displays.

To make a bar chart horizontal, please use the Gantt chart type. For additional information please check the Chart FX API in your electronic documentation.

Changing the bars appearance

Besides rectangular bars, Chart FX allows you to change the marker to cylinders, cones and floating cubes. These markers support both 2D and 3D effects.

The following figures display some of these special bar chart types:

Bar chart with initial values

Most Bar charts display bars commencing at the axis minimum point and extending across the chart area all the way to the value that has been given to the bar. In some cases, bars are required to have an initial value and an ending value, which forces the bar to draw differently. For example, a Gantt chart which allows a graphical display of activities in a project, each activity (bar) has a commencing and an ending date; this forces the bar to be displayed with an initial value as depicted in the figure to your right.

The trick in these chart types is simply to pass an additional initial value to the chart using the "SetYFrom" method. You can also assign a particular field in your dataset to represent initial values for the chart you are creating. For additional information, please refer to the "Passing Data" chapter in this manual or any of the samples located in the Chart FX Resource Center.

Note:

Initial values can be used on both horizontal and vertical bar charts.


Stacked

Another way to represent bar charts is through stacking. In this way, a single bar on the chart can show data for more than one category of data. Stacked bar charts show the relationship of parts to the whole. Stacking techniques differ depending on whether you are representing divisions within data label categories or stacking two separate numeric categories.

Stacked bar charts offer similar complexity to clustered bar charts by adding together component value items within chart bars or areas. By stacking items and assigning a different color to each item, you can effectively display trends among comparable or related items, or visually emphasize a sum of several indicators.

To create a Stacked bar chart, you need more than one series. Each series contains the additive value rendered as an additional segment along the length of the bar. Additionally, Chart FX lets you stack the bar charts vertically or horizontally as well as in groups of stacked bars as depicted in the following figure:


3D Charts

3D Bar Charts

Chart FX allows you to set a 3D look to your bar charts. Sometimes these charts are harder to read and analyze but present a nicer look for presentation purposes. Chart FX supports two types of 3D effects: Isometric and Oblique projections.

In Isometric 3D View, charts appear in the chart space as 3D objects with depth. In contrast, the Oblique 3D view allows you to set rotation angles and a perspective value for your charts. The following two pictures depict an Isometric and Oblique projections, respectively:

Note:

That does not mean that you are plotting three dimensions of data or using three dimensions of space to represent data (XYZ Coordinates). Chart FX will always use two dimensional data. In other words, 3D is simply a visual effect that can be switched off. Cluster normally applies to 3D bar charts and this effect allows you to change your chart perspective so that the Z-axis data extended in the third dimension is shown as clusters displayed in the foreground. This charting option is useful when Z-axis bars are hard to distinguish in standard bar formats. To create a clustered bar chart, you need more than one series. Each series occupies its own position along the Z-axis data.

Clustered charts

Cluster normally applies to 3D bar charts and this effect allows you to change your chart perspective so that the Z-axis data extended in the third dimension is shown as clusters displayed in the foreground. This charting option is useful when Z-axis bars are hard to distinguish in standard bar formats. To create a clustered bar chart, you need more than one series. Each series occupies its own position along the Z-axis data. The following picture depicts a clustered bar chart:

In 2D bar charts, you can use clustered bar charts to juxtapose categories in one label item. For example, use clustered bars to compare stores of different types. Alternatively, cluster bars can be used to compare two different value items, such as Amount of Sales and Units Sold.


Area

Area Charts

Area charts are essentially bar charts with the discontinuous breaks removed along the horizontal axis. Data is not broken into discrete bars but appears in a continuous ebb and flow as defined against the Y axis. Consequently, area charts are particularly useful for emphasizing the magnitude of change over time. In addition, area charts can be used for the same purposes as bar charts.

Because area charts do not break data along the horizontal axis, they are most useful for charting three dimensions of data. The Z-Categories pane should be used to either project data into a third spatial dimension, or to stack two categories of data in a stacked area chart.

Most of the settings introduced and described in the Bar charts section before (Stacked, Clustered, etc) also apply to Area charts. The following table presents different variations of Area charts supported by Chart FX:


Lines and Stripes

Lines and Stripes Charts

Line charts show trends in data at equal intervals and are effective for comparing highs and lows in a continuum. You can create multiple lines by adding additional data series to the chart. In a 2D line chart additional lines will be drawn in the main chart area and. In the case of 3D line charts, lines could be displayed at the same level or clustered in the Z axis.

Line charts have one advantage over bar charts. They do not allow one set of data to obstruct the representation of another. Since lines are thin compared to bars, the data displayed in the front does not block out the data behind. As a result, data that is not easily represented in bar or area charts work well in line charts. Many more dimensions of data can be superimposed without impairing the chart’s effectiveness. Other common uses of line charts include:

  • Display long data rows
  • Interpolating between data points
  • Extrapolating beyond known data values (forecast)
  • Comparing different graphs
  • Finding and comparing trends (changes over time)
  • Recognizing correlations and co-variations between variables
  • If the X axis requires an interval scale
  • Displaying interactions over two levels on the X axis
  • When convention defines meaningful patterns (e.g. a zigzag line)

Most line charts are accompanied by a timeline or date based X axis. For additional information on how to pass dates to the chart’s x or categorical axis, please refer to the Axes section in this manual.

Passing data to a line chart is processed in the same way as Bar charts. Additionally, Chart FX allows you to control many line settings such as width, color and marker styles. The following table presents different variations of Line charts supported by Chart FX:

Note:

Most line charts are accompanied by a timeline or date based X axis. For additional information on how to pass dates to the chart’s x or categorical axis, please refer to the "Axes" section in this manual.

Marker shapes and styles

In most charts, end users recognize different data series by their color. In line charts, however, the color difference is barely visible, especially in printed charts. For this reason, many developers choose to recognize each data set with visible markers in each of the connecting points between the lines. Chart FX provides an extensive API (PointAttributes object) that allows developers to customize any setting related to the line chart markers. Including but not limited to: shape, color, size, label and the frequency of display in the chart. The following chart depicts a line chart with customized chart markers.:

Curve charts

Instead of a line, you can choose to use curve charts. When used, curve charts will use a spline algorithm to draw a curve between the points in the chart, rather than connecting the points directly with a straight line. Just as lines, curves also exposed an extensive API to configure the curve color width and markers.

Step lines

Rather than connecting the points with a straight line, these charts display one set of data as steps in a line. These charts are used to illustrate trends between more than two members of nominal or ordinal scales. The following picture depicts a step line chart.

Ribbon (Strip) charts

When a line chart is displayed in 3D, most software refers to these charts as Ribbon or Strip charts. For simplicity purposes, Chart FX refers to these as line charts as well. The 3D flag attribute setting is the only notable difference. The following is an example of some of the most common line charts displayed as a Ribbon chart:

Most of the 3D settings mentioned in the Bar chart section (Perspective, Rotation, etc) also apply to 3D Lines or Ribbon charts.

Note:

Lines can also be combined with other chart types, such as bars and area charts, to achieve combination charts. For more information on Combination charts please refer to subsequent pages in this chapter.


Pie and Doughnut

Pie and Doughnut Charts

Pie charts are used to show classes or groups of data in proportion to the whole data set. The entire pie represents all the data, while each slice represents a different class or group within the whole. These chart types are used for:

  • Conveying approximate proportional relationships (relative amounts) at a point in time
  • Comparing part of a whole at a given point in time
  • Exploded: emphasizing a small proportion of parts (exploding pie)

Caution! Certain limitations and restrictions exist when using pie charts. For example, Pie charts cannot represent values beyond 100%. Also, pie charts should not be used for exact comparisons of values or if proportions vary greatly, because estimating angles is difficult for people. Additionally, Pie charts are only suited for presenting a few percentage values; therefore they are not good to represent large sets of data as a big number of slices in the chart will not be easy to read. Also do not use multiple pies to compare corresponding parts; instead you may use a grouped bar chart to do comparative analysis.

Because pie charts do not display a categorical or x axis, they process data differently than other chart types in Chart FX. Normally, you will want to create a pie chart by passing a single data series and accompanying each value in the data series with a label that could be displayed on each resulting slice.

If more than one data series is passed to the chart, Chart FX will create as many pies as series are in the data set resulting in multiple pie charts in the chart area.

Doughnut charts

Like a pie chart, a doughnut chart shows the relationship of parts to a whole. The following table shows different variations (2D and 3D) of a doughnut chart:

Exploding pie charts

A common practice to highlight certain data points (the highest or the lowest) in a pie or a doughnut chart is to separate one or more slices from the rest of the chart. This effect can be easily achieved using the SeparateSlice property available in the PointAttributes object.

Stacked Pie (Concentric pie charts)

When a pie chart contains more than one data series, you can achieve concentric pies by turning on the Stacked property in the chart. This will simply instruct Chart FX to display a single chart with concentric pies, as depicted in the following figure:

chart1.getData().setSeries(2);
chart1.getData().setPoints(3);
chart1.setGallery(Gallery.DOUGHNUT);
Pie pie;
pie = ((Pie)chart1.getGalleryAttributes());
pie.setStacked(true);
pie.setDoughnutThickness(10);
SeriesAttributes series;
series = chart1.getSeries().get(0);
series.setGallery(Gallery.DOUGHNUT);
series.setVolume((short)100);
/*  Make first series (Outside Doughnut) bigger */
series = chart1.getSeries().get(1);
series.setGallery(Gallery.PIE);
series.setVolume((short)80);

Pyramid charts

Pyramid charts are used to show hierarchical lists. You can use them to show business goals or customer requirements. Like a pie chart, a pyramid chart does not display an x axis. Several pyramid charts are presented in the following table:

Note:

Since the most important item is usually placed at the top of the pyramid, it is important to mention that the first item in the data array will be displayed at the top of the pyramid. You must make sure you order your data array.


Scatter Plots (XY Charts)

Scatter Plots (also called scatter diagrams or XY charts) are used to investigate the possible relationship between two variables that both relate to the same "event."

Each point in a XY Plot is defined by two coordinates (X, Y). This results in several important aspects regarding XY charts:

When passing data to a scatter plot you must have two sets of numbers to define a point in the chart. If you are passing data using the API, you must use the Value as well as the XValue properties. If passing data from a database, you must use the Datatype property to indicate which field will represent the X coordinate and which field will represent the Y coordinate of each point in the chart.

XY charts do not have a categorical axis. In other words, both the X and Y axis become a numerical axis and, therefore, you can set any axes values such as minimum, maximum, log base and other settings related to a numerical axis.

In most cases, scatter or XY Plots are created with point markers with no connecting lines. Nevertheless, Chart FX supports scatter plots (that is, charts which points are defined by two coordinates) in many chart types like Lines, Curves, Area, Step Lines, Surface, Bubble and Contour.

The following table highlights some XY Plots.

Marker shapes and styles

Like line charts, scatter plots use point markers as an important way to differentiate data series in the chart. Scatter plots support all chart marker properties described in the Lines chart section of this manual.

For additional information or samples on scatter or XY plots, please refer to the Chart FX Resource Center.


Financial

Financial Charts

Compared to traditional bar charts, many traders consider hi-lo-close and candlestick charts more visually appealing and easier to interpret. Financial charts provide an easy-to-decipher picture of price action. Immediately a trader can see and compare the relationship between the open and close as well as the high and low. The relationship between the open and close is considered vital information and forms the essence of these charts.

With Chart FX, you can create Hi-Lo-Close, Open-Hi-Lo-Close and candlestick charts. Passing data to these charts is essentially the same process as passing data to any chart type in Chart FX. You must, however, make sure the series are passed in a certain order so Chart FX can determine which data series represents the Open, Hi, Lo and Close values. For more information on passing data to a financial chart, please refer to the Passing Data section later in this Programmer’s Guide.


Bubble

Bubble Charts

Bubble charts are charts that display circles of different sizes representing a condition. Bubble charts are frequently used in market and product comparison studies

In a way, bubble charts are very similar to scatter charts in that each bubble position is defined by two coordinates. Additionally, the size of the circle at each point reflects an additional dimension of the chart. Because of this, Bubble charts allow three-variable comparisons allowing for easy visualization of complex interdependencies that are not apparent in two-variable charts.

The following table displays some Chart FX bubble charts:

Chart FX uses two series of data to create the most elementary bubble chart. By default, the first series passed to the chart is used for the actual point values (Y Values), while the second series is used to control the size of the bubble marker.

There are several factors that determine the size of the bubble; one being the actual value for the second series, and second being the axis scale which that second series is assigned. This feature actually gives the developer more control over the size of the bubble by providing the possibility of assigning that series to a Secondary Y axis. This scale can me modified independent from the primary Y axis used for the chart values, thus preserving the original display of the axis range. A bubble will reach maximum size when its value is equal to the Y-Axis Max.

Additionally, bubbles can be colored and label independently. 2D and 3D bubble charts are also supported.


Radar and Polar

Radar and Polar Charts

Radar charts are useful when you want to look at several different factors all related to one item. Radar charts have multiple axes along which data can be plotted. In a radar chart, a point close to the center on any axis indicates a low value. A point near the edge is a high value. When interpreting a radar chart, end users will check each axis as well as the overall shape.

The following table highlights a series of radar charts:

The following table highlights a series of polar charts:

Marker shapes and styles

Like line charts, radar charts use lines and markers as in the chart area. Radar charts also support all chart marker and line properties described in the Lines chart section of this manual.


Surface and Contour

Surface and contour plots

A surface plot is a 3D chart displaying data plotted over a surface area. A contour chart is normally a 2D representation of a surface chart. Surface and contour charts are suitable for comparing two groups of data combinations.

The following table depicts some surface and contour charts:

Passing data to a surface chart

In a surface chart, the number of points determines the width of the chart while the number of series determines the depth of the chart. For example, if we want to display a 3D surface chart with 10 Points and 10 Points per series with all values set to zero, it would look like:

As depicted in the figure, you must now locate which data points you want to change in order for the chart to start looking like a surface plot. For example, if we change the value of the points and series highlighted in the figure, the resulting chart will look like the following:

Setting colors to a Surface chart

One of the most important settings in a surface plot is the level of detail that the chart contains. Displaying different colors according to the value of each data point increases the detail of the chart. The color will gradually change from the Color of the first series to its AlternateColor.

Notice although values have been set, the level of detail shown in the chart may not be enough for the scale selected for the Y Axis (-20, 20). We need the surface plot to show the significance of the value using an additional method such as color.

To achieve this, simply change the step of the primary Y Axis to achieve the level of detail you need in the surface plot. For example, in the figure shown above the step has been set to 10, not allowing the surface to display enough variance. However, changing the Step to 2 will allow greater detail to be applied.

An alternative way to do this is by using the axis MinorStep property to get a gradual change in color without modifying axis Step as shown below:


Pareto

Pareto Charts

Vilfredo Pareto, a turn-of-the-century Italian economist, studied the distributions of wealth in different countries, concluding that a fairly consistent minority - about 20% - of people controlled the large majority - about 80% - of a society's wealth. This same distribution has been observed in other areas and has been termed the Pareto effect.

The Pareto effect even operates in quality improvement: 80% of problems usually stem from 20% of the causes. Pareto charts are used to display the Pareto principle in action, arranging data so the few vital factors that are causing most of the problems reveal themselves. Concentrating improvement efforts on these few will have a greater impact and be more cost-effective than undirected efforts.

Pareto charts display a bar chart with values in the primary Y axis and a line chart automatically calculated and displayed by Chart FX representing the cumulative percentage at each of the bars. Normally, the values are sorted so the 80% - 20% effect could be easily deciphered.

The following picture depicts a Pareto chart:

Note:

Chart FX DOES NOT sort the data for you. Therefore, you must sort the data before passing it to a Pareto chart.


Combination

Combination Charts

Combination charts combine some of the strengths of all chart types available in Chart FX. For example, Solid bars can be used for the most important data against which other dimensions are represented in lines. In this way, emphasis is given to a portion of data based on its importance. A combination chart is especially useful for comparing two numeric values, such as amount and units of sales.

To create a combination chart, you must have a multiple series chart and then set the gallery type for each individual series in the chart using the Series.Gallery property. This will set each gallery independently. The following table presents some of the most common combination charts.

Chart FX supports Combination charts in 2D as well as 3D modes.

The following table presents some samples of combination charts:


Overview

The most basic method of passing data to a chart using Chart FX for Java is to utilize the built-in API. The Chart FX for Java API provides properties and methods to load and manipulate data into a chart. Passing data to your charts using the API may be the most basic method, however, one of the features of Chart FX for Java is the ability to read or pass data from many sources. These sources include databases, text files, XML, arrays, collections, and many others.

In Chart FX, there is no need to loop through data points to populate the charts. If you have a previously filled data array, just pass it to Chart FX and have the chart filled with data with as little as one line of code.

This chapter will explain how Chart FX handles the data passed to it and how to populate your charts from the most common data sources. These sources include:

  • API
  • Database
  • Arrays
  • Text
  • XML
  • Field maps


Series and Points

In order to render a chart, Chart FX must have the data organized in a meaningful way.

Providing data for simple charts is as simple as having a basic set of values to plot and using the Chart’s Data collection to specify values. For example, a bar chart representing the total yes/no votes of a poll is a single series with two values as shown below.

int nSeries;
nSeries = 1;
int nPoints;
nPoints = 2;
chart1.setGallery(Gallery.BAR);
chart1.getData().setSeries(nSeries);
chart1.getData().setPoints(nPoints);
chart1.getData().set(0, 0, ((double)45));
chart1.getData().set(0, 1, ((double)75));

As shown above, we passed Y values for two points in the chart by using the data collection. Similarly, if we were to work with an XY chart in which each point has a coordinate on each axis, we would need to specify the value of the X coordinate also:

chart1.getData().set(0, 0, 45);
chart1.getData().getX().set(0, 0, 12);
chart1.getData().set(0, 1, 75);
chart1.getData().getX().set(0, 1, 57);

The most basic chart contains one series with any number of points. This can be translated to a bar chart, with one bar for each point. Many times however, that data is much more complex and multidimensional. For example, the bar chart can be the sales for the current year with the sales total for each of the 12 months. However in another situation you may have sales data for last year as well translating into a secondary series of 12 points each.

Unlike the simple bar chart example above, some gallery types require additional data for rendering. For example, a bubble chart requires an additional series identifying the size of the bubble. Similarly, the numerous other galleries utilize the series and points as required. By introducing series, Chart FX is able to capture the necessary data to produce many additional charts taking advantage of multidimensional data.

Additionally, a series can be distinguished by modifying the properties such as color, etc. To do this you would simply reference the index of the series you wish to modify using the indexer of the series collection.

chart1.getData().setSeries(2);
chart1.getData().setPoints(5);
chart1.getSeries().get(0).setColor(java.awt.Color.GREEN);

Reordering Series

Chart FX allows series reordering. In some cases, depending on the gallery type being used, a series may be hidden by the values present in another series. Although there are multiple solutions to this scenario such as transparency or multiple panes, the better solution may be simply a reordering of the series.

CAUTION: Some charts require multiple series of data and require those series to be in the correct order. Reordering series in such cases may produce unexpected results.

There are various methods for reordering the series in your chart such as the commonly seen SendToBack() and BringToFront() methods:

chart1.getSeries().get(1).bringToFront();//moves the second series to the front

Additionally, you can reorder the series by using the Remove() and Insert() methods. When removing a series, the remaining series to the right (or series with a higher index number than the one removed) are shifted to the left and have their index number decreased accordingly. Below for example, we demonstrate how you can swap two series utilizing this method.

//this code swaps the fourth series with the third series
SeriesAttributes series3 = chart1.getSeries().get(2);
chart1.getSeries().remove(chart1.getSeries().get(2));
chart1.getSeries().insert(3,series3);

Occasionally, you may need to reset the order of the series to their original sequence. You may do this at any time by calling the resetOrder() method as shown:

chart1.getSeries().resetOrder();

Hidden Points

Chart FX has the ability to create hidden points in the chart. Although Chart FX forces the same amount of points per series, you may specify hidden points to create the illusion of some invisible points in the chart. Assigning the Hidden Chart constant:

chart1.getData().set(0,0,Chart.HIDDEN);

All you need to do to create a hidden point is to assign the Chart object Hidden constant as a value to a particular point:

chart1.getData().setSeries(1);
chart1.getData().setPoints(5);
chart1.getData().set(0, 0, ((double)30));
chart1.getData().set(0, 1, ((double)45));
chart1.getData().set(0, 2, Chart.HIDDEN);
chart1.getData().set(0, 3, ((double)60));
chart1.getData().set(0, 4, ((double)50));

Changing Existing Values in the Chart

If you've already populated the chart and all you want to do is change an isolated value; you may do so without repopulating all the data again. As an example, the API calls necessary to make such a change are as follows:

chart1.getData.set[seriesIndex,pointIndex] = value;

Axes Rescaling

When data is loaded to the chart, by default, Chart FX automatically adjusts the axes Min and Max to guarantee every value is inside the range. This behavior is controlled by the axes’ AutoScale property. However, if a new set of values is loaded on the same chart, Chart FX will adjust the Min and Max again, only increasing when necessary but never decreasing them, which can affect the chart visualization. To force the Min and Max to be recalculated based on the new set of data, call the axes ResetScale method before loading the new data.

chart1.getAxisX.resetScale();
chart1.getAxisY.resetScale();


Setting Legends

Setting Chart Legends

A legend is a visual guide to show the viewer additional information regarding the values being displayed without convoluting the chart itself with additional overlaid data. Additionally, legends are particularly useful to improve chart readability for charts like Pie, which have no axes but point labels are still needed. Depending on the chart, legends typically are associated with the series or the values of the chart. Additionally, there may be instances where neither a Series-based legend nor a Point-based legend applies. In such scenarios, there is also the option for a user defined legend.

The LegendBox for values is always shown docked to a margin (right margin by default). Additionally, the setAlignment method can be used to align the LegendBox within the margin. The Chart object getLegendBox method is used to set position and style attributes directly to the legend box.

chart1.getLegendBox().setVisible(true);
chart1.getLegendBox().setContentLayout(ContentLayout.CENTER);
chart1.getLegendBox().setDock(DockArea.BOTTOM);

Series Legend

In a multiple series chart, it is standard practice to add a legend box containing descriptions of the series displayed. The text to be shown for each series can be customized by using the setText method of each series:

chart1.getData().setSeries(2);
chart1.getLegendBox().setVisible(true);
chart1.getLegendBox().setContentLayout(ContentLayout.NEAR);
chart1.getLegendBox().setDock(DockArea.BOTTOM);
chart1.getSeries().get(0).setText("Product A");
chart1.getSeries().get(1).setText("Product B");

Value Legend

In some scenarios, like when using Pie Charts, it is necessary to show legends for the points instead of the series. By default Chart FX will automatically detect when a per-point legendbox is required and will show a label for each value. In order to provide any desired meaning to the points, you need to use the getLabels method of the Data object to associate a string for each value point. For example, the following Pie chart is created with the following API calls:

chart1.getData().setSeries(1);
chart1.getData().setPoints(3);
chart1.getData().set(0, 0, ((double)30));
chart1.getData().set(0, 1, ((double)50));
chart1.getData().set(0, 2, ((double)20));
chart1.getData().getLabels().set((short)0, "Internet Explorer");
chart1.getData().getLabels().set((short)1, "Netscape");
chart1.getData().getLabels().set((short)2, "Other");
chart1.setGallery(Gallery.PIE);


Passing Data Using Databases

Overview

In most cases, you will want to populate charts with data coming from a database table or query. Chart FX for Java supports data binding through JDBC.

JDBC offers you a basic way to work with data: using a ResultSet, where you create an in-memory store of the records you want to work with.

It is important to note, development strategies used for database access vary greatly from application to application. Furthermore, JDBC can be used to integrate data from complex application tiers. Therefore, this section is limited to describe basic techniques on how Chart FX 7 for Java Desktop uses JDBC and its JDBCDataProvider to populate charts in JSP applications.

JDBC Resultset

When you execute SELECT statements against a JDBC connection, you get in return a ResultSet that contains all the records selected. To read the results, we provide a JDBCDataProvider, which works like a read-only, forward-only cursor, to which you can bind charts. This is a useful strategy for reducing memory usage and loading read-only data very quickly.

The following Java code creates a ResultSet and uses a JDBCDataProvider to populate the charts:

String url="jdbc:jtds:sqlserver://dbserver:1433/NetSamples";
java.sql.ResultSet rs = null;
java.sql.Connection conn = null;
class.forName("net.sourceforge.jtds.jdbc.Driver");
conn = java.sql.DriverManager.getConnection(url,"webguest","");
String query = "SELECT * from SampleFinancial1";
java.sql.Statement stmt = conn.createStatement(java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE,
java.sql.ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery(query);
JDBCDataProvider provider = new JDBCDataProvider(rs);
chart1.getDataSourceSettings().setDataSource(provider);
conn.close();

Note:

The above example uses the jTDS JDBC driver from The jTDS Project as an example. Any JDBC driver may be used to load data into the JDBCDataProvider and Chart FX 7 for Java Desktop.

Chart FX Tabular Data Interpretation

Chart FX will apply default rules to construct the chart when it has been bound to a database. These rules pick the information from the result set of the query and assign legends and values to the chart according to the field type. This behavior allows the creation of a default chart that fits or closely resembles the chart you want to achieve.

The rules to construct a chart when bound to a database table are:

  • All numerical columns in the query will be plotted as different series and all string and/or date columns will be plotted as point or X-axis labels (joined by the '-' character).
  • Series Legends will be taken from the numerical field names.
  • All string and numerical fields specified in the SELECT statement will be plotted in the chart.

For example, if you have a database table containing the following fields:

and bind the chart to result set of the following SQL query:

        SELECT Month,Product1,Product2 FROM Sales

The resulting chart will contain 2 series (Product1 and Product2) and X-axis labels containing the name of the months available in the Month field.

To change the default data binding behavior, Chart FX exposes the Fields collection which allows you to specifically define how the fields returned by your query are mapped to series in the chart:

String url="jdbc:jtds:sqlserver://dbserver:1433/NetSamples";
java.sql.ResultSet rs = null;
java.sql.Connection conn = null;
class.forName("net.sourceforge.jtds.jdbc.Driver");
conn = java.sql.DriverManager.getConnection(url,"webguest","");
String query = "SELECT Date, High,Low,Closed from SampleFinancial1";
java.sql.Statement stmt = conn.createStatement(java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE, java.sql.ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery(query);
JDBCDataProvider provider = new JDBCDataProvider(rs);
chart1.getDataSourceSettings().getFields().add(new FieldMap("Date",FieldUsage.XVALUE));        chart1.getDataSourceSettings().getFields().add(new FieldMap("High", FieldUsage.VALUE));
chart1.getDataSourceSettings().getFields().add(new FieldMap("Low", FieldUsage.VALUE));
chart1.getDataSourceSettings().getFields().add(new FieldMap("Closed", FieldUsage.VALUE));
chart1.getDataSourceSettings().setDataSource(provider);


Passing Data Using XML

XML has proven to be a very dynamic and flexible means of data storage. Chart FX has been developed with this in mind and allows you to populate your charts with data directly from XML files.

The Load method is supported by the XmlDataProvider object. To use this feature, you must first create a new XmlDataProvider object, load the XML data either through one of the various Load methods, and finally assign it to the chart through the setDataSource method :

XmlDataProvider cfxXML = new XmlDataProvider();
cfxXML.load("d:\temp\myxml2.xml");
chart1.getDataSourceSettings().setDataSource(cfxXML);

When passing the data using the XML data provider, the data is passed as columns and rows, the same as with a table. The following demonstrates the format of a typical XML used to import and export data to and from Chart FX:

<?xml version="1.0"?>
<CHARTFX>
   <COLUMNS>
       <COLUMN NAME="Product" TYPE="String"/>
       <COLUMN NAME="Q1" TYPE="Integer" DESCRIPTION="1ST QTR"/>
       <COLUMN NAME="Q2" TYPE="Integer"/>
       <COLUMN NAME="Q3" TYPE="Integer"/>
       <COLUMN NAME="Q4" TYPE="Integer"/>
   </COLUMNS>
   <ROW Product="ChartFX 98" Q1="9200" Q2="7835" Q3="10245" Q4="8762"/>
   <ROW Product="ChartFX IE 3.5" Q1="14350" Q2="11233" Q3="16754" Q4="987"/>
   <ROW Product="ReportFX" Q1="12398" Q2="7654" Q3="5678" Q4="9087"/>
   <ROW Product="Image Toppings" Q1="8742" Q2="12358" Q3="14321" Q4="8702"/>
</CHARTFX>

Here, the definition for each column is enclosed in a COLUMNS node. The columns can optionally contain a DESCRIPTION attribute used to label the legend of the chart. If the attribute is omitted as in Q2 through Q4 above, the value of the NAME attribute is used for the legend.

Configuring Properties via XML

Chart FX makes extensive use of XML. Chart FX not only supports XML for importing data, but XML can also be used to manipulate visual attributes and formatting for your charts. The XML property files can be written to or read from an XML file by using the ImportChart and ExportChart methods.

chart1.importChart(FileFormat.XML, myFile);
chart1.exportChart(FileFormat.XML, myFile);

In the XML, Each property is an element, and properties for most sub objects (series, point, axis, etc.) are represented as sub elements. When customizing series or point attributes, the values are represented as XML properties within the SERIES element instead of as sub elements as shown in the XML file below.

<CHARTFX>
   <VOLUME>35</VOLUME>
   <TITLES>
      <TITLE><TEXT>My First Chart</TEXT></TITLE>
   </TITLES>
      <SERLEGBOXOBJ>
         <DOCKED>Left</DOCKED>
         <DRAWINGAREA>true</DRAWINGAREA>
         <FONT><NAME>Verdana</NAME></FONT>
         <ALIGNMENT>Center</ALIGNMENT>
      </SERLEGBOXOBJ>
   <SERLEGBOX>True</SERLEGBOX>
   <SERLEG>
      <LEGEND>Sales</LEGEND>
      <LEGEND>Projected</LEGEND>
   </SERLEG>
   <SERIES>
      <SERIES index="0">
         <BORDER>True</BORDER>
         <GALLERY>LINES</GALLERY>
      </SERIES>
      <SERIES index="1">
         <BORDER>True</BORDER>
         <GALLERY>Lines</GALLERY>
      </SERIES>
   </SERIES>
   <POINT>
      <POINT series="1" point="2">
         <COLOR>Red</COLOR>
         <MARKERSHAPE>Rect</MARKERSHAPE>
      </POINT>
   </POINT>
   <STRIPES>
      <STRIPE>
         <AXIS>0</AXIS>
         <TO>20</TO>
         <FROM>30</FROM>
      </STRIPE>
   </STRIPES>
</CHARTFX>


CrossTab Data Provider

Many of the charts require data to be properly formatted for Chart FX to generate the desired chart. With data typically coming from data sources such as databases, the data is usually formatted in tabular format as shown in this table.

Normally, developers would have to spend countless hours manipulating the data to generate the desired format. Chart FX solves this problem by providing the Crosstab data provider. With the Crosstab data provider, we can easily convert the above data to the following format for correct display within Chart FX.

The tabular formatted table when passed to Chart FX will generate the following chart:

In most cases, this is not the chart you prefer to generate. The ProductName field information is repeated for each row and in order to compare the quarter sales for various products in different quarters, you must match numbers physically distant from one another on the page. Additionally, it could be easily overlooked there are some quarters with no sales for a specific product. Using the Crosstab data provider, the original table can easily be reorganized to produce the revised table. When read in by Chart FX, the revised table will display the following chart - displaying the data more effectively.

The Crosstab Data Provider Functionality

There are two important aspects to effectively use the Crosstab Data Provider:

  • How the Crosstab Data Provider integrates with Chart FX.
  • How to configure Crosstab to convert tabular data to columnar data.

The Crosstab Data Provider's input must be in the form of a supported Chart FX data provider, such as an array, collection, text file, XML or database among others.

Configuring the Crosstab Data Provider to Convert Tabular Data to Columnar Data

Due to the multitude of possible scenarios, the Crosstab Data Provider needs to have rules for the conversion of tabular to columnar data. These rules define how each column in the tabular format is used. A column may be defined through any of the options provided ion the FieldUsage Enumeration used when defining field mappings : Column Heading, Row Heading, Value, IniValue or Not Used.

chart1.getDataSourceSettings().getFields().add(new FieldMap("year",FieldUsage.ROW_HEADING));
chart1.getDataSourceSettings().getFields().add(new FieldMap("sales",FieldUsage.COLUMN_HEADING));

Column Heading: When data in a column of the tabular data is used as a column heading, each unique item appearing in a column will form a column in the resulting columnar format. There can only be one Column Heading defined; if more than one column heading is defined the first one defined will be used.

Row Heading: When a column or set of columns of the tabular data is used as a Row Heading, each unique item appears in the columns specified will form a row in the resulting columnar format. The number of row headings can be defined is unlimited.

If more than one column is specified as a row heading, the Crosstab Data Provider will concatenate the values into a single string in left-to-right order. The SetSeparator method can be used to define a string separating each part of the row heading. By default, there is no separator.

IniValue: When a column of the tabular data is defined as IniValue, the Crosstab Data Provider will use its content as the initial value for data points to achieve floating bars and area charts.

Value: When a column of the tabular data is defined as Value, the Crosstab Data Provider will use its content as the value of the element in the matrix, at the intersection of a specific row and column. Only one value column can be defined; if more than one value is defined, the first one defined will be used.

Not Used: When a column of the tabular format is defined as Not Used, the Crosstab Data Provider will ignore the column. By default, all the columns are not used.

Note: The RowHeading records passed to the CrosstabDataProvider need to be ordered consecutively. You must ensure the RowHeading values are consecutive, otherwise the chart will not understand which values to group together, displaying undesirable results.

Other Crosstab Data Provider Methods

setDataSource: The setDataSource method is used to instruct the Crosstab provider to retrieve the information from an external data provider. The configured external data provider must be configured to a valid data provider such as a TextProvider, XmlDataProvider, ListProvider, etc.

setDateFormat: The setDateFormat method is used to instruct Chart FX how to format the dates when a column specified as a Row Heading is a date. If no DateFormat is specified, the format will be set from the Culture property. By default, the Culture property is set to en-US.

setNullColumnHeading: The setNullColumnHeading method is used to instruct Chart FX to use the configured string value when a null column heading is encountered.

String url="jdbc:jtds:sqlserver://dbserver:1433/NetSamples";
java.sql.ResultSet rs = null;java.sql.Connection conn = null;
Class.forName("net.sourceforge.jtds.jdbc.Driver");
conn = java.sql.DriverManager.getConnection(url,"webguest","");
String query = "SELECT * from CTdata";
java.sql.Statement stmt = conn.createStatement(java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE, java.sql.ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery(query);
JDBCDataProvider provider = new JDBCDataProvider(rs);
conn.close();
CrosstabDataProvider CfxCT = new CrosstabDataProvider();
CfxCT.setDataSource(provider);
chart1.getDataSourceSettings().getFields().add(new FieldMap("quarter",FieldUsage.COLUMN_HEADING));

        chart1.getDataSourceSettings().getFields().add(new FieldMap("product",FieldUsage.ROW_HEADING));
chart1.getDataSourceSettings().getFields().add(new FieldMap("sales",FieldUsage.VALUE));
chart1.getDataSourceSettings().setDataSource(CfxCT);


Passing Data from Arrays

In many situations, the data is contained in a memory array. Although you can use the Chart FX 7 for Java Desktop API to loop through array elements, read and populate the chart, you can also do so in an easier way.

This feature is supported by the ListProvider class, and the chart's DataSource property, as follows:

int[] valArray = {12, 15, 10, 7, 5};
ListProvider lstProvider = new ListProvider(valArray);
chart1.setDataSource(lstProvider);

If you want to load data from more than one array, you can use the add method shown in the following example:

int[] series1 = {12, 15, 10};
int[] series2 = {20, 25, 7};
String[] labels = {"Yes", "No", "Don't know"};
ListProvider lstProvider = new ListProvider();
lstProvider.add(series1);
lstProvider.add(series2);
lstProvider.add(labels);
chart1.setDataSource(lstProvider);

Note:

You can pass arrays filled with Numerical Data and String or Dates that will be taken as legends in the chart. In this particular sample there are 3 arrays, two containing numerical data to be contained in the chart and the other containing legends for each point in the nValues array. This means, there's no limitation on the number of arrays you can pass using this technique.

Note:

You cannot pass multi-dimensional arrays to Chart FX 7 for Java Desktop. This means, if you create a matrix or a multi-dimensional array as nData(10,10), Chart FX 7 for Java Desktop will not know how to process this information. An error will occur.

Mapping arrays to series and labels

Just like with any other data provider, you can tell the chart how to use each of the arrays contained in the list passed to the chart.

For example, if we have the following data in our arrays:

Int[] year = {1999,2000,2001};
double[] sales = {100000, 125000, 150000};

Chart FX 7 for Java Desktop will consider the year array as another series since it is a numeric field. Instead, we want this field to be used as a value for the X-axis. We can easily override the Chart FX default behavior by defining FieldMaps in the field collection:

chart1.getDataSourceSettings().getFields().add(new FieldMap("field0",FieldUsage.XVALUE));
chart1.getDataSourceSettings().getFields().add(new FieldMap("field1",FieldUsage.VALUE));

Please note that in situations in which the source columns do not have a name or header, you can use the generic field0, field1, etc.


General Attributes

General visual attributes are exposed by the Chart object and when configured affect the chart as a whole. An example of setting a general visual attribute is setting the chart’s Gallery. Setting the gallery for the chart using the Chart object’s set Gallery method will set a chart type globally; in other words, only one chart type will be displayed at a time (Bar, Lines, etc.).

chart1.getAllSeries().setGallery(Gallery.AREA);

Some other supported members of the Chart class include the Border, BorderColor, BorderEffect, CylSides, MarkerShape, MarkerSize, PointLabels, Scheme, TypeMask, Volume, MarkerStep, etc. These are just a few of the general properties exposed by the Chart object, for more supported members please consult the Chart FX API Reference.


Per-series Attributes

The SeriesAttributes object exposes methods to manipulate many of the same properties described as General attributes, however, when configured only affect the selected series in the chart. By allowing customization on a per-series basis, Chart FX provides the developer with more control over the supported chart elements. Setting different chart galleries for selected series in a chart permits you to create combination charts to convey more information to the end users at one time. The Series object also allows you to set visual attributes to a series that can bring attention to a selected series.

chart1.getSeries().get(1).setGallery(Gallery.AREA);


Borders

Of all the features built into Chart FX geared to enhance the chart's presentation layer, none stand out more than Image Borders.

Alpha blending capability is used to display Chart FX image borders. These borders consist of a series of bitmaps that have transparent or semi-transparent pixels. In addition to a red, green, and blue color channel, each pixel in a border bitmap has a transparency component known as its alpha channel.

The alpha channel lets you control the color of the chart background as well as the color of the HTML page or form while keeping the effect of the border intact; resulting in an outstanding presentation effect for your charts without the restrictions imposed by static bitmaps that can't be changed programmatically.

Image Borders are very simple to integrate and require little or no programming efforts on your part..

Borders and Background Color

The Chart FX ImageBorders uses shading and great edge detail to give a multidimensional effect when they are placed in your forms. When using image borders, you want to seamlessly integrate them to your form design. If the area around image border is set to a color different from the form’s background, an undesirable block will be visible around the chart.

Chart FX 7 for Java Desktop takes care of this issue automatically. By default the PageColor property of the chart (which can be used to modify the background color of the shaded area around image borders) is set to transparent. If the chart is going to be exported to an image and later imported somewhere else, it might be necessary to change that. Setting the PageColor property to match the background color of the chart container will achieve a seamless visual effect. Also, the Border Object exposes some properties to customize the appearance of the border; for example, the setColor method can be used to change the border color.

The following figure shows a border object 'Pulsar' assigned to the chart, with its Color property set to 'Silver':

chart1.setBorder(new ImageBorder(ImageBorderType.Pulsar, java.awt.Color.SILVER));

Borders and other chart tools

Chart FX image borders are prepared to handle additional tools and windows that can be displayed in the chart area, including Toolbar, Legend windows and Data Editor.

The chart displayed uses an Embed image border, and notice how the different elements are properly rendered with the same border type.


Transparency

With transparency, you can make chart elements completely invisible in the chart area, such as background pictures and gradients that apply to the entire chart area. Also note that this setting can be applied to any chart element that receives a color. For example, if you have a scatter chart and you want to hide certain points, you can use the getPoint method and assign a transparent color to only certain points in the chart.

Essentially, transparency is achieved by setting the 4th parameter in the Color constructor as follows:

chart1.setPlotAreaColor(new java.awt.Color(0,0,0,0));

Semi-Transparency

In Chart FX, the alpha blending feature is used to display a chart element that has semi-transparent pixels. In addition to a red, green and blue color channel, each pixel in an alpha bitmap has a transparency component known as its alpha channel. The alpha channel typically contains as many bits as a color channel. For example, an 8-bit alpha channel can represent 256 levels of transparency, from 0 (the entire pixel is transparent) to 255 (the entire pixel is opaque). This channel can be controlled through the fourth parameter of the constructor of the java.awt.Color object. For example if you want to set the color of a particular series to be semi-transparent, you would need to do something like:

chart1.getSeries().get(2).setColor(new java.awt.Color(125,10,10,100));

Changing the transparency of an object evenly reveals the image elements that lie beneath the object and because semi-transparency can be applied to any chart element that supports a color, you can create a myriad of effects. For example, in a 3D oblique chart, you can make the first series semi-transparent so other series are revealed in the 3D view; or you can use the Point object to have particular marker(s) display semi-transparency. Similarly, you can make the chart background semi-transparent so a background image is blended into the chart, which creates a nice watermark effect.


Color Palettes

In most situations, you will want to assign colors to chart elements like markers, backgrounds and labels. However, our design team invested a lot of time creating default color palettes for Chart FX. This way, when you create a chart and populate it with data, everything looks nice and consistent (even if you have not taken the time to assign default colors to chart elements).

If you look into the Chart FX way of coloring your chart, you'll find out Chart FX provides other palettes that you, or your end users, can use to quickly change the chart.

Essentially, Palettes are a group of colors that apply to the different elements in the chart. When a palette is changed, all the elements that have not been forced to have a specific color will adapt to the new palette.

Using palettes from the Chart FX interface

Palettes provide a special functionality since they allow end users to customize the chart colors with a single click. All default and extended palettes are listed in the Chart FX Toolbar as a combo box that can be used to preview or apply a desired palette to the current chart. The image below shows the supported palettes available from the Toolbar:

Using Palettes programmatically

In order to set a specific palette to your chart, you need to use the setPalette method. Please note, the setPalette method receives a string parameter with the name of the palette you want to load.

chart1.setPalette("Nature.Sky");

Since Chart FX palettes are extensible, you can create and integrate your own palettes programmatically, or let your users use them through the Chart FX Toolbar. We have used this functionality to create a large set of predefined palettes within Chart FX:

DefaultNatural.SkyChartFX6.EarthTonesChartFX6.ModernBusinessDarkPastels.PastelsMesa.Mesa Natural.Adventure HighContrast.HighContrastVividChartFX6.AlternateChartFX6.WindowsChartFX6.ChartFX6Schemes.ColorfulSchemes.ClassicSchemes.SimpleSchemes.ProfessionalSchemes2.AutumnSchemes2.OceanicaSchemes2.Brown SugarSchemes2.SlateSchemes3.Sand & SkySchemes3.Rainy DaySchemes3.Snowy PineSchemes3.Lilacs in Mist Schemes4.MochaSchemes4.Black&Blue1

Note:

To properly load these palettes, you will simply use their string names (i.e. "DarkPastels.Pastels").

Palette Naming Convention

Notice how many of the palettes use a name consisting of two words separated by a period (DarkPastels.Pastels). Each of the Chart FX palettes is derived from a base color scheme, which provides the "first word". The unique combination of colors used to create a selected palette from a base color scheme is the "second word" in the name. Therefore, if a base color scheme only has one combination, the second word is not required. This can be observed in the Vivid palette for example. Because there is only one palette existing in Vivid, you only need to specify the base color scheme to complete the configuration (i.e. "Vivid").


Gradients

Gradient fills let you create a gradual blend between colors in chart elements like markers and backgrounds. For example, gradients in chart markers (i.e. bars) can improve the chart’s readability by giving a meaningful color representation to the data contained in the chart. Also, when applied to the chart background, gradients can help you achieve a superior visual effect for your Windows Forms applications and web sites.

By default, the color in a linear gradient changes uniformly. However, in this chapter you will learn how to use the Chart FX API so you can create and customize linear gradients so that the color may change in a non-uniform fashion.

Gradients in chart markers

In most situations, gradients are commonly used to achieve a cosmetic fill effect on a particular shape. However, when used in chart markers, Chart FX gradients serve a different purpose as they allow the user to immediately recognize data trends and call out important data in the chart.

chart1.getLegendBox().setVisible(false);
chart1.setGallery(Gallery.BAR);
chart1.getData().setSeries(1);
chart1.getData().setPoints(6);
int i = 0;
for(i = 0; (i < 6); (i)++);
{
    chart1.getData().set(0, i, ((double)(5 + ((10 * i)))));
}
chart1.getAxisX().getGrids().getMajor().setVisible(false);
chart1.getAllSeries().setFillMode(FillMode.GRADIENT);
chart1.getAllSeries().setColor(java.awt.Color.DARKBLUE);
chart1.getAllSeries().setAlternateColor(java.awt.Color.MINTCREAM);

To illustrate this, the chart displayed uses a gradient fill that allows the user to immediately recognize markers that fall within a range with just a quick look at the chart.

To achieve this effect, you must set a special color scheme that activates the markers gradient fill. Then, Chart FX defines a virtual rectangle that starts at the top of the chart (defined by the Y Axis Max) and uses the marker color as a starting point (top) and an alternate color to blend uniformly to the bottom (X Axis).

Setting the setFillMode method to “Gradient" and setting the Color and AlternateColor on the Series object will produce the Chart shown.

It is important to note that marker gradients are used for data analysis purposes in Chart FX. Therefore, marker gradients accept only two colors and are limited to a horizontal effect.

Finally, please remember the Y Axis Maximum will significantly affect the virtual rectangle on which the gradient is going to be painted. For example, in the chart shown above if the Y Axis Maximum is changed from 100 to 200, all chart markers will have intensity close to the alternate color (green) as they will be farther away from the top of the chart where the marker color (yellow) is used.

Gradients in the chart’s background

As opposed to marker gradients, background gradients are used for cosmetic purposes only. In other words, background gradients are only used to enhance the chart’s visual appearance and have no direct relation to the data contained in the chart.

In Chart FX, gradients can be applied to 2 rectangular areas in the chart area: The chart’s inside background and the main background.

Chart FX allows horizontal, vertical, diagonal and radial gradients when applying gradient fills to either of these areas of the chart.

You can use Chart FX API to set the objects and its properties to create and display gradient fills.

By default, the color in a linear gradient changes uniformly. However, in this chapter you will learn how to use the Chart FX API so you can create and customize linear gradients so that the color may change in a non-uniform fashion.

For more information about how to create a Gradient Background and how to assign it to any of the Chart’s backgrounds please refer to the Chart FX online Programmer’s Guide and the API Reference.

Manipulating gradient colors, positions.

You can use the GradientBackground object’s method to set visual attributes like colors, positions and color intensity. The following section will show you how to create multicolor and bi-color gradients.

Essentially, a gradient object provides a Color array property that you can use to set the colors you want for your gradient. These colors will then be uniformly blended in the chart’s background by dividing the bounding rectangle into equal sections and blending from one color to another in the Color array.

If for example, you pass four values to the color array, Blue, Red, Yellow and Green, and set the Chart’s Inside Background as "Forward Diagonal" gradient, Chart FX will create 3 regions that will blend uniformly:

Here region 1 will go from Blue to Red, section 2 from Red to Yellow and section 3 from Yellow to Green.

If this arrangement is not convenient, you may alter the positions of each blending area by using the Position array supported by the GradientBackground object.

To understand how positions work in the bounding rectangle, imagine the first position (where the gradient starts) as position 0; the ending position would then be 1 and then intermediate positions would be fractions between 0 and 1.

In our previous example if we wanted the gradient from Blue to Red to occupy only 10% of the bounding rectangle and the gradient from Red to Yellow to fill 70% of the area, we could have used the Position array as follows: 0, 0.1, 0.8 and 1.

Bi-Color gradients

In some cases, you may want to work with bi-color gradients and simply repeat a gradient pattern across the chart’s background. If this is the case, instead of defining a Color array with the 2 same colors over and over, you can simply create a bi-color gradient.

A bi-color gradient requires Position and Factor (color intensity) arrays to display a repeating pattern across the chart’s background. Previously we described the effect the Position array had on the gradient. In bi-color gradients a new Factor array must be defined to instruct Chart FX on the color intensity on each position.

To understand the Factor array, consider that the values it takes are a fraction between the 2 colors in the color array. If set to 0, then the resulting color will be the color available in the position 0 of the Color array and similarly with a value of 1.

For example take a closer look at the Factor array and the effect it creates on the gradient in the following 2 samples:

Position: 0,0.25,0.75,1, Factor: 0,1,0,1

GradientBackground g1;
g1 = new ChartFX.WebForms.GradientBackground(adornments.GradientType.BACKWARD_DIAGONAL);
g1.getColors().set(0, java.awt.Color.BLUE);
g1.getColors().set(1, java.awt.Color.RED);
g1.getPosition().set(0, ((float)0));
g1.getPosition().set(1, 0.25f);
g1.getPosition().set(2, 0.75f);
g1.getPosition().set(3, ((float)1));
g1.getFactor().set(0, ((float)0));
g1.getFactor().set(1, ((float)1));
g1.getFactor().set(2, ((float)0));
g1.getFactor().set(3, ((float)1));
chart1.setPlotAreaBackground(g1);

Position: 0,0.25,0.75,1, Factor: 0,0.8.0.9,0

GradientBackground g1;
g1 = new ChartFX.WebForms.GradientBackground(adornments.GradientType.BACKWARD_DIAGONAL);
g1.getColors().set(0, java.awt.Color.BLUE);
g1.getColors().set(1, java.awt.Color.RED);
g1.getPosition().set(0, ((float)0));
g1.getPosition().set(1, 0.25f);
g1.getPosition().set(2, 0.75f);
g1.getPosition().set(3, ((float)1));
g1.getFactor().set(0, ((float)0));
g1.getFactor().set(1, 0.8f);
g1.getFactor().set(2, 0.9f);
g1.getFactor().set(3, ((float)0));
chart1.setPlotAreaBackground(g1);

Note:

The Factor array does not apply to multicolor gradients (3 or more colors).


Handling Fonts and Titles

Fonts

As you have seen from the beginning of this section, visual attributes can be configured at a general level in the Chart object, or at a more granular level. Similarly, Fonts can be applied in general at the Chart level, or on a granular level for various sections of the chart such as: Axis Labels, Points Labels, Legends, Series Legends, Data Editor, etc.

If the Chart Object is assigned a font such as Bold Arial size 12, that font setting will be used for all chart objects that make use of fonts for rendering.

chart1.setFont(new java.awt.Font("Arial",java.awt.Font.PLAIN, 10));

Now if you want to show the Point Labels in a different font, size and color, you can custom configure them using the setFont and setTextColor methods of the PointLabels object.

chart1.setFont(new java.awt.Font("Arial",java.awt.Font.PLAIN, 10));
chart1.getAllSeries().getPointLabels().setVisible(true);
chart1.getAllSeries().getPointLabels().setFont(new java.awt.Font("Times New Roman",java.awt.Font.PLAIN, 8));
chart1.getAllSeries().getPointLabels().setTextColor(java.awt.Color.BLACK);

Titles

To improve the chart's readability, Chart FX supports the creation of titles that you can use to set the chart main title. A title is a string that can be assigned to any portion outside the main chart area.

This string can be positioned, aligned and formatted according to the different properties supported by the TitleDockable object which allows the creation of an unlimited amount of titles in the chart area.

By default, all the titles you create will be positioned at the top of the chart, or where the main chart title is displayed. For example, if you use the following API, it will create a title on the top portion of the chart.

chart1.getTitles().add(new TitleDockable("My chart Title"));

You can create multi-line titles by simply adding an additional title in the same position. These lines can then be independently aligned and formatted.

The Title object supports a series of methods that you can use to align, position and format the different titles in the chart.

chart1.getTitles().add(new TitleDockable());
chart1.getTitles().get(0).setText("My chart Title");
chart1.getTitles().get(0).setFont(new java.awt.Font("Arial",java.awt.Font.PLAIN, 12));
chart1.getTitles().get(0).setAlignment(StringAlignment.CENTER);
chart1.getTitles().add(new TitleDockable("Sales in Dollars"));

TitleDockable Class

The TitleDockable class supports the additional DockArea and LineAlignment properties that allow a title to be docked in the chart area. In order to utilize this functionality, you must create your title objects as a TitleDockable object and use the respective methods to access the properties.

TitleDockable title;
title = new TitleDockable();
title.setDock(DockArea.TOP);
title.setLineAlignment(StringAlignment.CENTER);
title.setText("My chart Title");

Axes Titles

Titles can be created on the chart’s Axes. They can be assigned, aligned and formatted according to the different properties supported by the Title object.

chart1.getAxisX().getTitle().setText("X Axis Title");
chart1.getAxisY().getTitle().setText("Y Axis Title");

Axes Titles are attached to the Axis to which they belong. If the Y Axis gets moved to the right side of the chart (Far), the Y Axis Title will get moved there as well. If the X Axis is hidden, the X Axis Title will be hidden also.


Introduction

Axes are one of the most important elements since they contain information that help the user interpret the chart. In most instances, charts are drawn in an XY-coordinate system. The Value or Y axis displays a range of values represented by the numeric data, and the Category or X axis displays how the data is broken down in the chart. The following picture highlights the Value (Y) Axis and the Category (X) Axis:

chart1.getAxisX().getTitle().setText("Categorical Axis");
chart1.getAxisY().getTitle().setText("Numerical Axis");
chart1.getData().setSeries(1);
chart1.getData().setPoints(12);
java.util.Random r;
r = new java.util.Random(1);
int i = 0;
for(i = 0; (i < 12); (i)++);
{
    chart1.getData().set(0, i, (100.0 * (r.nextDouble())));
}
chart1.getAxisX().getLabels().set((short)0, "Jan");
chart1.getAxisX().getLabels().set((short)1, "Feb");
chart1.getAxisX().getLabels().set((short)2, "Mar");
chart1.getAxisX().getLabels().set((short)3, "Apr");
chart1.getAxisX().getLabels().set((short)4, "May");
chart1.getAxisX().getLabels().set((short)5, "Jun");
chart1.getAxisX().getLabels().set((short)6, "Jul");
chart1.getAxisX().getLabels().set((short)7, "Aug");
chart1.getAxisX().getLabels().set((short)8, "Sep");
chart1.getAxisX().getLabels().set((short)9, "Oct");
chart1.getAxisX().getLabels().set((short)10, "Nov");
chart1.getAxisX().getLabels().set((short)11, "Dec");


Numerical and Categorical Axis

When you first create and populate a chart, Chart FX uses a "best-fit" algorithm that accommodates axis settings automatically. This behavior minimizes the initial programming effort of customizing the chart’s axes. However, in most cases, programmers will face complex axis configuration scenarios like labeling, scrolling, scaling and formatting that must be used in order to help users follow and analyze data.

This section describes the most common axis manipulation scenarios and advanced features and techniques that are used to enhance the chart’s readability like creation of logarithmic scales, multiple axes as well as axis sections and panes. It is important to note that end users can also manipulate the most common and recognizable axis settings via a user interface (Toolbar and context sensitive dialogs) provided by Chart FX. For additional information, please refer to the "Chart FX User Interface" chapter of this manual.

The first step to properly configure an axis is to recognize whether you are dealing with a numerical or categorical axis. Sometimes this is not trivial and you may need to closely inspect the chart. In most cases, you will have a categorical axis accompanied by a numerical axis, like the following image:

However, in an XY or scatter, both axes are numerical. Similarly, for some chart types like Gantt or horizontal bars, you can tilt the x axis to be vertical and while still remaining a categorical axis. Also, some chart types don’t even have X or Y axes; for example a pie chart will not respond to any of the properties or methods provided in the Axis object.

These situations are depicted in the following images:

In essence, a numerical axis will contain numbers associated with each tick mark and, therefore, will respond to any property or method that is used to scale or format such numbers. When dealing with numerical axis you don’t have to worry about labeling each tick mark as Chart FX will automatically select the label (or number) for each tickmark in the axis.

On the contrary, a categorical axis displays labels (not numbers). In most cases, you will need to label each tick mark to improve the chart’s readability. If no labels are specified for a categorical axis, Chart FX will assign numerical tags (1,2,3,…) to each tickmark in the axis.


Axes Scaling

Automatic Axis Scaling

As already mentioned, when you first create and populate a chart, Chart FX will use a "best-fit" algorithm that accommodates the numerical axis settings automatically. This behavior minimizes the initial programming effort of customizing the chart’s numerical axes. These values are chosen according to the chart type, data and the chart’s size and then adjusted so the axis shows "nice" values in the chart. Finally, the chart markers will be plotted in the chart area according to their value and the position in the chosen scale.

chart1.getAxisY().setMin(25);
chart1.getAxisY().setMax(200);
chart1.getAxisY().setMinorStep(0);
chart1.getAxisY().setStep(25);

You can reset any of these scale values using the several methods associated with a numerical axis. Some scale values include: Minimum (or where the axis starts), Maximum (or where the axis ends) and Step (or major unit).

The setStep method controls where labels and tickmarks are shown in a numerical axis. This fraction is usually called the major unit.

The setMinorStep method allows you to set a minor unit on which you can only show and configure tickmarks and gridlines.

Recalculating Axis Scale Information

chart1.getAxisY().setAutoScale(true);
chart1.getAxisY().resetScale();
chart1.recalculateScale();

When new data is set to the chart, Chart FX will then again recalculate the scale values according to the new data set. This behavior can be controlled by the setAutoScale method of the axis. This property is enabled by default. If you choose to disable this property you must set the Min and Max values manually.

If you preset any of the scale values (Min, Max, Step or MinorStep) Chart FX will not recalculate the scale when new data is sent to the chart. This behavior can be altered by invoking the ResetScale method of the Axis object. This method recalculates scale values associated to that specific numerical axis. This method is particularly useful if you know the specific axis that needs to be reset.

If you want to recalculate ALL numerical axes settings, the Chart exposes a method called RecalculateScale . Please keep in mind that the RecalculateScale method applies to ALL numerical axes and reads the entire data array. In other words, you should avoid calling this method repeatedly as it will adversely affect the performance of your application.

Formatting a Numerical Axis

Formatting a numerical axis is as simple as setting any of the pre-defined axis formats in Chart FX using the setFormat property supported by the ValueFormat class. For example, you can set scientific notation in the primary Y Axis using the LabelsFormat property.

Please make sure you check the setFormat property on the API Reference for more information on any pre-defined formats or constants supported by Chart FX.

chart1.getAxisY().getLabelsFormat().setFormat(AxisFormat.PERCENTAGE);
chart1.getAxisY().getLabelsFormat().setDecimals(3);

Logarithmic Scales

When plotting large numbers, Chart FX supports independent logarithmic scales on any of the axes (Primary, Secondary Y and X when used in a numerical sense). You may have Log-Log, Linear-Log or Log-Linear scales.

chart1.getAxisY().setLogBase(10);

To set a Logarithmic scale to any of the Chart FX numerical axes you can use the setLogBase method. This method will set a logarithmic scale for a numerical axis and recalculate the values as powers equal to the setting of this property. For example, you can set the Y Axis to be logarithmic with base 10.


Axis Labeling

Labeling a Categorical Axis

By default, a categorical axis (X Axis) is labeled with tags (1, 2, 3...) on every tick mark. You can improve the chart’s readability by assigning meaningful information to these tickmarks. The Labels collection can be used for this purpose. When setting a string to each member of the collection, the chart will display these labels in their appropriate tickmarks as depicted in the following figure:

chart1.getData().setSeries(1);
chart1.getData().setPoints(6);
java.util.Random r;
r = new java.util.Random(1);
int i = 0;
for(i = 0; (i < 6); (i)++);
{
    chart1.getData().set(0, i, (100.0 * (r.nextDouble())));
}
chart1.getAxisX().getLabels().set((short)0, "1st");
chart1.getAxisX().getLabels().set((short)1, "2nd");
chart1.getAxisX().getLabels().set((short)2, "3rd");
chart1.getAxisX().getLabels().set((short)3, "4th");
chart1.getAxisX().getLabels().set((short)4, "5th");
chart1.getAxisX().getLabels().set((short)5, "6th");

Note:

If you populated the chart from a database, these labels are automatically assigned from text fields in the query. For more information on populating charts with data coming from a database please refer to the "Passing Data" section earlier in this manual.

By default, Chart FX will calculate the amount of labels that can be displayed according to the chart size and will hide some labels if all cannot be shown. There are some properties and techniques that will help you fit more labels on a categorical axis.

chart1.getAxisX().setStep(3);
chart1.getAxisX().setFirstLabel(1);

Just like a numerical axis, a categorical axis supports the Step property to control the interval labels are shown along the axis. For example, when a value of 3 is applied to the Step property, labels will be placed on positions 3, 6, 9 and so on. The FirstLabel property works in a similar way, only that it forces the first label to be placed on a specific tick mark. For example, if setFirstLabel is set to 1, then X Axis labels will be shown at positions 1, 4, 7 and so on.

You can also make room for more labels if you rotate them 90 degrees using the setLabelAngle metod or you can make the labels staggered as depicted in the following figure:

chart1.getAxisX().setStaggered(true);

Additionally, the AxisX provides a myriad of methods that can be used to customize labels like font, gridlines, tickmarks, colors, axis styles, label rotation and other special effects. For more information, please refer to the Axis object in the Chart FX API reference or the samples included with the Chart FX 7 for Java Desktop installation.

Custom Labeling a Numerical Axis

Although it is not common to assign custom labels on a numerical axis, there may be situations in which a numerical axis may need to display or map a series of labels that describe the specific value of a tick mark. For example, consider the case of ratings. Ideally you would want the chart to display labels on the axis itself, as depicted in the following picture:

chart1.getAxisX().setStaggered(true);
chart1.getAxisY().getLabels().set((short)0, "Very Poor");
chart1.getAxisY().setMin(0);
chart1.getAxisY().setMax(100);
chart1.getAxisY().setStep(20);
chart1.getAxisY().getLabels().set((short)1, "Poor");
chart1.getAxisY().getLabels().set((short)2, "Average");
chart1.getAxisY().getLabels().set((short)3, "Good");
chart1.getAxisY().getLabels().set((short)4, "Very Good");
chart1.getAxisY().getLabels().set((short)5, "Excellent");
chart1.getAxisY().setLabelValue(20);

To accomplish this, you must:

  • Make sure you manipulate the scale settings (setMin, setMax,setStep properties) so you end up with six tickmarks in the axis (i.e. 0, 20, 40, 60, 80 and 100).
  • Use the getLabels().set(index,value) method and add six labels in the correct order corresponding to ticks allocated with Min and Max above. For example start with "Very Poor" (index 0) and end with "Excellent" rating (index 5).
  • Use the setLabelValue method to specify the interval where those labels should be placed on a numerical axis. If you specify a LabelValue of 20, each label will be placed next to its corresponding tick mark.


Manipulating Dates and Times in a Categorical Axis

Chart FX provides means of formatting the axis labels to display date/time labels through the Formatproperty. This property supports either Dateor Timeconstants specifically for displaying dates in a categorical axis. For example, if you have passed data that ranges in minutes, you would select the Time constant; or if you have passed data that ranges in days you can setup the setFormatmethod to Dateand control how frequent labels are displayed using the setStepmethod.

For example, you can setup a categorical axis and formatthe tick mark labels using a CustomFormatdate mask that formats the date with the month name and the day as depicted in the following figure:

chart1.getData().setSeries(1);
chart1.getData().setPoints(5);
java.util.Random r;
r = new java.util.Random(1);
Calendar cal;
cal = Calendar.getInstance();
int i = 0;
for(i = 0; (i < 5); (i)++);
{
    chart1.getData().getY().set(0, i, (100.0 * (r.nextDouble())));
    chart1.getData().getX().set(0, i, Chart.dateToNumber(cal.add(Calendar.MONTH, 1)));
}
chart1.getAxisX().getLabelsFormat().setFormat(AxisFormat.DATE);
chart1.getAxisX().getLabelsFormat().setCustomFormat("MMM-dd");
chart1.getAxisX().setStep(30);

Data-Driven labels

Although the ability of formatting dates in a categorical axis provides a certain freedom for customization, these labels are still fixed and do not change dynamically as the chart is resized in the browser or in a form. The Data-Driven labels involves passing dates as XValues to the chart and setting the setFormat method to Date or Time constants.

Because the Smart Date Axis IS NOT a categorical axis but a numerical one, it treats dates as numbers and it is capable of adapting dynamically to the chart size. For example, if the chart contains 3 years worth of data in days, you WILL NOT need to label each tick mark as Chart FX will assign labels accordingly making the process a lot easier to code as well as improving the chart’s readability. In the picture displayed below, Chart FX selected the Quarter view as the most appropriate label for the chart size.

chart1.getData().setSeries(1);
chart1.getData().setPoints(365);
chart1.setGallery(Gallery.BAR);
chart1.getAxisX().getLabelsFormat().setFormat(AxisFormat.DATE);
chart1.getAxisX().setStep(90);
java.util.Random r;
r = new java.util.Random(1);
Calendar cal;
dateTime = SfxNET.System.Convert.ToDateTime("01/01/05").StructClone();
int i = 0;
for(i = 0; (i < 365); (i)++);
{
    chart1.getData().getY().set(0, i, (100.0 * (r.nextDouble())));
    chart1.getData().getX().set(0, i, Chart.dateToNumber(cal.add(Calendar.DAY, 1)));
}


Tilting and Positioning Axes

The most common position for labels in numerical and categorical axes is at the left and bottom portion of the chart, respectively. Nevertheless, you could run into situations where axes must be tilted, inverted or positioned in different areas of the chart.

For example a Gantt chart not only tilts the categorical axis to the left side but usually displays the numerical axis (or dates) at the top of the chart. The following image depicts a chart with the categorical or x axis tilted with the help of the setTypeMask method (Horz constant) and the Y axis is repositioned to top portion of the chart:

chart1.setGallery(Gallery.GANTT);
chart1.getAxisY().setPosition(AxisPosition.FAR);

Note:

Not all chart types support axis tilting.


Interlaced Grids

In some cases interlaced gridlines are very useful to improve the chart’s readability; they are as depicted in the following figure:

chart1.getAxisY().getGrids().setInterlaced(true);
chart1.getAxisY().getGrids().setInterlacedColor(java.awt.Color.YELLOW);
chart1.setPlotAreaColor(java.awt.Color.WHITE);

To achieve this effect, you need to use the chart’s setPlotAreaColormethod and the setColor and setInterlacedColors method of the grids object.


Axis Scrolling

Although Chart FX provides a wealth of properties to control how labels are displayed on an axis, the number of data points and the chart size become important factors influencing how many labels you could fit within a chart or how much data is actually visible. In other words, some charts simply have too much data for the desired chart size and there’s little you can do to improve the chart’s readability.

Chart FX provides an elegantly designed scroll bar that attaches to an axis and allows end users to zoom in and view portions of an entire chart. All axes in Chart FX support scrolling.

To enable scrolling you must use the setAutoScrollmethod of the axis you wish to allow scrolling. The scroll bar will appear docked right next to the axis labels as depicted in the following figure:

chart1.getData().setPoints(50);
chart1.getAxisX().setAutoScroll(true);
chart1.getAxisX().SetScrollView(21.0, 28.0);

Once scrolling is enabled the user can click the arrows at the extremes of the Toolbar in order to move the viewing area to either side. By using the scrolling feature data points will not be crunched inside the chart area and all points will show their respective labels. This enhances the chart’s readability and allows the user to view portions of the chart at a time.

Note:

Scrollbars will appear automatically when the end user uses the Zoom tool available in the Chart FX Toolbar.

Controlling the Scroll position programmatically

Although the scroll bar is an end user tool, you may want to control the number of points that are visible in a specific scroll area. This can easily be done with the SetScrollView method supported by the Axis object.

For a categorical axis, this method receives the index of the points you want to see in the chart. For a numerical axis, the SetScrollView method receives the values yon want to show in a specific scroll view.

Chart FX will fire an event called UserScroll every time the user interacts with the axis scroll bar. This event may be useful if you need to allow the user to scroll two charts simultaneously as the user interacts with a single scroll bar.

Please refer to the Chart FX API Reference for more information on the UserScroll event supported by Chart FX.


Creating Additional Axes

Creating and displaying additional axes in the chart is very similar to assigning a secondary Y Axis.

For example, if you want to add a third series to the previous chart, which values range between 0 and 1; both existing scales (0-100 and 0-2000000) are still inadequate to represent fractions between 0 and 1. Therefore, we need a fourth axis to represent these values. Please remember that three axes are already displayed in the chart: Y Axis, Secondary Y Axis and the X Axis.

You can create as many as there are series in the chart. To add the fourth axis we will assign the third series to a new axis index, in this case 3.

Please remember Chart FX indexes are zero based. In addition, this assignment must be applied before the chart is populated so Chart FX can initialize the fourth axis properly. If this can’t be done before data is applied, then you must use the RecalculateScale method after populating the chart.

After you have assigned the series to its appropriate axis, you can use properties exposed by the Axis(n) object to configure its visual and scaling attributes.

Additional Category Axes

Additional category axes can significantly improve the chart’s readability by providing another categorical scale to the already existent x axis. For example, the following chart features a double categorical axis highlighting months as well as quarters in the year:

chart1.setWidth((short)310);
chart1.setHeight(210);
chart1.getLegendBox().setVisible(false);
chart1.setGallery(Gallery.CURVE);
chart1.getAllSeries().setMarkerShape(MarkerShape.NONE);
chart1.getAxisY().getGrids().getMajor().setVisible(false);
chart1.getAxisX().getGrids().getMajor().setVisible(false);
AxisX axis;
axis = new AxisX();
chart1.getAxesX().add(axis);
axis.getGrids().getMajor().setVisible(true);
axis.setMin(0);
axis.setMax(12);
axis.setStep(3);
axis.setFont(new java.awt.Font("Arial",java.awt.Font.PLAIN, 8));
axis.getGrids().getMajor().setVisible(true);
axis.getLabels().set((short)3, "1st Q");
axis.getLabels().set((short)6, "2nd Q");
axis.getLabels().set((short)9, "3rd Q");

The trick to adding an additional category axis is simply creating a new axis using the axis object and using a new index for the additional categorical axis. Make sure you keep track of the indexes that you have already used when creating a new numerical or categorical axes. Furthermore, the YAxis property of the newly created axis should be set to false. In the image shown above we have also manipulated the Min, Max and Step so it shows gridlines only every three months in order to highlight the respective quarters.

Creating a Secondary Y Axis

When the range of values for different data series varies widely, or when you have mixed types of data such as price and volume, you can plot one or more data series on a secondary value (y) axis. The scale of the secondary axis is independent and reflects the values for the associated series.

The first step in creating a secondary Y axis is to assign a series to the secondary Y Axis using the setYAxismethod in the Series object. After you have assigned the desired series to the secondary Y axis, you can use the AxisY2 similarly to the AxisY to handle scales, gridlines and different settings for the secondary Y Axis.

For example, the following chart contains price and volume information. We have assigned the volume series to a secondary Y axis that ranges in the millions while the price remained in the primary Y axis with values ranging between 40 and 80. We are also displaying the primary Y axis using the Currency format.

chart1.getData().setSeries(2);
chart1.getData().setPoints(60);
chart1.getLegendBox().setVisible(false);
chart1.setGallery(Gallery.AREA);
SeriesAttributes serie1;
serie1 = chart1.getSeries().get(1);
serie1.setAxisY(chart1.getAxisY2());
serie1.setGallery(Gallery.LINES);
serie1.setMarkerShape(MarkerShape.NONE);
java.util.Random r;
r = new java.util.Random(1);
int i = 0;
for(i = 0; (i < 50); (i)++);
{
    chart1.getData().getY().set(0, i, (100.0 * (r.nextDouble())));
    chart1.getData().getY().set(1, i, (400.0 + ((100.0 * (r.nextDouble())))));
}


Axis Panes

Sometimes, creating additional axes is not enough to highlight and properly separate data. The Chart FX Axis Panes allow the developer to display multiple sections of data in a single chart window. This feature allows developers to separate series allowing for improved analytical experience as each pane displays different scales and different chart types as required.

To create panes, you must first assign series to a new numerical axis as mentioned earlier, and then use the Pane property exposed by each series. Please note that multiple series may be configured to a single pane as well.

In the following example, we have a 3 series chart in which each series has been configured to display in a different pane:

chart1.getData().setSeries(3);
Pane pane1;
pane1 = chart1.getPanes().get(0);
chart1.getPanes().add(new Pane());
chart1.getPanes().add(new Pane());
chart1.getSeries().get(0).setPane(chart1.getPanes().get(0));
chart1.getSeries().get(0).setGallery(Gallery.LINES);
chart1.getSeries().get(1).setPane(chart1.getPanes().get(1));
chart1.getSeries().get(2).setPane(chart1.getPanes().get(2));
chart1.getSeries().get(2).setGallery(Gallery.AREA);

Axis Panes Attributes

The Pane object exposes a collection of members that allow the developer to control basic visual attributes for a selected pane item. Please see the short description of each below, for further details please consult the API reference.

chart1.getPanes().get(paneIndex).setProportion(5);

Background (get, set) - This member is used to configure a background image or GradientBackground object to a chart pane.

Proportion (get, set)- This member is used to get or set a value indicating the proportional size of the selected pane. For example, if there are three panes in a chart. Pane1's proportion is configured to the value "1". Pane2's proportion is configured to the value "2". Pane3's proportion is set to the value of "1" as well. Assuming the entire charting area represents 100%, Pane1 will use 25% of the chart area, Pane2 will use 50%, and Pane3 will use 25%. Other chart components visible in the chart area may affect the final size of the panes.

Separation (get, set)- This member is used to get or set a value indicating the space (in pixels) in between panes.

Title (get,set)- This member is used to obtain the Title object used for a selected Pane object. All the supported members of the Title object are exposed for the pane's title.


Axis Sections

The Axis Section implementation is another analytical feature offered by Chart FX. When using Axis sections in your applications, end users will quickly identify focus areas of a chart and will be able to easily determine whether values fall into a particular range. This analytic enhancement makes data driven charts more pleasing to the eye and easily deciphered by users.

Take a closer look at the following chart. The values between 40 and 60 are easily identifiable.

AxisSection section;
section = new AxisSection();
chart1.getAxisY().getSections().add(section);
section.setBackColor(java.awt.Color.RED);
section.setFontStyle(FontStyle.BOLD);
section.setFrom(40);
section.getGrids().getMajor().setVisible(true);
section.getLink().setUrl("www.SoftwareFX.com");
section.getGrids().getMinor().setVisible(true);
section.getGrids().getMinor().setTickMark(TickMark.CROSS);
section.setTextColor(java.awt.Color.BLUE);
section.getGrids().getMajor().setTickMark(TickMark.CROSS);
section.setTo(60);

The AxisSection object allows the creation and customization of the configured chart axes. This provides the developer with a way to emphasize axis sections in order to improve readability of charts. To create an axis section, first you must specify which Axis object in the chart you want to create a section in. This can be done using the Sections collection of the AxisX or AxisY objects. Once the AxisSection object has been created, you may specify the range (SetTo and SetFrom methods), the BackColor, grids and grid attributes, tickmarks, and much more. Many of the properties supported by the Axis object itself are customizable for the AxisSection object. Please see the API reference for a thorough explanation of the AxisSection and AxisSectionBase classes.


Data Grid

Chart FX provides a spreadsheet called DataGrid allowing the user to see all the series and points contained within the chart in a spreadsheet type fashion. By default, the DataGrid is readonly, however the developer can adjust it to be editable by Setting the setReadOnly method as shown below.

chart1.getDataGrid().setReadOnly(false);

Additionally, the DataGrid allows the developer to fully customize the look and feel at a very granular level by using per-cell attributes. Cell attributes include BackColor, BorderColor, BorderWidth, FontStyle as well as TextColor. For example, if you would like to set the first cell's border and background color, you would use the following code:

/* obtain a reference to the attributes for the cell */
CellAttributes ca;
ca = chart1.getDataGrid().getCells().get(0, 0);
/* modify the properties for the cell */
ca.setBackColor(java.awt.Color.RED);
ca.setBorderColor(java.awt.Color.BLUE);
/* This docks the datagrid to the top of the chart */
chart1.getDataGrid().setDock(DockArea.TOP);
chart1.getDataGrid().setVisible(true);

Note:

Based on customer feedback, setFontStyle is made available instead a more generic Font property allowing you to customize the look of the font without changing the font itself. The possible styles are Bold, Italic, Regular, Stirkeout, & Underline.


Custom Grid Lines

Custom Grid lines are some of the most useful objects when it comes to highlighting information in the chart area. You may want to create constant lines to highlight limits or specific points of interest in the chart. For example, in a scientific application, you may want to use the constant line object to highlight an alarm limit; or in a financial application you may want to highlight a target price or date.

Custom Grid lines are lines that you can draw anywhere in the chart area and associate them with a particular value in the axis that they're assigned to. The following figure includes the set of API calls required to create it:

chart1.setGallery(Gallery.CURVE);
CustomGridLine custom1;
custom1 = new CustomGridLine();
custom1.setValue(3);
custom1.setColor(java.awt.Color.BLUE);
custom1.setText("Limit 1");
custom1.setWidth((short)2);
chart1.getAxisX().getCustomGridLines().add(custom1);
CustomGridLine custom2;
custom2 = new CustomGridLine();
custom2.setValue(25);
custom2.setColor(java.awt.Color.BLACK);
custom2.setStyle(DashStyle.DASH);
custom2.setText("Alarm Limit 1");
custom2.setTextColor(java.awt.Color.RED);
chart1.getAxisY().getCustomGridLines().add(custom2);

All constant lines are handled by the Line and CustomGridLines objects and their supported members. Using the Line object, you can control the line color, styles and width. The ConstantLine object members also allow control over other attributes such as the associated axis.

Creating a Custom Grid line does not require a new data series and you can also configure labels and line styles, colors and widths.


Conditional Attributes

The Conditional Attributes feature of Chart FX provides a built in solution to configure point attributes for chart points that meet a configured condition. The value of each point is evaluated against the items in the ConditionalAttributes collection. When the point's value meets the conditions configured, that Conditional Attributes object would be assigned to the point; retaining the configured attributes.

The conditional attributes allow coloring points and setting marker size and shape independently without the need for creating complex algorithms to evaluate chart values. The ConditionalAttributes object derives from the PointAttributes object. For more information regarding the supported members of these objects, please consult the Chart FX API Reference.

In the following chart, different marker shapes and colors were configured to show the different ranges in a chart. The ranges are 0-20 (gray circle), 20-80 (blue square) and 80-100 (red triangle). Using 3 conditional attributes, one for each range, the points of the scatter plot were customized depending on their value. Below the chart appears the set of API calls required to obtain it:

chart1.getData().setSeries(1);
chart1.getData().setPoints(20);
chart1.setGallery(Gallery.SCATTER);
chart1.getSeries().get(0).setMarkerShape(MarkerShape.RECT);
chart1.getSeries().get(0).setText("Normal");
chart1.getLegendBox().setDock(DockArea.BOTTOM);
chart1.getLegendBox().setFont(new java.awt.Font("Arial",java.awt.Font.PLAIN, 7));
ConditionalAttributes condition1;
condition1 = new ConditionalAttributes();
condition1.setColor(java.awt.Color.GRAY);
condition1.setMarkerSize((short)5);
condition1.setMarkerShape(MarkerShape.CIRCLE);
condition1.getCondition().setTo(20);
condition1.getCondition().setToOpen(true);
condition1.setText("Underqualified");
chart1.getConditionalAttributes().add(condition1);
ConditionalAttributes condition2;
condition2 = new ConditionalAttributes();
condition2.setColor(java.awt.Color.RED);
condition2.setMarkerSize((short)5);
condition2.setMarkerShape(MarkerShape.TRIANGLE);
condition2.getCondition().setFrom(80);
condition2.setText("Overqualified");
chart1.getConditionalAttributes().add(condition2);


Per-Point Attributes

In some cases, you can’t use the ConditionalAttributes object to change the attributes of a particular point or set of points. For example, if you want to make the odd and even points look different, the ConditionalAttributes objects can’t be used. For such situations you can use the PointAttributes object.

The PointAttributes object exposes many of the same properties available in the Chart object. Once again, giving the developer access to the point object increases the control over charts generated using Chart FX 7 for Java Desktop. The supported PointAttributes object members allow you to set border, color, marker, point label and scheme attributes, as well as many others, directly to a selected point included in the chart.

Setting per-point attributes is most useful for highlighting special points or groups of points within charts. By highlighting selected points in a chart, you can focus the attention of end users to specific information conveyed in the chart. Another useful tool when setting per-point attributes is the user legend box. The user legend box is configured exclusively by the developer and can act as a legend for these special points.

The following set of API calls sets the color to red and the marker shape to triangle, for a particular point:

/* Setting the Point */
chart1.getPoints().get(0, 5).setMarkerSize((short)5);
chart1.getPoints().get(0, 5).setMarkerShape(MarkerShape.TRIANGLE);
chart1.getPoints().get(0, 5).setColor(java.awt.Color.RED);
chart1.getPoints().get(0, 5).getBorder().setVisible(false);
chart1.getPoints().get(0, 5).setText("My Custom Item");
/* Setting the Legend      */
chart1.getLegendBox().setVisible(true);
CustomLegendItem customItem;
customItem = new CustomLegendItem();
customItem.setAttributes(chart1.getPoints().get(0, 5));
chart1.getLegendBox().getCustomItems().add(customItem);


Data compacting

Many times charts contain a large amount of data whereby visualizing such data via a chart has little or no value. For example, you may have the number of sales per day for all 365 days of the year however seeing a trend from month to month is very difficult due to the busy and excess information in the chart. Instead you can use Chart FX Data Compacting feature to provide meaningful summarized data.

Predefined Formulas

When compacting data, the data will require summarization of some form. Chart FX allows you to specify how to summarize data in the form of a DataCompacting formula. For convenience, Chart FX provides predefined formulas for popular compacting schemes such as First, Last, Min, Max, and Average.

Here is a sample how to compact 10 bars into 5 by grouping them into 1 bar for every 2 bars. By default, Chart FX utilizes the CompactFormulas.Min.

Here is the original chart for the sample chart of 1 series and 10 points.

chart1.getData().setSeries(1);
chart1.getData().setPoints(10);
chart1.setGallery(Gallery.BAR);
chart1.getLegendBox().setVisible(false);
int i = 0;
for(i = 0; (i < 10); (i)++);
{
    chart1.getData().set(0, i, ((double)(10 + i)));
}

After applying the following code, the result chart provides summarized data compacting every two bars into one and producing a new bar which is the minimum Y value of both bars.

chart1.getData().setSeries(1);
chart1.getData().setPoints(10);
chart1.setGallery(Gallery.BAR);
chart1.getLegendBox().setVisible(false);
int i = 0;
for(i = 0; (i < 10); (i)++);
{
    chart1.getData().set(0, i, ((double)(10 + i)));
}
chart1.getData().Compact(2.0);

Note:

You must specify the formula prior to calling compact if you intend to use another predefined formula as shown below.

chart1.getData().getY().setCompactFormula(CompactFormulas.getMax());
chart1.getData().compact( 5 );


Overview

Chart FX allows developers to create visually rich, highly interactive charts with data analysis capabilities that go far beyond simple tooltips and dialogs. This User Interface not only reveals important trends in the chart’s underlying data but will also allow developers to build effective data visualization applications quickly and effortlessly with no complex code to write or maintain. For example, with a simple property setting developers can make charts scrollable, zoom in portions of the charts or even display a full data grid with the chart’s underlying data.


Basic UI Functionality

Toolbar and Menubar

One of the most useful tools in Chart FX is the Toolbar; many developers appreciate this UI element because they are not required to add additional lines of code in their web based applications to give end users more freedom to customize their charts.

By default, the Chart FX Toolbar provides the most common options used by an end-user, such as switching from 2D/3D, color change, zooming & rotation and show/hide tools like data editor and legends. However, it can be completely customized by the developer according to application and user needs, by adding or removing buttons from the Toolbar and even changing the tooltips displayed by the buttons.

chart1.getToolBar().setVisible(true);

The Chart FX Menu Bar provides the same options as those found in the Toolbar. The Menu Bar is often utilized when the application already has a Toolbar displayed. The following picture depicts a chart with a Menu Bar.

chart1.getMenuBar().setVisible(true);

Changing Underlying Data Using the DataGrid

Although Chart FX is mostly used as data visualization (read only) solution, there are ways end users can edit or change the underlying data in the chart. As a developer you must decide whether these changes should be reflected in the data source as Chart FX will simply trigger an event (DataChangebyUser event) that you can capture in your application to further process these changes in the data (For example, update the data source).

The first technique involves enabling the Data Grid to accept changes in the data. This can be done by using the setAllowChanges method. The end user will simply double click a value in its corresponding cell and the Data Grid will allow editing. After the value is changed, the chart will immediately repaint reflecting the change made by the end user.

chart1.setAllowChanges(java.util.EnumSet.of(AllowChanges.ALL));

Exporting Charts to other Applications

The Chart FX UI allows the user to copy both the chart image and its data to the clipboard as bitmaps and text respectively.

Zooming

The Chart FX Toolbar provides a button for zooming which is useful when details are hidden by large amounts of data. By simply selecting desired zoom level, the end-user will be able to zoom in to view details. When zooming is applied, the boundaries of the chart will change and scrolling will be enabled for access to other areas of the chart. The zoom tool can be used repeatedly in succession until the user reaches the desired zoom level.


Tooltips

Tooltips appear when the user to hovers the mouse over a chart element and are used to expose additional information about it. This is especially important in charts with many points, as the tooltips provide a means for discerning values in the chart.

Chart FX provides smart tooltips; which change according to the gallery type being displayed. For example, in a simple bar chart, the tooltip will show the bar value, while in a financial chart the tooltip will show the High, Low and Close values. Similarly, in a pie chart, Chart FX’s tooltip will show not only the value for a particular slice, but also its percentage of the total pie, as depicted in the following figure:

Tooltips can also be customized through the use of a mask. The following image shows an example of a tooltip customization:

chart1.setToolTipFormat("This the point %N of series %S");

If you want to disable tooltips, all you need to do is use the following code:

chart1.setToolTips(false);


Scrolling

Although Chart FX provides a wealth of properties to control how labels are displayed on axes, the number of data points and the chart size become important factors as to how many labels could fit along an axis or how much data is actually visible. In other words, some charts simply have too much data for the desired chart size and little can be done to improve the chart’s readability.

Chart FX provides an elegantly designed scroll bar, which attached to an axis, allows end users to zoom in and view portions of an entire chart. All axes in Chart FX support scrolling.

To enable scrolling you must enable the Chart object scrollable property using the following API call:

/* Set AxisX AutoScroll true */
chart1.getAxisX().setAutoScroll(true);
/* Set AxisY AutoScroll true */
chart1.getAxisY().setAutoScroll(true);

The scroll bar will appear docked right next to the axis labels as depicted in the figure. The user can now drag the scroll bar to a desired position in the chart.

By using the scroll bar, the data points will not be crunched inside the chart area and most points can show their respective labels. This enhances the chart’s readability and allows the end user to view portions of the chart at a time.

Controlling the Scroll Position Programmatically

Although the scroll bar is an end user tool, you may want to control the number of points visible in a specific chart. This can easily be done with the SetScrollView method supported by the Axis object.

For a categorical axis, this method receives the index of the points you want to see in the chart. For example, if you have 300 points and you want to force Chart FX to show points 30 to 60 in the categorical axis, you can set the SetScrollView method as follows:

chart1.getLegendBox().setVisible(false);
chart1.setGallery(Gallery.SCATTER);
chart1.getData().setSeries(1);
chart1.getData().setPoints(300);
java.util.Random r;
r = new java.util.Random(1);
int i = 0;
for(i = 0; (i < 300); (i)++);
{
    chart1.getData().getY().set(0, i, (100.0 * (r.nextDouble())));
}
chart1.getAxisX().setAutoScroll(true);
chart1.getAxisX().SetScrollView(30.0, 40.0);

For a numerical axis, the SetScrollView method receives the values to be shown in a specific scroll view. For example, if your numerical axis is scaled between 0 and 300 and you want to set a scroll view between 10 and 50, you can set the ScrollView method as follows:

chart1.getLegendBox().setVisible(false);
chart1.setGallery(Gallery.SCATTER);
java.util.Random r;
r = new java.util.Random(1);
int i = 0;
for(i = 0; (i < 300); (i)++);
{
    chart1.getData().getY().set(0, i, (300.0 * (r.nextDouble())));
}
chart1.getAxisY().setAutoScroll(true);
chart1.getAxisY().SetScrollView(30.0, 40.0);

Similarly, Chart FX will dispatch an event called UserScroll every time the user interacts with the axis scroll bar. This event is useful if you need to synchronize several charts as the user interacts with a scroll bar.

Refer to the Chart FX API Reference for more information on the UserScroll event supported by Chart FX.


Annotations

Chart FX provides an Annotation Extension to allow the inclusion of floating objects in the chart. The Annotation extension supports a Toolbar so end users can create objects and highlight different areas in the chart without additional programming efforts. This means end users will be able to add text, arrows, geometrical shapes, and even images they can freely move around to highlights specific data points or sections in the chart area. End users can also rotate, group and even flip annotation objects.

In order to enable to the annotation Toolbar, you must create an annotation extension object, set the setEnabledmethod to “True", add the newly created object to the chart and set the Toolbarto True. Below is an example of the annotation extension and some objects, as well as the required set of API calls to enable it:

Annotation.Annotations annots;
annots = new Annotation.Annotations();
chart1.getExtensions().add(((java.lang.Object)annots));
Annotation.AnnotationArrow arrow;
arrow = new Annotation.AnnotationArrow();
arrow.setHeight(100);
arrow.setWidth((short)-40);
arrow.Attach(2.0, 50.0);
annots.getList().add(((Annotation.AnnotationObject)arrow));
Annotation.AnnotationText text;
text = new Annotation.AnnotationText();
text.setText("This is an Annotation Text");
text.setTop(120);
text.setLeft(100);
annots.getList().add(((Annotation.AnnotationObject)text));
chart1.getLegendBox().setVisible(false);

The Annotation extension also exposes an Object Model that you can use to add and manipulate any annotation object programmatically. This is particularly useful when you want to draw anything on top of a chart and that is not supported using the API exposed by Chart FX. For example, if you want to add a company logo to any section in the chart you can easily use a picture object available in the Annotation extension. For additional information on examples using the Annotation extension programmatically, please consult the samples included with your installation of Chart FX 7 for Java Desktop.


Printing

The end user is able to print a hardcopy of the chart within the application. Chart FX provides an integrated printing mechanism available to the end user through the Toolbar.

The MenuBar also exposes Print Preview option as seen in the following images:

Chart FX also exposes the Printer object for a high level of customization. For details about the use of the Printer object, please consult the API reference.


DrillDown

Charts are an excellent visual navigational tool. Imagine delivering a system or application that puts summary level information into a chart and lets end users click on chart elements to drill down. End users can dive into the details, instantly create other graphs, or view news stories or abstracts that pertain to selected chart elements or markers.

Unfortunately, all this can’t happen without the developer’s intervention. In other words, you must instruct Chart FX what to do or where to go when an end user clicks certain chart elements. For this reason, there’s basic programming you must do in order to achieve drilldown.

Implementing Drilldowns

Implementing a drilldown in the chart involves capturing mouse events such as click and double click. When that event happens the developer will receive specific information about the point where the click happened (series, point, value, etc). Based on that information the developer can determine how the chart should behave.

Take, for instance, a pie chart with 3 slices. Each slice of the pie represents an employee, where the size of his/her slice represents their contribution to total sales (in percentage).

Suppose we would like to display more information on the employee when we click on his/her slice. By handling the mouse click event we can find out which point of the pie was clicked and rebind data to the chart that represents that particular point.

To make this work, we need to first add a MouseClickListener to our chart.

chart1.addMouseClickListener(new MyMouseClickHandler());

Now we must create a class that implements the HitTestListener interface. Inside our class we have the event handler (hitTestEventHandler), where we have information on where the click happened.

    public class MyMouseClickHandler implements com.softwarefx.chartfx.desktop.HitTestListener
    {
        public void hitTestEventHandler(HitTestEvent evt)
        {
            System.err.println(evt.getPoint());
            System.err.println(evt.getSeries());
            System.err.println(evt.getValue());
        }
    }

For more information about the HitTestEvent class and it’s methods, please refer to the API.


Chart Export

Chart FX provides the Export method that enables you (or your end users) to save chart files, images and data in a variety of formats.

There are also other file types in Chart FX called "Chart Templates" that allow you to save the appearance (Colors, Chart Types and Styles, Visible Tools, etc.) of the chart in a file so you can later apply it to another chart. This allows you to reuse code instead of setting the same attributes for all of your individual charts.

Note:

Templates save all the information that is not data related. This means, it will not save the values, number of series or points, or any other property related to this data, such as MultiType settings and Min, Max values in the chart axes.

File Formats

The following file formats are supported by the Export method:

Binary: Exports and imports chart settings to a binary file. BinaryTemplate: Exports chart settings to a binary file with 'Template' pre-assigned, using the FileMask property. XML: Exports chart settings to an XML file. Text: Exports chart data to a Text File. Bitmap: Exports the chart as a Windows Bitmap. JPEG: Exports the charts as a JPEG image PNG: Exports the chart as a PNG image

The Export Method

This method is used to export the chart data and/or set properties to the clipboard, file or stream in different formats. Check the API reference in your Resource Center for details on the different overloads supported by this member.

chart1.exportChart(FileFormat.BITMAP, "c:/image.bmp");

Filecontents

Whether you are saving chart files in Binary or XML format, you can control what is saved in the file by manipulating the FileContents property. The Binary format will save visual attributes and data; XML will save only visual attributes.

This property is particularly useful because it allows you to customize how chart files are saved. This way, you can build your own chart templates. By default, this property is set to save all visual attributes including the data.

However, if you want to save everything but the titles in the chart, this could be done by simply excluding the Titles using the setFileContents method(). Please see your API Reference in the Resource Center of your installation for details on using this property.

chart1.setFileContents(java.util.EnumSet.of(FileContents.TITLES));


Customizing the Toolbar

The Chart FX Tools provide an easy way for users to access the supported commands. However, if you plan to restrict access to any of those commands, keep in mind there are many ways to access any one command. For example, an end user may select the gallery command via the Toolbar, menubar or right-click context sensitive menus.

This introduces an additional level of complexity as customizing only the Toolbar does not mean other tools are not exposing the same command. For example, if you do not want end users to select an area chart, you may end up changing the Toolbar, menubar, the right-click menus, or any other tool the Area button may appear in.

To increase control over these commands, Chart FX introduces the Commands object. The Commands object contains all the Chart FX commands available and their definitions (picture, text, etc). This allows the developer to remove or disable a command once. This will affect all the tools used to create and display the user interface for Chart FX.

Other important properties supported by the Chart FX API are the chart object ToolbarObj and MenuBarObj properties which allow a programmer to control Toolbar and menubar positioning, visual attributes and command customization.

Relationship between the Commands & Toolbar Objects

When customizing the Toolbar, it is imperative you understand the relationship between the Commands and Toolbar objects.

When it comes to changing general settings, such as position, visual attributes and visibility, the supported members of the Toolbar object should be used.

On the other hand, if you want to customize items (buttons) in the Toolbar, many of the features you may want to change (ToolTips, Picture, etc) are configured using the members of the Commands object. Items accessed using the Commands object are usually available to any of the Chart FX Tools.

In the following figure, many of the important visible attributes for a particular button in the Toolbar like text, picture (icon), and style are controlled by the Commands object and not by the Toolbar object.

Showing/Hiding the Toolbar

The Toolbar object exposes the setVisiblemethod allowing you to show or hide a selected Toolbar in the chart. This Boolean property may be accessed using the API as follows:

chart1.getToolBar().setVisible(true);
chart1.getMenuBar().setVisible(true);

Positioning the Toolbar

The Toolbar object exposes several members allowing you to position the Toolbar in the chart's bounding rectangle. By default, the default position of the Toolbar is docked to the top margin. However, by using the Docked property you can position the selected Toolbar anywhere in the chart. For example, if you want to dock the Toolbar to the left margin programmatically, you can use the Docked property as follows:

chart1.getToolBar().setDock(DockArea.BOTTOM);

Removing Items from a Toolbar

You may want to remove buttons in the Toolbar as a result of a specific condition in your application. For example, you may not want the end user to switch between 2D and 3D modes therefore you can remove that button in the Toolbar. Or, you may want to allow users to save or open chart files. In this case, you can remove those buttons from the Chart FX Toolbar.

The Toolbar object supports the RemoveAt method to remove one or more items in the Toolbar. When using this method, be aware removed buttons will no longer exist in the Toolbar and all the indexes will be recalculated by Chart FX. For example, if you remove the first button in the Toolbar using the RemoveAt method, the index of the second button will become index 0, the index of the third button will become index 1, and so on.

The RemoveAt method accepts 2 parameters; the first parameter receives the position from where to start removing items and the second parameter specifies the number of items to remove. Also, be aware vertical separators count as additional Toolbar items, so if you plan to remove several buttons and they are separated, you must include the separators when calling the RemoveAt method. The RemoveAt method may be accessed as follows:

chart1.getToolbar().removeAt(iPosition);

Changing Functions of Existing Toolbar Items

Chart FX exposes a wide variety of pre-defined commands you can use to overwrite the functionality of buttons of the default Toolbar. New buttons can also be added to the Toolbar configured to perform such actions. Not only can you use existing commands Chart FX includes, but custom commands may also be created and processed internally by your application.

The CommandID enumeration allows you to easily overwrite the default actions performed by a Toolbar button (item) with any of the pre-defined Chart FX commands. For example, the Print button in the Chart FX Toolbar allows the end user to print the chart. This button prompts the user with a dialog where they can select the number of copies and their printer. There may be a case where you do not want the users prompted by this dialog. The Chart FX pre-defined commands include a print command to print a chart without prompting the user for any additional settings.

In the following sample, the default "Print with Printer dialog" command for the Chart FX Toolbar will be changed to the "Print without Printer dialog" command. Before you can change the command, you must determine the index of the print button item in the Toolbar.

As you can see, the print icon in the Toolbar is the third item visible; therefore, the index of the item is 2. Since we have established the index of the print command in the Toolbar, we can now assign the "Print without Printer dialog" command to that position. This may be done by configuring the Toolbar item index to the selected CommandID you wish to display in that position. See the API Reference for details.

Inserting Items in the Toolbar

There may be a situation where you want to include additional items in a selected Toolbar. To allow this, the Toolbar object exposes a method called Insert. This method allows you to insert additional command buttons to the Toolbar you can configure to execute existing Chart FX commands or a custom command you may want to include in your application.

Chart FX exposes a wide variety of pre-defined commands through the CommandID enumeration. As stated earlier, these commands can be used to overwrite the functionality of existing buttons in the Toolbar or to assign actions to newly added buttons.

When adding buttons, be aware the Chart FX Toolbar can handle up to 32-items (including buttons and separators), so when adding buttons in the Toolbar, be careful not to exceed that limit. Let's suppose you want to limit the number of available gallery types the end users may select from in a particular chart. The only gallery types you want to grant access to, are the Line, Area or Bar types. You decide you want to remove the default gallery command from the Toolbar, and add three additional buttons in the Toolbar to select from the desired chart types.

The first thing you need to do is remove the gallery selector by using the RemoveAt method, covered earlier in the "Removing Buttons from a Toolbar" section. The gallery selector may first be removed using the RemoveAt method as follows:

chart1.ToolBar.removeAt(iPosition);

Once you have removed the gallery selector from the Toolbar, you will want to insert the desired gallery commands into the Toolbar. In order not to overwrite other commands in the Toolbar, you will need to insert some "place-holders" for the additional gallery commands. The Toolbar object provides the insert method allowing you to specify the index of where you would like to insert items into the Toolbar as well as the number of items you would like to add. Then, using the getToolbar method, you can specify the indices of the empty Toolbar items to selected Command bar Items (CommandID enumeration). Visit the API Reference for details.

chart1.ToolBar.insert(iPosition,toolBarItem);

When you use the insert method, the indexes for other buttons in the Toolbar will be recalculated appropriately. In other words, because we have added 3 buttons at the beginning of the Toolbar, the index for the button previously located in the first position is no longer 0 but 3, and the buttons we have added will have the 0,1 and 2 index respectively.

Note:

Modifying just the Toolbar is no guarantee the end user can only switch to those 3 chart types. The above example shows how to use the insert method to add buttons to the Toolbar. If you really want to prevent the end user from switching to other chart types, you have to modify the Commands list appropriately so those chart types may not be accessed from another tool in the Chart FX UI.

Modifying ToolTips

A tooltip is the text appearing when the user positions the mouse over any button in the Toolbar. This is very helpful as it informs the end user about the functionality of the button, without actually pressing it and performing the action.

You may think this tooltip is part of the Toolbar; however, this text is also used in other parts of the Chart FX UI and therefore is controlled by the Commands object. Therefore, when you change the tooltip associated with a particular command, this change will be consistent throughout the Chart FX UI. Another point to keep in mind when changing the tooltip the text can be displayed somewhere else such as the menubar or context menus. Therefore, you must be careful not to make those tooltip strings too long or it will not be readable elsewhere.

To change the tooltip associated with a particular command, you must first identify the command ID for the command you wish to modify. For example, if you want to change the tooltip for the Gallery selector, you would reference the gallery enumeration (CommandID.Gallery). Once the desired command is referenced, you can set the text property for the command to modify the tooltip:

chart1.getCommands().add(new Command(20));
chart1.getCommands().get(20).setText("My Command");
chart1.getToolBar().get(1).setCommandId(20);
chart1.getToolBar().setVisible(true);

Changing Toolbar Icons

The entire collection of Chart FX tools shares the same icons used in the Toolbar; therefore, the Commands object controls them. When you change an icon for a particular command, the change will be reflected in all of the other tools allowing access to that command. For example, the Data Grid icon is used in the Toolbar as well as the right-click context menus. When you change the icon associated with the Data Grid command, both tools will reflect the change.

Any command may be assigned a pre-defined Chart FX icon from the icon list or a custom icon you add to the pre-defined list. This section will explain how to do both.

Selecting a Pre-Defined Icon Chart FX provides a pre-defined list of 16x15 icons used for all the pre-defined commands. You can assign these pre-defined icons to other commands throughout the Chart FX user interface. To do this, the Commands object supports the setImageIndex method. Setting this methodto the index of a desired icon in the icon list, will assign that icon image to the referenced CommandID. Below is an example of the pre-defined icon list:

To change the Gallery command icon to the ‘File’ icon (index 1 in commands picture), you would use the following code:

CommandCollection cmds;
cmds = chart1.getCommands();
cmds.add(new Command(20));
int nPict;
nPict = cmds.AppendImage(new javax.swing.ImageIcon(myImagePath));
cmds.get(20).setImageIndex(nPict);
chart1.getToolBar().get(1).setCommandId(20);
chart1.getToolBar().setVisible(true);

Adding and Replacing Command Icons

Selecting an icon from the pre-defined list is not particularly useful because most of them are used by other Chart FX commands. This can cause confusion for the end user because the icons will not be unique to the function of a particular command. The AddPicture and ChangePicture methods may be used to add and replace icons in the pre-defined icon list.

The AddPicture method is particularly useful when you are adding custom commands to the Chart FX UI. This method will append one or more icons to the pre-defined icons list you can use to assign to existing or new commands. The ChangePicture method is most useful when you want to change icons already being used by Chart FX.

This method allows you to replace all or part of the existing icons list. When adding or replacing any image in the icon list, it is very important your custom icons are the proper dimensions (16X15 pixels). When adding multiple icons you must ensure there are no spaces between the custom icon images.

AddPicture Suppose you have two new icons you want to add to the icons list. Both of these icons are placed into a single bitmap file. Once you have added the new icons, you want to assign the first icon to the 'Gallery' command and the second for the 'PrintDialog' command. The AddPicture method returns and integer specifying the index position where the icons were added to the list. This reference can be used when assigning the new icons to the desired command using the Picture property. Visit the API Reference for details.


Working with Subcommands

Although most buttons in the Chart FX user interface (Toolbar, MenuBar, etc) perform a specific action when pressed, there are other buttons presenting a list of subcommands, where one may be selected. For example, the Personalization button in the Chart FX Toolbar presents another list allowing the user to select personalization preferences, as depicted in the following figure:

These are called Subcommands lists and you can create or modify existing subcommands lists in the Chart FX user Interface. For this purpose, the Commands object exposes methods to access the SubCommandID property as well as the RemoveSubCommand and RemoveAllSubCommands methods.

Removing existing Subcommands

In the figure shown above, you can see how the Personalization Options command presents a list of subcommands allowing the end user to select which preference to apply to the chart. Let's suppose you want to remove end user access to the 'Restore Defaults' subcommand selection. You can easily remove that option from the Personalization Options subcommand list by invoking the RemoveSubCommand method. By specifying the Personalized Options CommandID in the Commands property, you can remove items from the options list.

chart1.getCommands().get(0).getSubCommands().RemoveAt(0);

When you remove a particular subcommand from the subcommand list, the indexes will be shifted to the actual number of subcommands available in the command. For example, if you wanted to remove the 'Remove Defaults' subcommand and the separator above it, you would need to remove the same index twice.

You can also remove all subcommands from a command list by using the Clear method:

chart1.getCommands().get(commandIndex).getSubCommands().clear();

By removing a subcommand from the list, you will also remove this option from other tools using the same command ID.

Adding Subcommands

To add a subcommand to a list you will use the SubCommandID property. If you are adding subcommands to a specific command you must make sure to keep the indexes in order as non-consecutive indexes may cause unpredictable results.

This feature is particularly useful when you are working with custom commands. For more information, refer to the "Adding Custom Commands" chapter below, where we show a custom command containing several subcommands.

Working with Selectors

A selector is a command containing a list of subcommands; when pressed, a list of images (icons) will be shown so the user can make a selection and when closed the selector will show the current selection. In Chart FX, the gallery icon in the Toolbar is a selector as shown in the following figure:

The only notable difference between selectors and regular subcommand lists is the style for the subcommand has been set to 'Selector'. For more information on controlling the style for a particular command, refer to the setStyle method in the commands object.

Adding Custom Commands

In previous topics you learned the API provided by the Toolbar and Commands objects to add, remove or modify the Chart FX pre-defined list of commands. This was useful as you were able to customize the default Chart FX Toolbar, by removing existing commands, changing the icons and other important aspects related to the Chart FX User Interface.

Chart FX not only allows customization of the default Toolbar with pre-defined Chart FX commands, but it allows you to add custom commands you can process internally in your application.

Let's say, for example, you want to add a button in the Chart FX Toolbar that when pressed loads another chart with new data and new visual attributes. It is clear Chart FX will not provide this functionality as a pre-defined command because it will not know how to react when end users actually press such a button. Therefore, you'll need to add a custom command to give you the desired results.

Furthermore, you can also create groups of buttons, lists and selectors that will seamlessly integrate into your application. This section explains the necessary steps to add custom commands to the Chart FX User Interface.

Adding a custom command to the Toolbar means setting the correct attributes using the Commands object and then using the methods provided in the Toolbar object to physically add (or replace) that button in the Toolbar.

The following are the steps you need to follow to add a custom command to the Chart FX Toolbar:

Add the Command ID to the Chart FX Commands list The very first step to add one or more custom commands to the Chart FX UI is to add their IDs to the Chart FX Commands list using the AddCommand method supported by the Commands object.

The ID is an integer used to identify the command when the user presses or interacts with it. This is a unique ID associated to the custom command and should never be duplicated for use with another command. Chart FX defines its pre-defined IDs between 'CommandID.First' (29440) and 'CommandID.Last' (29951), so make sure you avoid a number in this range as it will cause unpredictable results.

Setting the Visual Attributes of the Custom Command Once the Command ID has been added to the list, you must instruct Chart FX how to display this command in the UI. Will it be a button or a list? What will be the icon used? What is the text to be displayed? Is it enabled by default?

There are methods to set and get the properties corresponding to each particular attribute in the commands object as shown in the following API:

Style. The Style method allows you to tell Chart FX if the command you're adding is a two-state button, a list, a selector, or if the command belongs to a group. If you do not set the Style property, the custom command is added as a regular button.

Picture. The Picture property allows you to specify the icon to be used in the button. You can add your own buttons as described in the "Changing/Adding icons" section.

Text. The Text property allows you to set the tooltip to be displayed, or the text if the command is to be shown in the menubar. For example, to set a new tooltip to the button you can set the Text property.

CommandCollection cmds = chart1.getCommands();
cmds.add(new com.softwarefx.chartfx.desktop.Command(20));
javax.swing.ImageIcon ii = new javax.swing.ImageIcon("C:/icon.png");
java.awt.Image img = ii.getImage();
int nPict = cmds.appendImage(img);
cmds.get(20).setImageIndex(nPict);
cmds.get(20).setStyle(java.util.EnumSet.of(CommandStyles.SMART_LIST));
cmds.get(20).setText("My Command");
cmds.get(20).setEnabled(true);
cmds.get(20).setChecked(true);
chart1.getToolBar().get(1).setCommandId(20);
chart1.getToolBar().setVisible(true);

Adding the Custom Command to the Toolbar To add the custom CommandID to the Toolbar, you can use the Insert method and the CommandID properties exposed by the Toolbar object. Visit the Resource Center and API reference for detailed samples.

Processing the Custom Command Since you have added a Custom command to the Chart FX commands list and the button has been added in the Toolbar, you need a mechanism to add your custom code to processes that particular command. The UserCommand Event is posted to your application when the user clicks or interacts with the custom command you have added. So if you want to change the chart gallery to lines when the user presses the button, you will process the UserCommand event.

Customizing Context Menus

Each Chart FX context menu has its own CommandID and is comprised of a list of subcommands. Custom, as well as pre-defined, subcommands may be added or removed from selected context menus by utilizing the supported members of the CommandBar and Commands objects.

There are context menus for the axes, background, constant line, series, stripe, title and Chart FX tools. By selecting a particular context menu, you can add or remove commands from the context menus to control the options users have access to when selecting a menu on demand for a particular chart element.

The UserCommand Event is raised in your application when the user clicks or interacts with the custom command you have added. Using the UserCommand event, you may process custom commands you add to your applications.