Copyright: Copyright ¸ 1995-2000 by David Berneda


Welcome to TeeChart
	TeeChart Pro v5 VCL Version
The 100% Native Data-Aware Charting Component Library for Borland Delphi and C++ Builder*

What's new !

Component reference

User guide

License & disclaimer

More about TeeChart...

Steema SL

Programming environments

TeeChart Copyright © 1995-2000 David Berneda. All rights reserved.

* Borland Delphi and C++ Builder copyright of Borland International, Inc.


TeeChart Pro

TeeChart Pro order information	License and disclaimer

TeeChart Pro is a comprehensive charting tool aimed at those developers wishing to program with or make use of extended TeeChart functionality. TeeChart Pro includes the option to purchase 100% source code.

Select this link to see What's new  in TeeChart 5 Pro.

Features of TeeChart Pro v5:

100 % Source code available

32 - bit version for Delphi 3 and later and Borland C++ Builder 3 and later

18 Palette components including ChartGrid, Navigators, Web source and Control Bar

12 standard Series types

11 Extended Series types

9 Statistical Series types

2 Financial Series types

10 additional Series types

8 Standard Statistical function types

9 Financial Statistical function types (includes Bollinger, ADX, MACD and more..)

7 Extended Statistical function types

10 Chart tools

Data aware with Summary grouping and orderable data

Series Gallery

Very Fast ! TeeChart now fully utilises dynamic arrays of your data

2D, 3D plus OpenGL 3D with 360º rotation

Numerous new features to facilitate web charting

Chart Export formats: Native tee, PNG, GIF, BMP, WMF, EMF, JPEG, PCX

Data Export formats: Native tee, Text, XML, Excel, HTML table

Unlimited Custom Axes at design and runtime

Chart Data Grid

QuickReport Integration

Zoom, scroll and real time

Royalty free for exe distribution

Custom drawing canvas

Custom printing

Extensive demos

Design and runtime integrated Chart and Series editor

New improved Online help

Electronic reference manual (hlp format)

Custom Series build

Sample Custom Series and Functions

Many new visual features, Transparency, 3 colour gradients

Many other improvements everywhere !


About us...

TeeChart Pro

TeeChart charting components have been written in Delphi by David Berneda. They are 100% Delphi Native VCL compliant. TeeChart products are distributed and supported by Steema SL. of Barcelona, Catalonia, Spain.

Please email the following address for questions:

email address: info@steema.com

www: http://www.steema.com

Address:

Steema SL.

Emili Grahit 31 E-D

17002 GIRONA

CATALONIA, (Spain)

Tel. +34 97 221 87 97

Fax: +34 97 221 87 18


TeeChart version 5
TeeChart license and disclaimer

TeeChart Pro	About

License

License Terms:

-- A Single License of TeeChart Pro v5 VCL is per developer.

-- A Site License of TeeChart Pro v5 VCL is per

   "physical place" with unlimited number of

   developers under the same company building(s).

-- TeeChart Pro v5 VCL is royalty free (see below).

-- For special licensing issues, volume discounts, integrations

   or redistribution please contact us at: sales@steema.com

TeeChart Pro v5 is royalty free:

You can freely distribute TeeChart Pro code COMPILED into your applications as executables or dynamic link libraries, including as OCX ActiveX Controls or ActiveX Forms, but not including as design-time packages. If compiled into a DLL or OCX and used in a Web server scripting environment a WebServer runtime license should be registered.

You are NOT allowed to distribute stand-alone TeeChart Pro files, TeeChart Pro source code, TeeChart Pro manual and help file or everything else contained in this software without giving our written permission.

Disclaimer

The Author cannot and does not guarantee that any functions contained in the Software will meet your requirements, or that its operations will be error free.  The entire risk as to the Software performance or quality, or both, is solely with the user and not the Author.  You assume responsibility for the selection of the component to achieve your intended results, and for the installation, use, and results obtained from the Software.

The Author makes no warranty, either implied or expressed, including without limitation any warranty with respect to this Software documented here, its quality, performance, or fitness for a particular purpose. In no event shall the Author be liable to you for damages, whether direct or indirect, incidental, special, or consequential arising out the use of or any defect in the Software,  even if the Author has been advised of the possibility of such damages, or for any claim by any other party.

All other warranties of any kind, either express or implied, including but not limited to the implied warranties of merchantability and fitness for a particular purpose, are expressly excluded.


TeeChart help sources

Please look in the ‘Info sources’ document (TeeChart Pro Introductory Guide) for a complete listing of current information and help sources.


TeeChart Component Reference
Component Reference

Quick Start	About..	Contact us..

The main TeeChart component is: TChart.

TChart is a placeholder for TChartSeries components. TChart is derived from TPanel component, and inherits all its functionality.

When you place a TChart component in a Delphi Form, you will see a standard TPanel with an upper title and a lower foot text.

Right click on the Chart to see the opening TeeChart menu where you can select the Chart editor alternatively double-click to directly call the Chart editor.

The Chart editor presents Chart configuration options and the TeeChart Gallery which contains access to all data series types. Data series types are subcomponents that can be accessed and manipulated independently of the Chart and are accessible across Charts.

For Database charts, you need to use: TDBChart

Place one or more series in the Chart and either connect to a DataSource or write your own code to populate the series.

Key palette components

 TChart

 TDBChart

 TQRChart


Programming environments

TeeChart Pro order information	TeeChart Pro

TeeChart is written as a 100% Delphi native VCL.

TeeChart and TeeChart Pro v4 support:

Delphi1: 16bit version

All other versions of Delphi to Delphi v5: 32bit version

All versions of C++Builder to C++Builder v5: 32bit version

TeeChart Pro v5 supports:

Delphi v3 to Delphi v6: 32bit version.

C++Builder versions 4 and 5: 32bit version

There is no 16bit version of TeeChart Pro v5


TeeChart Whats new
What's new !

The new version of TeeChart Pro adds many new features, many new enhancements to existing features, new components, new series types, new editor dialogs and some fixed bugs.

New features by Category:

•	Chart Canvas, Walls, Axes, Titles and Footers

•	Chart Legend, Events, Zoom and Print Preview

•	Database Charting

•	New Chart Tool components

•	Chart Editor dialog

•	Chart Grid

•	Web Charting

•	New Functions

•	Series Values

•	New features in Series types

•	New Series types

•	Chart Gallery

•	Actions (VCL only)

•	Exporting

•	OpenGL 3D

•	Miscellaneous


New v5 Canvas
New v5 - Chart Canvas, Walls, Axes, Titles and Footers

Canvas

•	In orthogonal 3D mode, you can specify the Orthogonal Angle

•	Gradients can include a Middle color (3 color gradients)

•	The 3D rotation center can be specified.

•	Big non-solid pen lines (more than 1 pixel) (only in Windows NT and 2000)

•	Additional Brush styles (patterns)

•	Cone shapes

•	Truncated pyramids.

•	Transparency.

Walls

•	Right wall

•	Back wall can be filled using a Gradient or a image.

Titles and footers

•	New SubTitle and SubFooter objects

•	Custom positioning of Titles and Footers

•	OnClick event

•	Additional formatting properties (font shadow, gradient, bevels, etc)

Axes

•	Grids can be displayed in front of Series.

•	Minor grids

•	Custom axes can be manipulated at design-time using the editor dialog.

•	Axis Title has a Visible property.

•	Axes Labels can display Milliseconds, also Exponent Superscripts

•	Axes Labels can be left-aligned.


New v5 Legend
New v5 - Chart Legend, Events, Zoom and Print Preview

Legend

•	Custom positioning

•	Text alignment and columns width

•	Check boxes to select Series

•	Background brush image

•	Vertical spacing

•	Symbols configuration

•	New Legend styles

•	Show current page only

•	Font Series color style

•	Additional formatting properties (gradient, bevels, font shadow, etc)

•	Choose the displayed series

•	Multiple Legend on the same chart

•	Drawing additional text

Events

•	OnBeforeDrawChart

Zoom

•	Pen and Brush

•	Minimun pixels

•	Direction

Printing and Print Preview

•	Multiple Charts at Print Preview


New v5 Database
New v5 - Database Charting

•	Better Speed when loading datasets.

•	Summary Grouping

•	Sort order

•	Locating records

•	ADO support


New v5 Tools
New v5 - New Chart Tools

•	Cursor

•	Drag series marks

•	Axis arrow

•	Draw line

•	Nearest point

•	Mark tips

•	Color band

•	Color Line

•	Rotate

•	Image

•	Axis labels


New v5 Editor
New v5 - Chart Editor dialog

•	New tabs everywhere

•	New tab for Chart Tools

•	New tab for Chart Grid

•	New tab for Print Preview

•	Resizeable dialog.

•	Insertable in forms


New v5 Grid
New v5 - Chart Grid

Chart Grid

A new visual component (grid) to display Chart series data.

•	Shows all series in a Chart or a single series only

•	Read-write or Read-only mode

•	Shows or not series labels (text)

•	Includes a ChartGrid navigator toolbar with buttons

VCL note: ChartGrid component derives from TStringGrid class.

Example:

ChartGrid1.Chart := Chart1

Chart Grid Navigator

A special component to use the Chart Grid, similar to a Database Navigator:

Allows scrolling through the grid, adding, editing and removing Series values.

Changes are automatically reflected back in the Chart Series.


New v5 Web
New v5 – Web Charting

TeeChart and the Internet

Version 5 includes several helper methods and components to add charts to your web applications..

•	Exporting Charts as GIF, JPEG and PNG pictures.

•	ChartWebSource component to load Charts from remote webs.

•	SeriesTextSource component to load Series data from remote webs.

Some ways to program:

At the Server side:

•	CGI / WinCGI

•	An executable module (created with Delphi for example) can create charts and return them inside html pages.

•	ISAPI module

•	ASP page

•	WebHub

•	VCL WebModule

At the Client side:

•	Static image ( GIF, JPEG, PNG, Metafile, Bitmap )

•	The server module (cgi, asp, etc) can create a Chart and send it to the client as a static image.

•	In ASP and VCL WebModules, using the Response.BinaryWrite method.

•	HTML Image maps

•	Dynamic interactive Chart ( ActiveX )

•	A TeeChart ActiveX control can be inserted on an HTML page (using FrontPage for example), and can be manipulated using VBScript or JavaScript languages. The ActiveX can be created in Borland Delphi / C++ Builder as an ActiveForm. Or you can use TeeChart Pro ActiveX control.

Other Internet Technologies:

•	XML

•	SOAP


New v5 Functions
New v5 – New Functions

•	Exponential Trend

•	Momentum Div.

•	MACD

•	Stochastic

•	New RSI calculation.


New v5 Series Values
New v5 – Series values

•	Dynamic arrays

Series values are now internally stored in dynamic arrays by default.
There is a new property that points to the dynamic array:

Series1.YValues.Values := MyArray

New property: Modified

•	Importing from Text files and from Web

The new TSeriesTextSource component is used to import values (points) from text files (or from TStrings). It can also retrieve text from Internet URL's.


New v5 New in Series
New v5 – New features in Series

•	Series Marks

o	Border shadow

o	Rotation Angle

o	Draw every "n"

o	New XY Style

o	Multi-line text

o	Persistent custom positions

o	Additional formatting properties

•	 Line and Point

o	Stack and overlap modes

o	Clickable Line property

o	Image patterns

•	 Point

o	Drawing pointers on a custom Canvas

•	 Area

o	"Y" Origin to stack Areas

•	 Bar and Horizontal Bar

o	New layout: "Side All"

o	Brush Image

o	Customizable Gradient

o	Bar Stack Groups

o	Cone Bar style

•	 Surface

o	Surface Sides

o	Smooth palette

o	XYZ Floating Point

o	Wireframe and Palette

o	Strong palette colors

•	 Pie

o	Multiple Pies

o	Shadow

o	Semi-Pie style

•	Shape

o	Brush Image

o	Vertical text alignment

•	 Polar

o	Clock-wise labels

o	Circle labels inside

o	Wind rose

o	Labels Angle increment

•	 Point 3D

o	Event for Pointer style

•	 Contour

o	Custom contour levels

o	Easy 2D drawing

o	Palette and Color range modes

•	Clock and Line Point

o	New editor dialogs

•	 Candle

o	Custom candle colors

o	New Open-Close style

•	Miscellaneous

o	Freeing Series

o	Depth 3D


New v5 - New Series Types
New v5 – New Series Types

•	Donut

•	TriSurface

•	BoxPlot (BoxWhisker)

•	Histogram

•	ColorGrid

•	Horizontal Line

•	Bar Join

•	HighLow

•	Waterfall

•	Smith

•	Pyramid

•	Map GIS


New v5 - Gallery
New v5 – New in Chart Gallery

•	Sub-Gallery of chart styles

•	Categorized Gallery


New v5 - Actions
New v5 – Actions (VCL only)

•	3D on / off

•	Axes on / off

•	Legend on / off

•	Grids on / off

•	Marks on / off

•	Series visible on / off

•	Copy to clipboard

•	Edit Chart

•	Edit Series

•	Print preview


New v5 - Exporting
New v5 – Exporting

The new TeeChart export dialog allows charts to be copied to clipboard, save to file, or e-mailed.

•	Exporting Charts as pictures

•	Exporting Chart Data

•	Exporting native Charts (templates)

Exporting Charts as pictures

The export dialog allows several formats to output Charts.
The Chart size in pixels can be specified for any format:

Every different format has its own specific tab of properties:

GIF

Thanks to Anders Melander's TGIFImage component, (http://www.melander.dk/delphi/gifimage/) Charts can now be exported to pictures in GIF format.
Options include compression method (LZW or RLE), dithering mode and reduction schema.
Important Note: Using the LZW compression method requires a License from Unisys (http://www.unisys.com/unisys/lzw/).

JPEG

Using the freely redistributable JPEG library (http://www.jpeg.org/), Charts can be saved to JPEG files.
Options include performance quality and gray scale.

PNG

The freely redistributable PNG library (http://www.libpng.org/) (Portable Network Graphics) is supported in TeeChart.
PNG offers the best compression (smaller size) and image quality.
The compression level when exporting charts is configurable.

BMP

Standard Windows image format.
Settings are Color depth and monochrome.

WMF

Windows Metafile and enhanced metafile formats are supported.

Exporting Chart Data

Series values can be exported in several formats.
Point labels and point indexes are optional.

Text, CSV

Series values can be exported to Text files with the specified field delimited.

HTML

Index	Series1	Series2	Series3	Series4
0	12	12	6	4
1	7	7	4	2
2	2	2	0	1
3	10	10	4	3
4	9	9	4	2
5	9	9	4	2
XML

eXtended Markup Language.
Series values are converted to XML, like in this example.
Note: Internet Explorer 5 is required to view XML files properly.

Excel

Series values are exported to Microsoft Excel BIFF3 format (*.xls).

Sending email

In a Windows machine with a MAPI email application installed (Outlook for example), you can export Charts that automatically get attached to a new email message ready to send:

Exporting native Charts (templates)

Charts can be exported to the native TEE format. This is basically like an VCL "dfm" file, optionally appending the Series values. Size of the TEE file is keeped to a minimum using all kind of optimizations.

These files can be used as templates at run-time using the "LoadChartFromFile" method, and can be also automatically downloaded from Internet using the TChartWebSource component:


XML Example

Example XML

Back to export page

<?xml version="1.0" ?>

- <chart>

- <series title="Series1" type="Point">

- <points count="6">

  <point index="0" Y="1108" />

  <point index="1" Y="1122" />

  <point index="2" Y="1119" />

  <point index="3" Y="1122" />

  <point index="4" Y="1120" />

  <point index="5" Y="1135" />

  </points>

  </series>

- <series title="Series2" type="Point">

- <points count="6">

  <point index="0" Y="1112" />

  <point index="1" Y="1124" />

  <point index="2" Y="1121" />

  <point index="3" Y="1123" />

  <point index="4" Y="1121" />

  <point index="5" Y="1133" />

  </points>

  </series>

- <series title="Series3" type="Point">

- <points count="6">

  <point index="0" Y="1116" />

  <point index="1" Y="1126" />

  <point index="2" Y="1123" />

  <point index="3" Y="1125" />

  <point index="4" Y="1123" />

  <point index="5" Y="1134" />

  </points>

  </series>

- <series title="Series4" type="Point">

- <points count="6">

  <point index="0" Y="1128" />

  <point index="1" Y="1130" />

  <point index="2" Y="1129" />

  <point index="3" Y="1129" />

  <point index="4" Y="1128" />

  <point index="5" Y="1130" />

  </points>

  </series>

  </chart>


New v5 - OpenGL
New v5 – OpenGL

•	New OpenGL Editor (active when Chart in OpenGL mode)


New v5 - Misc
New v5 – Miscellaneous

•	Design-time Series window (VCL only)

•	TeeCommander

TeeCommander component now adds Vertical alignment, a 3D button,a Save button, and it no longer reuses Chart mouse events.

Example:
  TeeCommander1.Vertical:=True;
  TeeCommander1.Align:=alLeft;

•	Chart ListBox

The ChartListBox component now has additional properties to control if the
end-user can change a Series type or Series color, if Series can be
re-ordered by dragging, and if Series can be deleted pressing the Del key.

Mouse-wheel scrolling

Chart Series can be scrolled vertically using the mouse wheel.
You can turn on / off this feature using a global variable:

Example: TeeUseMouseWheel := False;

•	Assign to Pictures (VCL only)

Charts can now be assigned to any TPicture (or descendant) object.
The chart is assigned to pictures in bitmap format.

Example: Image1.Picture.Assign( Chart1 );

Edit Color dialog

When using the EditColor method, colors created by the user are now preserved.
Show the color editor and add custom colors. Show it again. The custom colors are there again.

Custom Colors can also be created at run-time.

•	Custom shape object

A new generic base object: TeeCustomShape.
This object has basic properties to display a shape, like: bevels, border, font, font shadow, shape shadow, shape style, gradient background, color and so on.

A generic editor dialog can be used to modify TeeCustomShape objects at run-time.

•	Metafiles

Chart metafile images can now be optionally transparent.
This can be useful, for example, to copy and paste 2 or more transparent charts in Microsoft Word or Excel, one behind the other.

•	Fixed bugs

Area Series in "Stair" mode was not functioning properly in version 4, when having several Area series stacked.

A small "typo" bug in version 4:
Now there is the new constant: bsCylinder (it erroneusly was bsCilinder).

Fixed bugs about printing charts:

- The Canvas "MapMode" is preserved.
When printing charts, the Windows Device Context MapMode is changed to "Anisotropic" (metafile).
After printing charts, the previous MapMode is restored.

- No printers installed.
When there are no printers installed on Windows, the print preview dialog does not raise any exceptions.

Null Series points are preserved when calling the ColorRange method.

•	Other changes

Package name's contain the TeeChart version and the Delphi / C++Builder version.

Package name	Environment
Tee56	Delphi 6
Tee55	Delphi 5
Tee54	Delphi 4
Tee53	Delphi 3
Tee5C5	C++ Builder 5
Tee5C4	C++ Builder 4

The difference with TeeChart version 4 is all database units now reside at TeeDB package, so now the TeePro and TeeUI packages do not require the VCL DB and BDE packages.

•	New packages:

TeeImage55.bpl Both a design and run-time package.
Adds chart exporting support for GIF, JPEG and PNG graphic formats.

•	Run-time packages:

Package	Description
Tee55.bpl	Core engine.
TeeDB55.bpl	Database Chart and components.
TeeUI55.bpl	User Interface dialogs.
TeePro55.bpl	Extended Series and components.
TeeGL55.bpl	OpenGL 3D rendering.
TeeImage55.bpl	Exporting graphic formats (GIF, JPEG and PNG)
TeeQR55.bpl	QuickReport Chart.
•	Design-time packages:

Package	Description
DCLTee55	Standard Charts and Series
DCLTeP55	Professional Series and components
DCLTQR55	QuickReport Chart design-time package
DCLTGL55	OpenGL 3D design-time package
TeeImage55	Exporting graphic formats
•	Other important internal changes are:

-Series now use VCL Dynamic arrays to store points data. This increases speed.
-All "Longint" variables converted to "Integer".
-Series colors are not stored if not supplied (less memory used).

•	Renamed units:

To better identify TeeChart units, some of them have been renamed, prefixing them with "Tee". These units are mostly internally, so there should be no conflict with your existing applications.

Example:

Uses BarEdit ----> Uses TeeBarEdit
Uses EditPro ----> Uses TeeEditPro


Introduction

For VCL (Borland Delphi and C++ Builder) and ActiveX (Visual Basic, Internet Explorer) environments.

Version 5 Pro is much more powerful than the Standard version 4 bundled for free in Delphi and C++ Builder

See What's New for a list of all new features in TeeChart Pro version 5

We hope you enjoy working with TeeChart Pro 5 !


About TeeChart

TeeChart Pro order information	License and disclaimer

TeeChart Charting components have been written in Delphi by David Berneda. They are 100% Delphi Native Visual Component Library compliant.

For those of you familiar with TeeChart you may wish to look at What's new for a listing of many of the new features of version 5.


Ordering TeeChart
Ordering TeeChart Pro

If you would like to order TeeChart Pro please contact us for latest pricing and licensing information or see the Steema web.

Steema SL

Emili Grahit 31 E-D

17002 GIRONA

CATALONIA, (Spain)

Email: sales@steema.com

Web: www.steema.com


Gallery
TeeChart Gallery

Description

The TeeChart Gallery contains a visual catalogue of all available Series types. You may access the Gallery via the Chart Editor.


Additional TeeChart palette components
Additional TeeChart palette components - Overview

TeeChart version 5 includes several new components on the Delphi palette. Go to the TeeChart tab to access these components:

Components

TChartEditor

TChartEditorPanel

TChartGalleryPanel

TChartGrid

TChartGridNavigator

TChartListBox

TChartPageNavigator

TChartPreviewer

TChartScrollBar

TChartWebSource

TDraw3D

TSeriesDataset

TSeriesTextSource

TTeeCommander

TTeeOpenGL

TTeePreviewPanel

To see a listing of items declared in this unit including their declarations, use the ObjectBrower.


How to create charts with manually inserted values

Data Aware Charts

If values are manually inserted it means that you do not want TeeChart to automatically retrieve the Series points from a Table or Query.

1) Place a TChart component in a Delphi Form.

2) Add a Series component via the Chart Editor. (For example, you can choose a BarSeries component.)

3) In your Form1.OnCreate event (or in a Button1.OnClick event), type the following code:

Series1.Clear;    {Where Series1 is your Bar series}

Series1.Add( 25 , 'Barcelona'     , clTeeColor );

Series1.Add( 50 , 'Rome'          , clTeeColor );

Series1.Add( 30 , 'San Francisco' , clTeeColor );

Series1.Add( 50 , 'New York'      , clTeeColor );

Series1.Add( 40 , 'Los Angeles'   , clTeeColor );

Series1.Add( 35 , 'London'        , clTeeColor );

That's it.

Now lets add a new Line Series component (Series2):

4) Place a Line Series component in the Form.

5) Add the following code to the previous code:

Series2.Clear;   {Where Series2 is your LineSeries}

Series2.Add( 25 , '' , clTeeColor );

Series2.Add( 50 , '' , clTeeColor );

Series2.Add( 30 , '' , clTeeColor );

Series2.Add( 50 , '' , clTeeColor );

Series2.Add( 40 , '' , clTeeColor );

Series2.Add( 35 , '' , clTeeColor );

(Notice you do not need to insert the Horizontal Labels again).

clTeeColor is a TeeChart color constant that means "draw the point in the default color". You can assign a specific color (clRed, clBlue, etc) to each point or you can set the LineSeries1.ColorEachPoint property to True in order to automatically draw each point with a different color.

If you have X (Horizontal) Coordinates:

Replace the AddY method with AddXY:

Series2.AddXY( 15.2 , 25.4 , 'Barcelona' , clBlue );

Other Chart Series types:

Other Series types may use the same methods to add points:

PieSeries1.Add( 333 , 'Sales' , clTeeColor );

Whilst some series that rely on more inputs have series specific methods to add points:

BubbleSeries1.AddBubble( 15.2 , 25.4 , 13 , '' , clRed ); {being 13 the bubble radius}


How to Create Data Aware Charts
How to Create Data-Aware Charts

Manual Charts

The only difference between TChart and TDBChart is TChart does not need the Borland Database Engine.

However, points must be manually added by programming.

TDBChart, in contrast, accepts Series connected to database components (like TTable, TQuery or TClientDataset).

TDBChart will retrieve database records and will automatically add the points.

Add a data table to your form

1) Place a TTable component and assign to it an existing Table. It is not necessary to make the table Active at this stage.

Steps to create a simple data-aware chart

(You can do all steps without programming, using the Chart editor)

2) Place a TDBChart in your form.

3) Right mouse key on the Chart to call up the TeeChart menu then select the Chart editor menu option or Double-click on the chart to go straight to the Chart editor.

4) In the Chart editor add a Series to the Chart by clicking on the Add button. This will call the TeeChart Gallery.Select a series type and click OK.

5) Back in the Chart editor select the Series page with the tab selector (or double-click on your series in the editor series list)

6) On the series page select your new series in the Series Combobox (If you only have one series in the chart it will automatically be displayed in the combobox). Click on the datasource tab to add the new datasource.

7) Select Dataset from the dropdown combobox to define the DataSource property.

Now you can set the series data sources:

8) Set the Dataset field to Table1.

9) Now you need to set Table Fields that will be used to draw your data series: Set the Labels field to the desired table Field. (for example: Table1.CityName) Set the Y values to the desired Vertical Table Field. (for example: Table1.Population). The fields available in this tab page of the Chart editor will depend on the series you are adding. For example a LineSeries will a permit the use of X and Y co-ordinates and an optional Label field, a Pie-series only uses the label field and one set of values. See the Series unit for more information.

Activate your data

10) Now set Active to True (or Open) the Table. Opening or closing the Table will force TDBChart to retrieve the records again, thus allowing refresh.

Color in fields:

It is also possible to have the point colors in a Table or Query field. The field must be a Numeric field containing RGB (Red,Green,Blue) values. Assign the LineSeries1.ColorSource property to this field.

Colors are expressed as numbers, please refer to the Delphi and Windows help to know more about RGB colors. (TColorType)


TeeChart User Guide

The TeeChart User Guide provides a backgrounder and an indepth look at most commonly used and some advanced Chart design techniques.

1. Introduction

1.1. Introduction

1.2. Licensing issues

1.3. About TeeChart Standard version

2. Getting started

2.1. Getting Started

2.2. Using TeeChart online help

2.3. Using the TeeChart Wizard

2.4. Which TeeChart Component should I use ?

2.5. Creating a new Chart with the TChart or TDBChart component

2.6. The Chart Editor

2.7. Configuring data Series in a TChart

2.8. Configuring data Series in a TDBChart

2.9. Modifying Chart data

3. TeeChart demos

3.1. TeeChart demos

4. Component reference

4.1. TChart component

4.2. TDBChart component

4.3. TeeChart Series

4.3.1. TeeChart Series

4.3.2. Line and Fast Line

4.3.3. Bar

4.3.4. Horizontal Bar

4.3.5. Area

4.3.6. Point

4.3.7. Pie

4.3.8. Arrow

4.3.9. Bubble

4.3.10. Gantt

4.3.11. Shape

4.3.12. Combining Series

4.4. Adding a Chart to QuickReport

4.5. Standard Functions

5. Working with Chart and Series

5.1. Overview

5.2. Click events

5.3. Custom drawing on the Chart

5.4. Working with Axes

5.5. Series manipulation

5.6. Printing Charts

5.7. Chart Zoom and Scroll

5.8. Real-time Charting and speed

5.9. Functions


Getting Started

This section should bring you up to speed if you are trying out TeeChart version 5 for the first time. Building a Chart from scratch is very quick with TeeChart so we recommend it worth your while to run through the included examples in your Delphi IDE.

Topics in this section:

2.1. Getting started

2.2. Using TeeChart online help.

2.3. Using the TeeChart Wizard.

2.4. Which TeeChart Component should I use ?.

2.5. Creating a new Chart with the TChart or TDBChart component.

2.6. The Chart Editor.

2.7. Configuring data Series in a TChart.

2.8. Configuring data Series in a TDBChart.

2.9. Modifying Chart data.


Using TeeChart on-line help

Selecting a TeeChart component

Whilst designing your project using a TeeChart component you may select the component from the component palette or on the form where you have placed it and key F1. Context sensitive help relating to that component will appear.

Selecting a TeeChart property, method or event

Highlight a property or event in Object Inspector and key F1 to obtain help for that item. Alternatively write the word for which you would like some help in your code. Select the word by placing and clicking the cursor on that word and key F1. If help is available, TeeChart context sensitive help will access directly a description relating to that functionality.

Help Contents page

The Delphi help Contents page includes a branch dedicated to TeeChart. You can follow the headings there to take you to particular reference section.


Using the TeeChart Wizard

The TeeChart Wizard is only available for use with 32bit Delphi.

To create a Chart using TeeChart Wizard select the File menu in Delphi and New. Choose Business from the tab selector in the New Items window. You will see the TeeChart Wizard icon.

Simply double-click the icon to start creating Charts! The Wizard will lead you through the steps necessary to create your own non-database or database aware Chart.


Which TeeChart component should I use?

There are three TeeChart icons in the component palette.

TChart	TDBChart	TQRChart

TQRChart, is a component especially tailored for use with QuSoft’s QuickReport - See the chapter Adding a Chart to QuickReport.TQRChart is descendant of TDBChart.

The 2 components, TChart and TDBChart are the basic building blocks of all TeeChart Charts.

If you wish to create the data Series for your Chart manually, or via a coded procedure then use the TChart component. If you wish to source your graph data from a table or SQL query then use the TDBChart component. You may, of course, use TDBChart in all cases but it will result in a larger compiled size of your code which would be inefficient if you are not using a datasource (explanation follows).

Once an initial data Series is defined, both Chart components, TChart and TDBChart support the use of another data Series as a data source.

- So why two kinds of Chart components?

- couldn’t we achieve this functionality via just one component?

Answer:

Projects compiled with using only TChart components, don't need the Borland Database Engine DLL's (BDE).

Internally, both derive from the TCustomChart component, which is responsible for most Charting capabilities.

In Delphi 4 and 5 TClientDataset can be accessed without the need for BDE.


Creating a new Chart with TChart or TDBChart component

Many of the steps necessary for defining a TChart or TDBChart are the same. This section describes the common steps needed to start defining either of the two types of Chart.

Create a new Form.

Create a new form and place a TChart or TDBChart component on it (drag it across from the component palette).

Drag the corners of the new TChart or TDBChart component out to a size that helps you visualise the contents of the new Chart as you define it. Later you can adjust the size of the Chart to suit your needs.

Edit the new Chart

Position the mousepointer over the new Chart and press the right mousebutton. A menu appears that includes the ‘Edit Chart’ option.

Fig. 1. Using the right mouse button on the Chart will call the Chart options menu.

Select the Edit Chart… option to edit the Chart and define and populate its data Series.

Go to the next step.


The Chart editor

Fig. 2. The Chart Editor screen
The Chart page (1st page) of the Chart editor contains definition information for the Chart. It includes sections to define general and other more specific, Chart parameters. Some parameters won’t apply until you have some data Series defined in the Chart. Try modifying a parameter, the Title for example, and you will see it update in real time on the Chart.

To access the Chart editor double-click on any TChart or TDBChart component placed on a Form. Alternatively right mouse-click on the TChart to bring up a menu which includes Chart editor as one of the options.

To edit a TQRChart you may follow the same procedure as above whilst the TQRChart is placed on a QuSoft QuickReport.

See the user guide for more information about the Chart Editor.

To see some data Charted we need to create a data Series...

Add a data Series

Press the Add button in the Series tab section of the Chart page. TeeChart will show you a gallery of Series types. Select one to add to your Chart, you can change its type later if you decide that you would prefer to visualise your data in a different way.

Fig. 3. The Chart Gallery
Select a Series type by mouse or with arrow keys and press ‘OK’. Double-clicking on the Series type will achieve the same result. The Extended Series page is only available in the Gallery with TeeChart Pro.

The Series type is automatically added to your Chart. In the Chart editor you will see a new configuration tab added for the new Series.

Suppose we had selected a line Series. The editor will appear as follows:

Fig. 4. New Series added to Chart
TeeChart has added the Series to the Chart. It has also added some random values so that you can visualise, in the Chart, the Series appearance at design-time to easily follow any changes you are making.

Press the F9 key to compile your project. The project should compile to show you an empty Chart. The random values don’t work at runtime so the next step is to go back to the Chart Editor and add a data source or write your own code to add data values.

Edit the Series

Selecting the Series tab allows you to edit your Series. The next step is to add data to the Series. The steps necessary to include the data for the Series vary slightly between a TChart component and a TDBChart component. See the following 2 sections:

Configuring data Series in a TChart.

and

Configuring data Series in a TDBChart.


Configuring data Series in a TChart

We have a TChart on the form and have added a Series to it. We are ready to populate the Series.

Let’s type some Pascal code to add points values programmatically.

We'll see later how to create a database-aware Chart with automatic record retrieval.

Example Pie-Series

Suppose the Series we added was a Pie Series. We could populate the Series in the following way. For the following code to work we should leave the Series name as its default of Series1.

Place a TButton on your Form and go to the OnClick event .

Copy the following code at the Button1.OnClick event:

With Series1 do

Begin

    Add(  40, 'Pencil' , clRed ) ;

    Add(  60, 'Paper',  clBlue ) ;

    Add(  30, 'Ribbon', clGreen ) ;

end;

A description of the Add method and other available methods and properties is available at design time via the context sensitive help included with TeeChart. Place the cursor on the word Add in your code and press F1 for a full description of the method.

Return to your code and press F9 again to run the project.

Press Button1 to see the Pie Chart appear - the code works!

Editing the Series

Close the program to go back to Delphi’s IDE.

In design mode, all Chart and Series properties are accessible through the Delphi Object Inspector or by right-clicking the Chart and selecting the ‘Edit Chart’ option or double-clicking on the part of the Chart that you wish to edit. Here we’ll use the Chart editor to edit our new Chart and Series. Fig.5. Shows the first editor screen.

To edit features of the Series we can double-click on the Series in the list or highlight the Series and select Edit or directly select the tab for the Series - each technique will take us to the editor for the Series.

Fig. 5. The Chart Editor screen showing the new Pie Series
Try changing some properties of the Pie Series; you will see the results update automatically on the Chart. There is no cancel to undo changes but most parameters are easily toggled. Remember, in design time the TChart component hasn’t yet run your code so it shows the randomly generated set of data. You will need to start your project to see how the new parameters show up with your own data.

Fig. 6. The Chart Editor Series page showing editor tab for our Pie Series
Many changes can be made visually in the editor, or try modifying some parameters in Object Inspector, or modifying a property with your own code. For more advanced projects, you’ll most likely find yourself typing some Object Pascal code.

For a recap and further look at adding data to a TChart via another example, see How To Create Charts with manually inserted values

Now we’ll take a closer look at adding data to the TDBChart component.

Configuring data Series in a TDBChart.


Configuring data Series in a TDBChart

Prior to using any database facilities, you should have correctly installed the Borland Database Engine (or equivalent) and the Database Delphi VCL components.

A Step by step guide to creating a database aware Chart....

- Place a TTable component and point it to the "DBDEMOS" database and the "ANIMALS.DBF" dBase table.

- Place a TDatasource component and set its DataSet property to Table1.

- Place a TDBGrid and set the DataSource property to DataSource1.

- Set the Table1.Active property to TRUE to see the Grid filled with table data.

- Place a TDBChart component onto a Form.

- Select and install a Pie Series as described in section The Chart Editor.

- Go to the Series page of the Chart editor by either double-clicking on the Series name, highlighting the Series and selecting Edit, or by selecting the Series tab.

- Select your Series from the Series listbox and go to the datasource tab.

From the listbox select your data source type.

There are 4 types of data source available. The DataSource style is a  component property that may be one of the following:

‘No data’ if  points are being added programmatically (at source code).

or...

‘Random values’ draw your Chart Series with random values.

or…

‘A function’ which may be:

One or more other Series (like LineSeries1, BarSeries2, etc.) which could come from this Chart or from another Chart in your project. A function may work with a combination of one or more other Series and an algorithmic function (min, max, average, etc.).

or..

A ‘Dataset’ which may be a:

TTable, TQuery, TClientDataset or any other TDataset component.   (like Table1, TQuery1, etc.)

Adding a dataset

For our example, let's choose the 4th option from the previous section, ‘Dataset’ style. In our TDBChart we’ll include data from the table that we’ve already added to the form.

You need to select the listbox option A dataset to map this Series to the table that you have included in the project. As you make the selection you will notice new page options appear to define the dataset for the pie Series. Your editor should look like Fig. 7.

Fig. 7. The Chart Editor screen showing the Data source tab for our pie Series
All you need to define a simple dataset for the Series lies here. You have already included a table and datasource in your form, and set the table to active. But the options here offer you the flexibility to define the dataSeries in varying ways:

Click on the down-arrow for the ‘Dataset:’ combobox.

If you have an activated table in the form it will be

highlighted here.

Select your table.

Define the values that will be plotted in the Chart:

As we have defined a Pie Series we are presented with pie specific configuration options. Each Series has parameters that vary, but only slightly, in definition from the example below.

The Pie field is mandatory, and must contain a valid numeric field or a string field with values that can be converted to numbers.

In our example, choose the Weight field.

(The ANIMALS table is a collection of animal names with weight and size information.)

You can optionally select an Labels field to draw the corresponding string for each point on the pie.

In our example, choose the Name field.

This label will be used to draw the Pie Legend.

Note

Some Chart Series types have more than one figure to represent a point. Values that are plotted by date or time are an example of X Values Series. Not all date-time values should be equally spaced. The X Value is the specific horizontal position for each  Y value. Later try deleting the pie Series and adding a Series of a different type, - ie. LineSeries -, you will see the option to apply X and Y values appear.

(We don't have X Values in a Pie Series.)

Now click the "OK" button.

The TDBChart component will show a Pie Chart and a Legend.

You are seeing exactly the same Chart you saw when you pressed F9 to run the project.

For a recap and further look at adding data to a TDBChart via another example, see How To Create Data Aware Charts


Modifying Chart data

Chart data may be accessed via the the Point Valueindex of each Series' points.

Deleting points:

Use the Series Delete method:

{This will delete the 5# point from LineSeries1}

LineSeries1.Delete( 5 );

Modifying points:

Use the Series XValue, YValue properties:

LineSeries1.YValue[3] := 27.1 ;

{In Bubble Series}

BubbleSeries1.RadiusValues.Value[ 8 ] := 8.1 ;

{In Pie Series}

PieSeries1.PieValues.Value[ 3 ] := 111 ;

Please refer to each specific Series type to see its specific data related methods.

DateTime point coordinates:

TeeChart Series accept DateTime values.

{First, you need to set the DateTime property to True in the desired X and/or Y values list.}

LineSeries1.XValues.DateTime := True ;

{Second, use the same above described methods, but give the values as Date, Time or DateTime values}

LineSeries1.AddXY( EncodeDate( 2000 , 1 , 23 ) , 25.4 , 'Barcelona' , clGreen );


TeeChart demos

The Getting Started section of the TeeChart User Guide explains the most basic TeeChart procedures. Another useful place to look for help are the examples in the demo files.

Location of TeeChart demos

Open in Examples folder below the TeeChart installation folder to access the TeeChart demo projects.

There are many included forms in the TeeChart examples.

Each form shows a specific TeeChart feature or Series type.

Many Forms contain Pascal source code to show event handling or interactive Charting.

The following example shows how to add data to a Chart by code and scroll the Series with the new point:

Note:

The flexibility of TeeChart’s components offers the ability to change Series type at any time - thus Series names by default are generic, Series1, Series2, etc..

Add a TeeChart to a Form and select the Editor ‘Add’ button to add a LineSeries

Click on Form.OnCreate or switch to source code to see the following:

procedure TScrollForm.FormCreate(Sender: TObject);

begin

  FillDemoPoints;

end;

procedure TScrollForm.FillDemoPoints;

var t:Longint;

begin

  { fill the LineSeries with some random data }

  Series1.Clear; { <-- this removes all points from Series1 }

  { let's add 60 minutes from 12:00 to 12:59 }

  for t:= 0 to 59 do

      AddXY( EncodeTime( 12, t, 0,0),Random(100),’’,clRed );

  { let's add 60 more minutes from 13:00 to 13:59 }

  for t:= 0 to 59 do

      AddXY( EncodeTime( 13, t, 0,0),Random(100),’’,clRed);

end;

This code will Clear LineSeries and plot two hours of random values from 0 to 100.

Because it is placed on the Form.OnCreate event, each time the form is shown, this code is executed.

Double click the Button1 component to see its associated OnClick code:

procedure TScrollForm.Button1Click(Sender: TObject);

var h,m,s,msec:word;

begin

  if CheckBox1.Checked then { If VERTICAL SCROLL }

     DecodeTime( Series1.YValues.Last , h, m, s, msec)

  else

     DecodeTime( Series1.XValues.Last , h, m, s, msec);

  { add a new random point to the Series (one more minute) }

  inc(m);

  if m=60 then

  begin

    m:=0;

    inc(h);

  end;

  AddXY( EncodeTime( h, m, s, msec), Random(100),’’, clYellow );

end;

This code increments the last added point Time by one more minute.

The incremented Time value is added to the LineSeries, thus giving a new point.

The next code sample shows the key purpose of the example:

How to scroll the Horizontal Axis as new Points are added to the end ?

The easy way is to type the following code at the Series.OnAfterAdd event. This event is called each time a new point is added to the Series.

In this example, we scale the bottom horizontal Chart axis to show 55 minutes prior to the last point and 5 minutes after the last point.

{ This is the event we need to arrange Axis scale as new points are added. }

procedure TScrollForm.LineSeries1AfterAdd(Sender: TChartSeries;

  ValueIndex: Longint);

begin

 { If VERTICAL SCROLL }

  if CheckBox1.Checked then

  begin

    With Sender.GetVertAxis do  { <-- with the 	Vertical Axis... }

    Begin

      Automatic := False;        { <-- we don’t want 	automatic scaling }

{ In this example, we will set the Axis Minimum and Maximum values to

show One Hour of data ending at last point Time plus 5 minutes }

      Minimum := 0;

      Maximum := Sender.YValues.MaxValue +

                 DateTimeStep[ dtFiveMinutes ];

      Minimum := Maximum - DateTimeStep[ dtOneHour ];

    end;

  end

A great deal of flexibility can be achieved by manually setting the Axis properties.

Each Chart component has four standard front plane axes:  LeftAxis, TopAxis, RightAxis and BottomAxis and one Depth axis, DepthAxis. Each Axis has a boolean "Automatic" property that defaults to True, meaning TeeChart will always calculate the Minimum and Maximum values for each Axis. In addition to the Standard axes you may add as many Custom axes as you wish, horizontall or vertically.

The Axis Minimum and Maximum properties are of type double, allowing float numbers or DateTime representations like "Date", "Time", "Now" or any other valid datetime value.

Now, compile and execute this project and look at each sample form in the TeeChart example project.

They should give you ideas that you can apply to your projects while you learn about TeeChart features.

The TEECHART.HLP file describes each component property in detail, with some source code examples mostly taken from the TeeChart demo projects.

We suggest that you to experiment with each different sample form and create new small projects to test TeeChart with your real data.


TChart component (Guide to use)
TChart component

The TChart component is the basic building block for ‘non-database-aware’ Charts. Select the TChart component from the Delphi palette and simply drag it onto your form to include a Chart in your application.

See TChart Component for Class definition.

You can use the Chart Editor to define display characteritics for the Chart and to add new Data Series. Alternatively all properties can be set and changed at runtime using Chart properties and methods.

Data Series for the TChart component must be populated by code. See Configuring data Series in a TChart for an introduction.

For an indepth look at how to create Charts with TeeChart see the TeeChart User Guide.


TDBChart component (Guide to use)
TDBChart component

TDBChart derives from TChart and inherits all its functionality. When a Chart Series is connected to a TDBChart component, TDBChart looks in the Series DataSource property.

The datasource for the Series is defined by the Series definition - not by the Chart - Thus multiple Series in a TDBChart could access different data sources. However, if those Series are not associated, via ParentChart, with a TDBChart then the option to define a Series database-datasource won’t be available.

Creating the Dataset

TeeChart Charts will connect with several different types of Dataset.

TTable

TQuery

TClientDataset

TADOTable

TADOQuery

The minimum that requires to be set in each case is:

The name of the database,

For the table the TableName of a table

or

in the case of the query a valid SQL string.

or

in the case of a ClientDataset Define source (right button on TClientDataset object in form).

* Remember to activate the Dataset by setting the Active property to True.

Connecting your Series to a database Dataset

In ‘Getting Started’ you saw how to connect a data Series to a database dataset. Let’s recap here on the key components.

When you select your new Series in the Chart Editor Series page you will see the tab option for Data Source. If you want your data Series to be connected to a new dataset then you should select Dataset from the drop down combo listbox. A new selector box will appear with the options for definition of the new dataset.

The exact contents of the page will change depending on the Series type you have chosen. The parameters you set here modify  the properties in the Series definition which vary between Series type. The following table shows the possible options for some Standard Series types Function Series are based upon their resident Series type, eg. An average function may be displayed as a LineSeries or BarSeries, etc so work with the same number of variables.

SERIES TYPE	DATASOURCE PROPERTIES
Standard Series
Line	XValues, YValues, Xlabel
HorizLine	XValues, YValues, Xlabel
Fast Line	XValues, YValues, Xlabel
Bar	XValues, YValues (called Bar), Xlabel
Area	XValues, YValues, Xlabel
Point	Xvalues, YValues, Xlabel
Pie	PieValues, Xlabel
Arrow	StartXValues, StartYValues, XLabel, EndXValues, EndYValues
Bubble	Xvalues, YValues, XLabel, RadiusValues
Gantt	StartValues, EndValues, AY (Y axis level), AXLabel (Label optionally shown on Y-axis or as mark)
Shape	X0 (Top), Y0 (Bottom), X1 (Left), Y1 (Right)

Coding your datasource

You may populate your Chart at runtime by coding which Series to add to the Chart and defining the fields of those Series.

It assumes you have a table on your form, Table1 with fields Name and Amount.

Var

MySeries,Ave:TLineSeries;

MySeries:=TLineSeries.Create( Self );

With MySeries do

begin

 ParentChart:=DBChart1;

 DataSource:=Table1;

 XLabelsSource:='Name';

 YValues.ValueSource:= 'Amount';

 CheckDatasource;

end;


TChartSeries

The TChartSeries component is the ancestor of all Series types. When referencing the properties of the Series type with which you are working check, in addition to the properties listed with that Series, the properties of the TChartSeries to get a full list of properties common to all Series.

Topics included in this section:

Line and Fast Line

Horizontal Line

Bar

Horizontal Bar

Area

Point

Pie

Arrow

Bubble

Gantt

Shape

Combining Series


Line Series

There are 2 standard line Series types available, Line and Fast Line. Which one should be used ?  Fast line is just what its name describes - it is fast. It is distinct from Line because to achieve speed - speed to add new points to the Series - the price paid is that it foregoes some properties that the Line Series has. See the section on Fast Line for a description of those differences.

Line

See TLineSeries for a full list of properties and methods

A 3D Line Series showing one Series with the stairs property set to true. The stairs can be inverted.

Fast line

See TFastLineSeries for a full list of properties and methods

This line Series draws only at 2 Dimensions but draws very quickly - performance will depend on your hardware - The Series type was originally conceived to tackle high volume requirements of technical and financial applications but serves well for any dataset of very high point volumes.

If, when using Fast Line you know approximately how many data points will be added to your Series you could use the global variable TeeDefaultCapacity to prepare memory. For example, assuming a data Series of 10,000 you should set TeeDefaultCapacity to 10,000. This will, in one pass, allocate memory to populate the whole Series replacing the need to incrementally allocate memory which costs more time.


Horizontal Line Series

The Horizontal Line Series allows the display of X and Y points to be reversed. That is available with Standard Line Series which by default join points along the X plane by setting the LineSeries Xvalues Order to LoNone and adding the points in the order with which to be plotted. That’s made easier with the Horizontal LineSeries which connects points on the Y plane by default giving a ‘vertical’ appearance to the Line.

Horizontal Line

See THorizLineSeries for a full list of properties and methods

A 3D Horizontal Line Series.


Bar

See TBarSeries for a full list of properties and methods

The bar Series in 2 or 3 dimensions doesn’t have to be represented by a rectangular bar -

Choose a barstyle for your Chart Series or ‘mix and match’ to suit your needs.

Example bar Series configuration

Mixing bar Series styles may be useful for some applications. Below is an example stacked bar Chart.

Mixed bartypes

Steps taken to build this demo Chart and populate it with data are as follows:

1. Drag a Chart component onto your form and drag it out to the size you want.

2. Click the right mouse button over the Chart and select editor from the menu.

Add 3 bar Series and give them individual titles using Title on the first editor screen (titles in our example ‘East’ ‘West’ and ‘Other’).

Select Multi Bar and set as stacked in the Format page of any one of the 3 Series (The change will apply to all 3 Series).

Add a title using the entry tab for ‘Titles’ in the Chart page of the editor.

Go to the axis tab. Select Left axis and add the title. We allowed the axis to automatically size itself but took minor ticks off on the bottom axis.

Each Series has a different shape defined for its bars. We define the shape individually in the configuration page of each barSeries. The first tab, Format, has the option for Style.

You could code the style with:

East.BarStyle:= bsPyramid ;

West.BarStyle:= bsInvPyramid ;

Other.BarStyle:= bsRectangle ;

Lookup BarStyle in the TeeChart online help to get the full list of options.

For this Chart it would be necessary to control the Series order to achieve the correct effect. This can be done in the Chart Editor at design time by selecting the Series in the Series list of the Chart page and using the arrows to change the order. At runtime we can achieve the same with the following code:

Drawing order is always based on the order for which the Series are assigned to  ParentChart.

The order can be altered at run-time via the Serieslist property:

Chart1.SeriesList[ 0 ] := East;

Chart1.SeriesList[ 1 ] := West;

Chart1.SeriesList[ 2] := Other;

We added some random values to populate this demo. We could launch the code at form creation or put a button on the form to run the code.

procedure OurForm.Button2Click(Sender: TObject);

var t:integer;

begin

Randomize;

with East do

for t:=1 to 12 do AddY( Random(70), ShortMonthNames[t],clTeeColor);

with West do

for t:=1 to 12 do AddY( Random(70), ShortMonthNames[t],clTeeColor);

with Other do

for t:=1 to 12 do AddY( Random(30), ShortMonthNames[t],clTeeColor);

end;

We populated the data for 12 months but are showing only 5 months. The Paging tab in the Chart page of the editor has the definition of points per page.

Bar Series display

The Multi Bar parameter set in the Format tab of the Series page for one of the bar Series sets the display alignment of the bars for each bar Series in the Chart. - It is not necessary to go to each bar Series to change the parameter.

The following figure shows different formats to display bar Series. Each Chart has the same information only displayed in a different way. The Stacked 100% Series display doesn’t represent the actual values but rather the relative value of each element of the Series to a total of 100%.

Fig. a A 3D Bar Series showing four methods to display the same information.		Stacked property None
Fig. b		Side
Fig. c		Stacked
Fig. d		Stacked 100%


Horizontal bar

See THorizBarSeries for a full list of properties and methods

The horizontal bar Series shares the same properties as the bar Series. Apart from any aesthetic requirement, one occurrence of the need to use a horizontal bar Series may be to adequately display long axis labels which are best read horizontally.

2D Horizontal bar


Area

See TAreaSeries for a full list of properties and methods

An Area Series has similar characteristics to a line Series - filled -

3D Area Series


Point

See TPointSeries for a full list of properties and methods

A Point Series is similar in definition to a Line Series without the line.

2D Horizontal bar


Pie

See TPieSeries for a full list of properties and methods

A Pie Series is unique in not needing any axis. It is possible to mix a Pie Series in a Chart with another Series that requires an axis.

3D Pie


Arrow

See TArrowSeries for a full list of properties and methods

3D Arrow Series
The arrow Series is useful for displaying start and end points of many individual events.


Bubble

See TBubbleSeries for a full list of properties and methods

The Bubble Series has 3 configurable parameters that define the value of the data in your Series.

Xvalues, YValues, RadiusValues

The bubble Series is useful for showing importance weighting. For example, comparing high volume selling product that, by income, doesn’t bring in a revenue of the scale of another low volume seller. We can see at a glance, literally, that big bubbles are important !

2D Bubble Chart

Shapes

Bubble Series can be configured in variable shapes, triangles, etc..


Gantt

See TGanttSeries for a full list of properties and methods

Use the Gantt Chart as a planner or to track progress of a project or Series of activities.

The Gantt Series draws bars that have start and end values which may be of datetime format. You may define a Y axis value for the vertical position of the bar and you may define ‘next bar’ to draw connection lines between the bars.

2D Chart with a Gantt Series.

How to add Gantt bars manually

Use the  AddGantt or AddGanttColor methods.

Example:

   GanttSeries1.AddGantt(  EncodeDate( 2000, 1,  1 ),

                           EncodeDate( 2000, 1, 31 ),

                           0,

                           'Programming' );

Or...

   GanttSeries1.AddGanttColor(EncodeDate( 2000,1,1 ),

                              EncodeDate( 2000,1,31),

                                0, 'Programming',

                                clGreen );

Where "0" is the desired vertical position for this bar.

Choose the vertical position you prefer.

To connect gantt bars:

1) Store the "AddGantt" or "AddGanttColor" function return longint:

Var tmp1, tmp2 : Longint;

tmp1:=GanttSeries1.AddGantt(EncodeDate(2000,1,1 ),

                            EncodeDate( 2000,1,31 ),

                               0,'Programming' );

tmp2:=GanttSeries1.AddGantt(  EncodeDate( 2000,4,1 ),

                              EncodeDate( 2000,4,30),

                               0, 'Testing' );

2) Then use the NextTask property:

GanttSeries1.NextTask[ tmp1 ] := tmp2 ;

This will draw a line from 'Programming' gantt bar to 'Testing' bar. The "ConnectingLinePen" property is the pen used to draw lines.


Shape

See TChartShape for a full list of properties and methods

Shape Series are useful for defining or adding any additional information to your Chart, perhaps in runtime as a result of receipt of exceptional data. You may add text to any shape you add to your Chart and relate the shape to  another Series.

Shape Series

Each shape has two co-ordinates associated with it, top left and bottom right of the invisible rectangle that encloses the shape. You may add text to the box. These co-ordinates and messages could be updated at runtime by your code to dynamically put the shapes anywhere on your Chart.


Combining Series

There is no practical limit to the number of Series that you can add concurrently to your Chart.

You may mix different Series types, almost any Series type with any other Series type. For certain combinations it is not practical as axis definition between Series may directly conflict. For those cases the Series not available are greyed out in the Series gallery so that you cannot mistakenly select them.

See the section on functions for more about combining Series types. Functions work with other Series to create and display algorithmic relationships.

Combining Series

Example Series combination

Combining Seriestypes in one Chart can add a great deal of information value.  The following example shows the incomes by Division and puts the $ index in the same Chart to measure the effect of that external influence on incomes (perhaps no influence at all in this example !!).

2D Combining Series types

You may combine Series in 3D Charts. The previous example is represented in 3D below. The Chart looks attractive although a high degree of 3D perspective makes it more difficult to visualise the monthly $ index with Division incomes.

3D combining Series types (60% 3D)

You could minimise the effect by reducing the extent of ‘side’ view (percentage 3D).

3D combining Series types (6% 3D)

Or you could modify code so that at runtime the Chart will put all Series in the same Z-plane. 3D Charts have a property called Z-Order (see figure) which controls the depth position of each Series.

It is possible to put all Series on the same plane although we advise caution as the effect may be confusing depending on which Series types you are combining.

The following line of code (name of Chart here Chart1) will put all Series in the same Z plane:

Chart1.ApplyZOrder:=False;


Adding a Chart to QuickReport

TeeChart integrates seamlessly with Qusoft’s QuickReport. To add a TeeChart to a QuickReport follow these steps:

Drop a QuickReport on a form.

Using the QRChart icon on the QuickReport palette

Put a TQRChart onto the QuickReport worksheet.

You may now double click on the TQRChart to bring up the Chart editor. From this point forward you may work with the Chart as with any other TDBChart.

At runtime, access properties and methods for the Chart via the TQRChart.Chart property.

TQRChart on a QReport at design time

Notes on working with QuickReport

Metafile

TeeChart uses Windows Metafile format for superior quality when outputting to a printer and for drawing onscreen. Also the quality of the printout is better if the Chart shape is maintained as nearly as possible to the default Chart rectangle form.

Clipping

TQRCharts do not support Series clipping. The may result in slight overlay of the Series onto the Chart axis if data points are adjacent to the axis.


Standard functions

Add

See TAddTeeFunction for a full list of properties and methods

The Add function adds data from one or more Series. If we create a line Series ‘Series1’, create a line Series ‘Function Add’ and define Series ‘Function Add’ as Add of Series1 and do nothing more we will obtain a Chart with Series1 displayed and ‘Function Add’ as one flat line which is the sum of all  values of Series1. In the figure the total of 1 + 2 + 3 + 4 + 5 + 6 = 21.

Fig. 1. 2D Add function with 1 Series input

We can modify the Series ‘Function Add’ to represent Add of Series1 by 2 point groupings (1+2), (3+4), (5+6). We use the period property (Chart Editor in the Data source page). Coded it looks like this:

Series2.FunctionType.Period:=2;

{where Series2 is the functionSeries}

Alternatively:

TeeFunction1.Period:=2;

{The name of the function is automatically allocated when the function is defined in the Chart editor - You will find it in the Object inspector}

Defining the period as 2, sets the Add function to add every 2 points. The period property adds enormous value to function Series.

Fig. 2. Add function with period = 2

Subtract

See TSubtractTeeFunction for a full list of properties and methods

Subtract requires 2 input Series. With more than one Series in the function the default period sets to 1 axis point.  the 2nd Series will be subtracted from the 1st Series in the list.

The following Chart is defined with ApplyZOrder:=False which forces all Series to draw in the same 3-Dimensional plane - The resulting Series overlay (a sort of optical illusion) in the Chart depends on the Series paint order.

Fig. 3. Subtract function

Multiply

See TMultiplyTeeFunction for a full list of properties and methods

The default period for the function ‘multiply’ is 1. You may add as many Series as you wish to the multiply function.

Fig. 4. Multiply function

Divide

See TDivideTeeFunction for a full list of properties and methods

As divide requires at least 2 input Series the default period for the divide function is 1. The 2nd Series in the list is the denominator.

If you add more than 2 Series then the 1st will be divided by the 2nd then that is divided by the third, etc.…

Fig. 5. Divide function

High

See THighTeeFunction for a full list of properties and methods

High accepts multiple input Series and will always display the highest point between those Series at each period point. (1 Series default period 0,  2 or more Series default period 1).

Fig. 6. High function

Low

See TLowTeeFunction for a full list of properties and methods

Low accepts multiple input Series. It will always display the lowest point between those Series at each period point. (1 Series default period 0,  2 or more Series default period 1).

Fig. 7. Low function

Average

See TAverageTeeFunction for a full list of properties and methods

Fig. 8. Average function

The default period for average with one Series is 0 (all) which will give you the average for that Series across the whole Chart. If you have more than one Series the period will be 1 axis point.

You may change the period to alter the frequency of the average curve.


Working with TeeChart Overview
Overview - Working with Charts and Series

This section describes some design considerations and conventions for working with TeeChart. The section Working with Charts and Series brings to your attention some points of interest that may help with the design of your application.

Topics in this section include:

Click events

Custom drawing on the Chart

Series manipulation

Printing Charts

Chart Zoom and Scroll

Real-time Charting and speed

Functions

To understand the design paradigm of TeeChart we need to separate conceptually the contents of the Chart -the data Series-  from the Chart itself, e.g. its Axis format, Legend and Titles. We can define and work with Series across Chart boundaries, referencing Series components independently of the Chart. We may, however, copy and paste a Chart and it will copy with all its defined contents, Axis, Legends and Series

Two Chart components

There are 2 Chart components - The distinction serves simply to help cut down memory use for Charts that do not need to access a database.

Projects compiled with using only TChart components, don't need the Borland Database Engine DLL's (BDE). A new TChart will not contain configuration parameters for connecting to a database.

Delphi Version 4 and 5 offers the use of the TClientDataset as a Datasource. It does not use the BDE.

Chart subcomponents

The 2 Chart components have subcomponents. If, for example, you wish to access or modify the property of an axis of your Chart you will be modifying the property of one of the following subcomponents:

BottomAxis

TopAxis

LeftAxis

RightAxis

DepthAxis

See TChartAxis to get a complete list of axis properties. Legend is another example of of a TChart subcomponent.

The Chart as backdrop to your Series

The Chart components provide the backdrop for your data Series. The overall ‘look’ of your Chart is controlled by the Chart properties accessible via the Chart Editor, the Delphi Object Inspector or by coding - see the online help for a complete list.

As a backdrop you have available to you the Delphi Canvas property and methods to calculate screen co-ordinates from values and vice-versa. Every TChart component has a "Canvas" property which is a standard Delphi TCanvas object.

Associating a Series with a Chart

Series associate with a Chart via a Series property called ParentChart. The Series are moveable between Charts by changing the Chart defined in the ParentChart property. When you add a Series using the TeeChart Editor the ParentChart property of the Series is set automatically to the Chart in which you are working.

Via the Chart editor

After a Chart has been placed on a form, a right button click gives access to the Edit Chart menu (alternatively double-click). The first screen of the Edit Chart menu offers a list of button options to add, delete, clone, change type or title of a Series. Adding a data Series via this menu automatically associates the new data Series with the Chart.

Via the Object Inspector

Whilst browsing the list of components of a form in the Object Inspector you should see all Series added to any Chart on that form. Those Series components are not directly visible on the form but are nevertheless components with accessible properties.

If, for example, and you could try this with a simple test, you have 2 Charts on your form and have used the Chart editor to add a Series to one of the Charts - you could now access the property list of that Series in the Object Inspector and change the name of ParentChart to the other Chart on the form. On now opening the Chart editor for the new ‘ParentChart’ you will see the Series. Of course if you make this move for a Series defined with DataSource from a TDBChart to a TChart you will lose the ability to access the DataSource as the TChart is not database aware.

Via code

Use the ParentChart property to associate (or disassociate) a Series with a Chart.

Example:

In Form1, we'll create and show another Form (Form2), and assign Form1.LineSeries1 to Form2.ChartInForm2 :

With TForm2.Create(Self) do

try

Self.LineSeries1.ParentChart := ChartInForm2 ;

ShowModal ;

finally

Free ;

end ;

That will show Form2 (containing a Chart component) and drawing Form1.LineSeries1.

Often used parameters

All the parameters associated with Charts are useful at the time you need them. We cover a few frequently used properties in detail below as an introduction. For a more detailed study of these and many other configurable parameters please refer to the remaing Topics of this section, Working with Charts and Series.

Label increment, % separation and angle

It may be difficult to fit all your axis labels onto the axis that displays onscreen - As an example, this is often true of date labels which are long and can have a high incidence of change on the axis.

Label Increments

TeeChart offers Label increment as a means to controlling the frequency of labelling on your Chart axis. You can access the property via the Chart Editor under Axis (select your axis) - Scales - Desired increment. The menu shows you a list of the standard options for time increments (e.g. One second, one minute … one day, etc.) Selecting ‘one day’ will cut out repetitions of date on the axis, showing the date label only once for the point range of that date.

Via code you may access the property as a property of the subcomponent for the relevant axis.

Example:

Chart1.BottomAxis.Increment := DateTimeStep[ dtOneHour ] ;

Chart1.RightAxis.Increment  := 1000 ;

% Separation

If the labels on the axis have a look of rolling into one another you can increase the % separation which will forcibly increase the gap between them. In some cases this may, as a result, hide some labels. It will very much depend on your labels and whether your Chart users will have the option to ‘resize’ their Chart.

The option is available in the Chart Editor under Axis (select your axis) - Labels - % Separation.

Setting Labels Separation to 0 % means no overlapping checking will be performed, thus all axis labels will be displayed.

Angle

If it is neither practical or possible to place the axis labels side to side along the axis another option is change the angle of the labels to 90º to the axis. This option is available in the Chart Editor under Axis (select your axis) - Labels - % Angle.

BitMaps (BMP) or  Metafiles

TeeChart offers both the bitmap (BMP ) and the Metafile format to save Charts. Two type of metafile formats are supported WMF (Windows Metafile Format) and EMF (Extended Metafile Format).

Bitmap format is used internally by TeeChart. It is quicker to draw onscreen than a Metafile. When requiring a Chart to be ‘exported’ to another application or to be embedded in a container application such as MSWord a Metafile format handles resizing better onscreen - TeeChart uses Metafile format with QuickReport.

Zoom

TeeChart offers as default zoom on all Charts. To obtain zoom at runtime hold the left mouse button and drag mouse toward down/right. You'll see a rectangle around the selected area. Release the left mouse button to Zoom. You can continue zooming again and again. To RESTORE (or UNDO) the zoom, drag a rectangle in the opposite direction (up/left).

Note

You may use mouseclicks to activate code associated with points in data Series. That OnClick behaviour will override zoom behaviour. You can set toggle between OnClick events and zoom with the CancelMouse property.

You may enable or disable zoom functionality in the Chart Editor - Chart page, General tab. The option, AllowZoom accesses the Chart property, also changeable by code:

Chart1.AllowZoom := False;

‘False’ deactivates zoom.

Zoom can also be obtained via coding. It is necessary to obtain the screen pixel co-ordinates for the area in which you wish to do the zoom.

Example 1:

Zoom an area with "pixel" co-ordinates:

Rect.Left  := 123 ;

Rect.Top   := 67 ;

Rect.Right := 175 ;

Rect.Bottom:= 100 ;

Chart1.ZoomRect( Rect );

Example 2:

Zoom an area with point value co-ordinates:

You need first to translate from value to pixel co-ordinates. To do so, you can use the Axis or Series components.

Rect.Left  := LineSeries1.CalcXPosValue(22.5);

Rect.Top   := LineSeries1.CalcYPosValue(5000);

Rect.Right := LineSeries1.CalcXPosValue(57.6);

Rect.Bottom:= LineSeries1.CalcYPosValue(15000);

Chart1.ZoomRect(Rect);

Backimage

You can add more information to your Chart or simply enhance its appearance by adding a bitmap as a backdrop.

Bitmap as a Chart backdrop
You will find the parameters to define your Chart backdrop in the General tab of the Chart page of the Chart editor.


Click events

Topics in this section include:

OnClickSeries

OnClick

Series OnClick and OnDblClick

Chart OnClickSeries

The TChart event, OnClickSeries, permits access to any active Series in your Chart. Put the following code into your project to get an idea of the possibilities. To access the event and add the procedure definition to your project, select your Chart and open the Object Inspector. Select the events tab to find OnClickSeries. Double-click on OnClickSeries.

procedure TForm1.DBChart1ClickSeries(Sender: TCustomChart;

  Series: TChartSeries; ValueIndex: Longint; Button: TMouseButton;

  Shift: TShiftState; X, Y: Integer);

begin

  ShowMessage(' Clicked Series: '+Series.Name+' at point: '+    inttostr(valueindex));

end;

The valueindex refers to the index of the Series data point (point, bar, etc.) within the Chart. You may use it to access the X and Y value. For example:

begin

ShowMessage(' Clicked Series: '+Series.Name+' at point: '+ Floattostr(Series.XValue[valueindex]) + ',' + Floattostr(Series.YValue[valueindex]));

end;

Chart OnClick

You may use the OnClick event of the Chart to get the same information.

procedure TForm1.DBChart1Click(Sender: TObject);

var t,tmp:Longint;

    x,y:Double;

begin

  Series1.GetCursorValues(x,y);

  for t:=0 to DBChart1.SeriesCount-1 do

  begin

    tmp:=DBChart1.Series[t].GetCursorValueIndex;

    if tmp<>-1 then

       ShowMessage(' Clicked Series: '+DBChart1.Series[t].Name+' at point: '+inttostr(tmp));

  end;

end;

Series OnClick and OnDblClick

The Series OnClick event catches click events at Series level. Thus for multiple Series Charts you are able to restrict access to the data of a specific Series. To access the OnClick event of the Series you must select the Series in the Object Inspector and go to the events tab.

procedure TForm1.Series1Click(Sender: TChartSeries; ValueIndex: Longint;

  Button: TMouseButton; Shift: TShiftState; X, Y: Integer);

begin

  ShowMessage(' hello: '+Sender.Name+' at point: '+inttostr(valueindex));

end;


Custom drawing on the Chart

If you require to add textboxes or other shapes relative to Chart axis the Shape Series may be the best choice. If the shape Series doesn’t match your specific requirement you may draw your own lines and/or shapes on the Chart.

TeeChart offers access to the Chart area by axis or by screen pixel. The TeeChart demos, UDraw.pas and Uhighlo.pas, are useful references for custom drawing on a Chart.

Topics in this section include:

Calculating Co-ordinates

Axis' Value to Screen co-ordinate Methods

CalcPosValue

CalcPosPoint

CalcSizeValue

CalcYPos and CalcXPos

Series' Value to Screen co-ordinate Methods

CalcPosValue

CalcXPos and CalcYPos

XScreenToValue and YScreenToValue

Chart Canvas

Writing to the Canvas

Internal bitmap

Repainting

When to draw ?

Chart Regions

Drawing

Calculating Co-ordinates

This chapter explains how to convert from Point co-ordinates to pixels and vice-versa. Also how to determine the exact co-ordinates for each graphics element in Chart components.

Point Values are expressed in user custom scales. 	Chart Axis are responsible for converting point values into suitable X and Y screen pixel co-ordinates for displaying them.

Both Axis and Series components have several functions to convert from screen co-ordinates (in pixels) to Axis or points values (in user-defined units).

The difference between using Axis or Series conversion functions is that Axis will only interpret co-ordinates for the topmost position in 3D mode, while Series will adjust co-ordinates to their Z order position.

Note:  Using conversion functions is only valid after a Chart component has been drawn, either to screen or to a private hidden Canvas.

Axis' Value to Screen co-ordinate Methods

CalcPosValue

You can calculate the screen position for a given value using any Axis:

 	  Var MyPos : Longint ;

  MyPos := Chart1.LeftAxis.CalcPosValue( 100.0 );

MyPos holds now the pixel co-ordinate for “100.0” on Chart1 Left Axis ( Vertical ), being “100.0” a floating value in Axis scales.

You can use this co-ordinate to custom draw or to calculate mouse clicks. See chapters below.

If you want to convert from pixel co-ordinates to Axis values, you can use the opposite function:

CalcPosPoint

  Var MyValue : Double ;

  MyValue := Chart1.LeftAxis.CalcPosPoint( 100 );

MyValue holds now the Axis value co-ordinate for “100” on Chart1. Left Axis ( Vertical ), being “100” a screen pixel co-ordinate.

Note: Pixel co-ordinates start from 0, being 0,0 the Chart origin point. This is valid for screen, but when drawing to metafiles, drawing to custom canvases or printing, Chart origin point can optionally be different than 0,0.

The Chart1.ChartBounds property returns the origin and ending co-ordinates for the Chart bounding rectangle.

CalcSizeValue

Axis have another function to calculate how much screen space represents a given Axis range:

Var  Space : Longint ;

Space := Chart1.LeftAxis.CalcSizeValue( 1000 );

Remember Axis can be DateTime and you can for example convert a Date Range period in pixels:

Var  Space : Longint ;

Space := Chart1.BottomAxis.CalcSizeValue(

EncodeDate( 2000,12,31) - EncodeDate( 2000,1,1) );

CalcYPos and CalcXPos

You could use CalcYPos and CalcXPos. When drawing using the XPos and YPos co-ordinates remember that the co-ordinate 0,0 is Top,Left of the Chart rectangle, ChartRect. ChartRect is the area enclosed by the 4 axis of the Chart.

The following example draws a line from an arbitary point from the Y-axis across the Chart. Note the use of canvas properties.

procedure TForm1.Button1Click(Sender: TObject);

var

MyHalfwayPoint, YPosition:longint;

Begin

With Series1.YValues do

   MyHalfwayPoint:=round(((MaxValue-MinValue)* 0.5) + MinValue);

{ then calculate the Screen Pixel co-ordinate of the above value }

    	YPosition:=DBChart1.LeftAxis.CalcYPosValue(MyHalfwayPoint);

   With DBChart1.Canvas do

      begin

{ change pen and draw the line avoiding the

3D areas and axis of the Chart - Height3D,Width3D}

      	Pen.Width:=3;

      	Pen.Style:=psSolid;

      	Pen.Color:=clBlack;

         with DBChart1 do

         begin

      	MoveTo(ChartRect.Left,YPosition);

      	LineTo(ChartRect.Left+Width3D,YPosition-Height3D);

      	LineTo(ChartRect.Right+Width3D,YPosition-Height3D);

         end;

   	end;

end;

Series' Value to Screen co-ordinate Methods

Series have similar methods for converting co-ordinates to point values and vice-versa. The main difference is that by using the Series method you don’t need to know the exact Axis component for calculations.

This is a big advantage when having Series associated to Right or Top Axis, or multiple Series associated to each Axis.

CalcPosValue

This code calculates where in the screen the Series1 point with value 1000 is located:

Var MyPos : Longint ;

MyPos := Series1.CalcPosValue( 1000 );

or...

MyYPos := Series1.CalcPosValue( Series1.YValue[ 0 ] 	) ;  { <-- first point }

CalcXPos and CalcYPos

You can calculate both X and Y co-ordinates for a specific point or for a specific point value:

MyXPos := Series1.CalcXPos( EncodeDate( 2000, 12, 31) ) ;

or...

MyXPos := Series1.CalcXPos( Series1.XValues.Last );  	{ <-- last point }

XScreenToValue and YScreenToValue

To convert from screen pixels to point values, use:

Var MyValue : Double ;

MyValue := Series1.YScreenToValue( Y ) ;

(and XScreenToValue for horizontal co-ordinates).

You can query the point under a given pair of XY screen co-ordinates using the Series.Clicked function. (See Mouse Clicks chapter).

Chart Canvas

Chart.Canvas is a standard Delphi Canvas. You may control the appearance of your Chart using Canvas properties. See TCanvas help in Delphi for a full list of properties.

Writing to the Canvas

The following example divides the area of the backdrop of the Chart rectangle into 5 equal segments and colours them according to the colour array.

procedure TDrawForm.LineSeries1BeforeDrawValues(Sender: TObject);

Const

   MyColors:array[1..5] of TColor=

    ( clNavy,

      clGreen,

      clYellow,

      clRed,

      $00000080 { very red }

      );

var t,partial:Longint;

    tmpRect:TRect;

With Chart1 do

  	Begin

    	{ we will divide the total Chart width by 5 }

    	tmpRect:=ChartRect;

    	tmpRect.Right:=tmpRect.Left;

    	partial:=ChartWidth div 5;

    	{ change the brush style }

    	Canvas.Brush.Style:=bsDiagCross;

    	Canvas.Pen.Style:=psClear;

    	{ for each section,fill with a specific color}

    	for t:=1 to 5 do

    	Begin

     	 { adjust the rectangle dimension }

      	tmpRect.Right:=tmpRect.Right+partial+1 ;

      	{ set the brush color }

      	Canvas.Brush.Color:=MyColors[t];

      	{ paint !!! }

      	With tmpRect do

        	Canvas.Rectangle( Left+Width3D,Top-	Height3D,Right+Width3D,Bottom-Height3D );

      	{ adjust rectangle }

      	tmpRect.Left:=tmpRect.Right;

    	end;

   	end;

end;

Internal bitmap

TChart components have an internal bitmap object, which is used when drawing as a hidden “buffer”. When drawing is finished, this “buffer” is copied to the screen video memory to display it.

TChart Canvas property returns the internal bitmap Canvas object.

Note:  BufferedDisplay property controls if the internal bitmap is used. Using this bitmap no flicker occurs when redrawing real-time Charts. Also, some Charts with many points can take advantage of faster drawing speed on memory bitmaps instead of direct drawing to slower video card memory chips.

Drawing to a bitmap Canvas is exactly the same as drawing to another “real” Canvas in terms of source code transparency and results.

Note: When drawing to a metafile or printing, the Chart Canvas property refers to metafile or printer Canvas objects. No bitmap is used in these cases.

After a Chart has been drawn onto the internal bitmap, and its copied onto the screen canvas, Chart Canvas property refers to the original “real” Chart Canvas.

Repainting

You should call Chart1.Repaint or Series1.Repaint to force a Chart component to draw again.

When to draw ?

The order in which you draw to the Canvas is important.

If you wish Custom drawn items to appear above Chart Series you should use the Chart OnAfterDraw event. The Chart1.OnAfterDraw event is fired each time the Chart component is redrawn, just before copying the internal bitmap to screen.

You can place Custom drawn items above the Chart grid and below the Chart Series by placing your code in the Chart OnBeforeDrawSeries event.

Key Chart Paint events:

OnBeforeDrawChart

OnBeforeDrawAxes

OnBeforeDrawSeries

OnAfterDraw

Chart Sub components also have events that may be used to Paint to the Canvas.

Eg.

OnAfterDrawValues

OnBeforeDrawValues

An example of use of OnBeforeDrawValues is the TeeChart multiple Pie example which sets the Chart rectangle plotting area before plotting the values of the Series.

Advanced: For more control you might want to create your own Chart class and override the several Draw... virtual methods.

Chart Regions

The biggest rectangle around a Chart is at ChartBounds property. ChartWidth, ChartHeight,  ChartXCenter and ChartYCenter are pre-calculated co-ordinates based on ChartBounds property.

Axis are drawn inside this space. The ChartRect property returns the bounding rectangle for Axis ( same in 2D and 3D ).

Chart Legend has the RectLegend public property which defines the Legend rectangle bounds.

Chart Title and Foot have TitleRect public properties.

In 3D Charts, each Series is assigned a specific section among the “Z” ( depth ) axis.

The Chart Width3D and Height3D are the dimensions of the 3D depth, in pixels. SeriesWidth3D and SeriesHeight3D are the dimensions for each individual Series in a Chart.

Drawing

Lets start drawing with a basic example.

This code draws an horizontal line just at the middle of Chart1:

procedure TForm1.Chart1AfterDraw(Sender: TObject);

begin

  With Chart1 do

  	begin

    	Canvas.Pen.Color:=clYellow;

    	Canvas.MoveTo( ChartBounds.Left,

ChartYCenter );

    	Canvas.LineTo( ChartBounds.Right, 	ChartYCenter );

  	end;

end;

Drawing inside Axis space:

procedure TForm1.Chart1AfterDraw(Sender: TObject);

begin

  With Chart1 do

  begin

    	Canvas.Pen.Color:=clYellow;

    	Canvas.MoveTo( ChartRect.Left, ChartYCenter );

   Canvas.LineTo( ChartRect.Right, ChartYCenter );

  end;

end;

Drawing a line at each point in Series1 :

procedure TForm1.Series1AfterDrawValues(Sender: TObject);

var t ,x,y : Longint ;

begin

   for t := 0 to Series1.Count - 1 do

   	begin

     	x:=Series1.CalcXPos( t );

    	y:=Series1.CalcYPos( t );

   	Chart1.Canvas.MoveTo( x-8, y-8 );

   	Chart1.Canvas.LineTo( x+8, y+8 );

     end;

end;

Note: Drawing Text

Always set Chart1.Canvas.Font.Height to a negative value

instead of using Font.Size if want same font sizes on screen

and on printer or metafiles.


Working with Axes

Topics in this section:

Setting Axis scales

DateTime Axis

Logarithmic Axis

Inverted Axis

Axis Styles & Increment

DateTime Increment

Grid lines

Axis Labels

CustomDraw (Axis)

Custom Axes

Setting Axis scales

Chart components have five standard axes: LeftAxis, RightAxis, TopAxis, BottomAxis and DepthAxis. Each axis is an instance of TChartAxis component class. Unlimited Custom Axes may be added.

Axes are responsible of calculating pixel co-ordinates for Series points and to allow any valid range so scroll and zoom can be always performed. As new Series are inserted, or new points are added to the Series, Axes recalculate, by default, their Minimum and Maximum values.

You can turn off automatic recalculation of Axis scales by setting the Automatic property to false:

Chart1.LeftAxis.Automatic := False ;

Also, both the Axis Minimum and Axis Maximum values can optionally be independently automatic or not.

Chart1.LeftAxis.AutomaticMaximum := False ;

Chart1.LeftAxis.AutomaticMinimum := True ;

You can change Axis scales using the Minimum and Maximum properties:

With Chart1.LeftAxis do

begin

    Automatic := False ;

    Minimum:=         0 ;

    Maximum:= 10000 ;

end;

or using the Axis SetMinMax method:

Chart1.LeftAxis.SetMinMax( 0, 10000 );

DateTime Axis

Note:

An Axis contains DateTime scales when the associated Series components have XValues.DateTime or YValues.DateTime properties True. There is no DateTime property for Axis.

Changing scales in DateTime Axis is the same as for non-datetime values:

With Chart1.LeftAxis do

begin

 	    Automatic := False ;

    Minimum:=  EncodeDate( 1990, 3,16 ) ;

    Maximum:= EncodeDate( 2000, 5, 24 );

end;

Logarithmic Axis

An Axis can be set to Logarithmic only if Axis Minimum and Maximum are greater than or equal to zero. This is the only difference between setting linear and logarithmic scales.

Note:

Axis Labels are not displayed in logarithmic increments. You can generate custom Axis Labels (see OnGetNextAxisLabel and OnGetAxisLabel events and the Axis Labels section in this Topic).

Inverted Axis

An Axis can be Inverted so Axis Minimum and Maximum are swapped. We suggest you use Inverted:=True as little as possible as it can give misleading results due to its (normally) rarity of use.

Axis Styles & Increment

Axis can be displayed in several ways, with tick lines or without,

with grids or without, with Labels or without, and you can customise all formatting properties such as colours, fonts  and pen styles. The Axis Increment property controls the number of grid lines and labels and the distance between them.

By default it’s zero, meaning Axis will automatically calculate the Labels increment. Setting the Axis Increment property is independent of setting Axis scales. You can have automatic Axis Maximum and Minimum and a fixed Increment.

The Increment property grows automatically until all Axis Labels can be displayed. If you don’t want this automatic feature, set the Axis LabelsSeparation to zero:

Chart1.LeftAxis.LabelsSeparation :=  0 ;

Warning:

When LabelsSeparation is zero, no checking is performed against

labels size, so you must take care labels will not overlap each other.

The following code sets the vertical Axis Increment to 30:

Series1.Clear;

Series1.AddArray( [ 20, 50, 120 ] );

Chart1.LeftAxis.Increment:= 30;

By default, the first Axis label starts at nearest Increment. Setting RoundFirstLabel to False makes labels to start at Axis Maximum:

Chart1.LeftAxis.RoundFirstLabel := False ;

DateTime Increment

Use the predefined DateTimeStep array of constants to determine the Axis Increment on DateTime axis:

Chart1.BottomAxis.Increment := DateTimeStep[ dtOneMonth ] ;

And set the ExactDateTime property to True if you want Axis Labels to be at exact datetime boundaries, for example at 1st day of month.

Chart1.BottomAxis.ExactDateTime := True;

Note:

Logarithmic axis use the Increment property as linear.

Grid lines

Axis Grid lines are displayed at each Increment position, or at each Axis Label position. The Axis TickOnLabelsOnly property controls this feature:

Chart1.BottomAxis.TickOnLabelsOnly := False ;

Axis Labels

There are several Axis labelling styles. The Axis LabelStyle property control axis labelling modes:

Chart1.BottomAxis.LabelStyle := talValue ;

Possible values are:

talValue	Labels display Axis scales
talMark	Labels display Series Point Marks
talText	Labels display Series XLabels
talNone	No labels displayed
talAuto	Style is automatically calculated

When LabelStyle is talText, TeeChart will set it automatically to talValue if Series have no XLabels.

For talMark and talText styles, axis labels are displayed exactly at Series point positions, thus not using the axis Increment property.

You can customise labels text by using the OnGetAxisLabel event:

procedure TForm1.Chart1GetAxisLabel(Sender: TChartAxis;

  Series: TChartSeries; ValueIndex: Integer; var LabelText: String);

begin

  if Sender=Chart1.LeftAxis then

      if ValueIndex < 2 then LabelText :=’’ ;

end;

The OnGetNextAxisLabelEvent allows you to define where you want the Labels to appear. In this example, we want the Vertical Left Axis to show labels only for positive values, starting at zero and with 250 label increment.

procedure TAxisLabelsForm.Chart1GetNextAxisLabel(Sender: TChartAxis;

    LabelIndex: Longint; var LabelValue: Double; var Stop: Boolean);

  begin

    if Sender=Chart1.LeftAxis then

    Begin

      if LabelValue>=250 then LabelValue:=LabelValue+250

                         else LabelValue:=250;

    End;

    { we want more labels !! }

    Stop:=False;

  end;

The following example plots only the specified 3 Labels on the Left Axis then stops plotting Labels for that Axis:

procedure TForm1.Chart1GetNextAxisLabel(Sender: TChartAxis;

  LabelIndex: Integer; var LabelValue: Double; var Stop: Boolean);

begin

    if Sender=Chart1.LeftAxis then

    Begin

      Stop:=False;

      Case LabelIndex of

         0:  LabelValue:=50;

         1:  LabelValue:=80;

         2:  LabelValue:=110;

         else Stop:=True;

      end;

    End;

end;

CustomDraw (Axis)

CustomDraw adds more axes to your Chart - As many as you wish. CustomDraw adds an axis as a ‘copy’ of an existing axis at a new location. CustomDraw axes are not Custom Axes, they are copies of the original Standard Axes at a (normally) different location.

The following example populates a line Series with random data. And creates 2 additional axis. There are 3 configurable locations PosLabels, PosTitle and PosAxis to place, respectively, the labels, title and the axis. The last parameter, GridVisible , which is boolean, defines whether to extend the axis grid to the new axis.

procedure TForm1.FormCreate(Sender: TObject);

var

   t:integer;

begin

     Series1.XValues.DateTime := False;

     Chart1.BottomAxis.Increment:=0;

     For t:= -10 to 10 do

         Series1.addXY(t,Random(100),'', clTeeColor);

end;

procedure TForm1.Series1AfterDrawValues(Sender: TObject);

var posaxis,percent:longint;

begin

  percent:=50;

  With DBChart1 do

  begin

PosAxis:=ChartRect.Left+Trunc(ChartWidth*Percent/100.0);

   LeftAxis.CustomDraw(posaxis-10,posaxis-40,posaxis,True);

    	PosAxis:=ChartRect.Top+Trunc(ChartHeight*Percent/100.0);

   	BottomAxis.CustomDraw(posaxis+10,posaxis+40,posaxis,True);

  end;

end;

Custom Axes

With Chart Editor

Custom Axes may be added and configured at design time using the Chart Editor. Basic steps to bear in mind:

-	On Chart Editor Axis page use the “+” button to add an Axis

-	The new Axis is vertical with Left sided Labels by default. Go to the Poistion tab to optionally  set it to Horizontal and to set the Labels to the Otherside (Right or Top depending on whether Vertical or Horizontal axis)

-	Configure all Axis characteristics as per any Standard Axis. Important feature, as with Standard Axes is the Position tab that allows you to move and redimension the Axis to anywhere on the Chart

-	The Custom Axis must be associated with one or more Series. Go to the Series General tab and select the Axis for the Series

By Code

The following code adds 2 Axes, vertical and horizontal and associates them to a Series. The axes will scale by default to best fit the data to the Chart, so after adding the Series then adding the custom axes you will note that the Custom Axes scale is (most likely, depending on data) different to the Standard Axis scale. To test the following code, start a new project, add a TChart to a Form and a Bitmap Button, add 2 Series to the Chart with the Chart Editor, then paste in the following code:

procedure TForm1.FormCreate(Sender: TObject);

begin

  Series1.FillSampleValues(10);

  Series2.FillSampleValues(10);

end;

procedure TForm1.BitBtn1Click(Sender: TObject);

var

 tmpVertAxis: TChartAxis;

 tmpHorizAxis: TChartAxis;

begin

  {Add vertical Axis}

  Chart1.CustomAxes.Add;

  tmpVertAxis:=Chart1.CustomAxes[0];

  tmpVertAxis.PositionPercent:=50;

  Series1.CustomVertAxis:=tmpVertAxis;

  {Add horizontal Axis}

  Chart1.CustomAxes.Add;

  tmpHorizAxis:=Chart1.CustomAxes[1];

  tmpHorizAxis.Horizontal:=True;

  tmpHorizAxis.Axis.Color:=clGreen;

  tmpHorizAxis.PositionPercent:=50;

  Series1.CustomHorizAxis:=tmpHorizAxis;

end;

The Custom Axes may be accessed via the Chart.CustomAxes list.


Series manipulation

This chapter documents how to manipulate Series and how to manipulate Series points and other Series internal data.

Note: Advanced.  Series and values code is mainly located at TEENGINE.PAS unit.

Topics in this section:

Creating Series at runtime

SeriesList Collection

SeriesCount property

Deleting Series

Changing the Series Z order at runtime

Adding Points

Adding arrays of data

Null Values

Controlling Points Order

XY Points

Point Limits

Series Points

Retrieving and modifying Points

Locating Points

Point Statistics

Notifications

Point Colours

Point Labels

Changing the Series type at runtime - Advanced

Creating Series at runtime.

Series can be created at runtime just as like any other Delphi component:

First you need a Series variable:

Var MySeries : TBarSeries ;

{Then create the component:}

MySeries := TBarSeries.Create( Self );

{And then assign it to the desired Chart component:}

MySeries.ParentChart := Chart1 ;

{Now you can add points to MySeries or do whatever you can do with a design-time created Series.}

Shortcut:

{If you don’t need access to MySeries, the above code can be reduced to just one line of code:}

Chart1.AddSeries( TBarSeries.Create( Self ) );

{Class references:

Or you can use a Series class reference:

First declare the Series class variable:}

Var MyClass : TChartSeriesClass;

{Then set the desired Series class type:}

MyClass := TBarSeries ;

{Now you can create the Series component:}

Chart1.AddSeries( MyClass.Create( Self ) );

SeriesList collection

Chart components store all Series in SeriesList property, a Delphi TList object.

You have read-only access to this list in three ways:

A) Using the SeriesList property:

MySeries := Chart1.SeriesList [ 0 ]

B) Using the Series array property:

MySeries := Chart1.Series [ 0 ]

C) Or using the Chart1 default property:

MySeries := Chart1 [ 0 ]

Either way does the same.

SeriesCount property

The Chart1.SeriesCount property returns the number of Series in the SeriesList.

You can use SeriesCount to traverse all Chart Series:

for t := 0 to Chart1.SeriesCount - 1 do

With Chart1.Series [ t ] do

begin

   SeriesColor := clBlue ;

end;

Deleting Series

Series can be hidden in three ways:

A) Setting the Series Active property:

Series1.Active := False ;

B) Removing the Series from their parent Chart:

Series1.ParentChart := nil;

C) Destroying the Series completely:

Series1.Free ;

Changing the Series Z order at runtime.

In 3D mode (when Chart1.View3D is True ), all Series are assigned a Z order position. That is, the order where Series will be drawn, starting with the far most Series on the Chart 3D space.

You can control the order Series will be drawn, using these methods:

Chart1.ExchangeSeries( 0, 1 );

or...

Chart1.SeriesUp( Series1 );

Chart1.SeriesDown( Series1 );

The Series.ZOrder integer property returns the corresponding Z position for the Series.

Some Series in certain modes share the same ZOrder, like Stacked BarSeries. 	You can check if more than one Series has the same Z order using these functions:

if Series1.FirstInZOrder then .....

if Series1.MoreSameZOrder then .....

Adding Points

Every Series type has, at least, 2 values for each point. These values are designed as X and Y point co-ordinates.

Note: Values are defined as “Double” floating point variables.

Extended Series types have more than 2 values, like BubbleSeries has X, Y and Radius	values for each point.

So, each Series type has its appropriate method to add points, although the most common Series types like Line, Bar, Point and Area share the generic AddY method to add points.

The following code empties a TPieSeries and adds some sample values to it:

Series1.Clear ;

Series1.Add(  1234, ‘USA’, clBlue );

Series1.Add(  2001, ‘Europe’, clRed );

For extended Series types, please refer to each specific Series reference to know which method should be used to add points.

The Series AddArray method can be used in some situations:

Series3.Clear;

Series3.AddArray([ 1234, 2001, 4567.12 ] );

AddArray does not Clear the Series before adding points.

You can express points as constants or variables:

Series3.AddArray([ Table1Sales.AsFloat, 123, 	MyTotal ] );

Adding arrays of data

To add an array of data to a Chart Series simply allocate the array to the Series.

Example

procedure TDynArrays.Button1Click(Sender: TObject);

Var X,Y : Array of Double;   // TChartValues

    t   : Integer;

    Num : Integer;

begin

  { number of points here using an Editbox to set Array size}

  Num:=StrToInt(Edit1.Text);

  { allocate our custom arrays }

  SetLength(X,Num);

  SetLength(Y,Num);

  { fill data in our custom arrays }

  X[0]:=0;

  Y[0]:=Random(10000);

  for t:=1 to Num-1 do

  begin

    X[t]:=t;

    Y[t]:=Y[t-1]+Random(101)-50;

  end;

  { set our X array }

  With Series1.XValues do

  begin

    Value:=TChartValues(X);  { <-- the array }

    Count:=Num;               { <-- number of points }

    Modified:=True;           { <-- recalculate min and max }

  end;

  { set our Y array }

  With Series1.YValues do

  begin

    Value:=TChartValues(Y);

    Count:=Num;

    Modified:=True;

  end;

  Chart1.UndoZoom; { <-- remove zoom (optional) }

  { Show data }

  Series1.Repaint;

end;

Null Values

In some circumstances you might have no values for specific points. You should then add these points as “zero” or add them as “null” values.

Null values will not be displayed, while “zero” values will be displayed as usual.

The following code adds several points and a null point:

With Series1 do

begin

  Clear ;

  AddY( 10, ‘John’, clGreen );

  AddY( 20, ‘Anne’, clYellow );

  AddY( 15, ‘Thomas’, clRed );

  AddNull( ‘Peter’ );

  AddY( 25, ‘Tony’, clBlue );

  AddY( 20, ‘Mike’, clLime );

end;

Each Series type will handle null values in different ways.

Bar, HorizBar, Line, Area and Point do not display null points.

PieSeries use null values as “zero”.

Controlling Points Order

Points can be optionally sorted either by their X values or Y values. The Series.XValues and Series.YValues Order property controls the points Order:

Series1.XValues.Order := loAscending ;

Possible values are: loNone, loAscending or loDescending.

By default, XValues Order is set to loAscending, and YValues Order to loNone, which means new added points are ordered by their X co-ordinate. For non XY Charts, the X co-ordinate is always the point position, starting from zero.

The point Order is used by Series components to draw their points.

Note: Order must be set before points are added to the Series.

You can change the Order property at run-time, followed by a call to Sort method:

Example:

Drop a TChart onto a Form, add a Line Series.

Drop a TButton and assign this code to Button1Click:

Series1.AddArray([ 5, 2, 3, 9]);

Now drop another TButton and add this code to Button2Click:

With Series1 do

begin

    YValues.Order:=loAscending;

    YValues.Sort;

    Repaint;

end;

Now execute and press Button1 to fill Series1, and press Button2 to see Series1 points drawn on Series1 YValues Ascending order, but having the original X co-ordinates.

Note: If you aren’t using X co-ordinates, one more line of code is required.

Drop a new TButton (Button3) and add this code to Button3Click:

Series1.XValues.FillSequence;

Series1.Repaint;

Now points will be “re-numbered”, starting from zero among Series1 XValues axis. This will re-order points so now they will be drawn as if they were originally added to the Series in their new order.

This “two-step”  point sorting allows Line Series to draw with vertical orientation.

XY Points

Adding X co-ordinates to points makes Series components calculate user specific horizontal point positions.

Note: Bar Charts can be difficult to interpret with X co-ordinates.

Pie Series do not allow X co-ordinates.

To add X co-ordinates, simply use the AddXY method:

Drop a TChart, add a Point Series:

With Series1 do

begin

  Clear ;

  AddXY(  10, 10, ‘Barcelona’, clBlue );

  AddXY(  1, 10, ‘San Francisco’, clRed );

end;

Note:  If you use a Bubble Series, use the TBubbleSeries AddBubble method.

Remember to set XValues.Order to loNone if don’t want points to be sorted on their X co-ordinate.

Point Limits

16bit Delphi 1.0

(TeeChart versions up to v4) Maximum 16380 Series per Chart, and 16380 points per Series.

32bit Delphi

Maximum 134217727 points per Series and same for Series per Chart.

Deleting Points

Simply call the Series.Delete method, passing the point index as the argument. Point index starts at zero.

Series1.Delete( 0 );  { <-- removes the first point in Series1 }

Series1.Delete( Series1.Count - 1 ) ;  { <-- removes the last point in Series1 }

An exception “List out of bounds” will be raised when attempting to Delete a non-existing point, so always check there are enough points in the Series prior to delete them:

if Series1.Count > MyIndex then Series1.Delete( MyIndex );

Calling Delete forces re-calculation of Functions and repainting of the Chart.

Series Points

Retrieving and modifying Points

Once points have been added, you can retrieve their co-ordinates or change them.

The XValues and YValues array properties can be used:

Var MyValue : Double ;

MyValue := Series1.YValues[ 0 ] ;   { <-- retrieves 	the first Y value }

You can traverse these arrays to perform calculations:

Var MyTotal : Double ;

t : Integer ;

MyTotal := 0 ;

for t:= 0 to Series1.Count - 1 do

MyTotal := MyTotal + Series1.YValues[ t ] ;

ShowMessage( FloatToStr( MyTotal ) );

Extended Series types have additional array properties, such as

BubbleSeries RadiusValues.  You can access these properties in

the same way as with XValues or YValues arrays:

if BubbleSeries1.RadiusValues[ Index ] > 100 then .....

Modifying point values can be performed using the above properties:

Series1.YValues[ 0 ] := Series1.YValues[ 0 ] + 1 ;

Series1.RefreshSeries ;

Locating Points

The XValues and YValues Locate function searches a specific

value in the List and, if found, returns the value Index, starting

from zero.

Var MyIndex : Integer ;

MyIndex := Series1.YValues.Locate( 123 );

if MyIndex = -1 then

  ShowMessage(‘  123 not found in Series1 !! ‘ )

else

 	  ShowMessage(‘  123 is the ‘+IntToStr( MyIndex+1 )+’ th point in Series1 !! ‘ );

Point Statistics

XValues and YValues properties maintain the following statistical figures:

Total	The sum of all values in the list.

TotalABS	The sum of all values as absolute (positive).

MaxValue	The maximum value in the list.

MinValue	The minimum value in the list.

You can call manually to RecalcMinMax method to recalculate MinValue and MaxValue. Total and TotalABS are maintained automatically.

These values are used to speed up several Axis scaling calculations and are used as helpers for percent calculations.

TChartValueList object has several other methods and  properties to manipulate point values. Please refer to online help documentation.

Notifications

Whenever points are added, deleted or modified, the Series generates internal notification events. These events are used to recalculate Series that depend on other Series points.

Advanced:  You can use RecalcOptions property to control when recalculations are performed.

Point Colours

All Series maintain an internal List of colours. One for each point in the Series.

You can access this list with ValueColor array property, to retrieve or change point colours:

Var MyColor : TColor ;

MyColor := Series1.ValueColor[ 0 ] ;

Series1.ValueColor[ 1 ] := clBlue ;

TeeChart defines a generic colour constant named:  clTeeColor.

Points with clTeeColor colour will be drawn using the SeriesColor colour.

Delphi predefines constants for basic colours (clBlue, clRed, etc.). Colours can also be expressed in RGB format. Using a video colour depth of 16k colours or more results in better colour matching.

Point Labels

Each point has an associated text, called XLabel, and declared as a Delphi string.

Point Labels are used in Axis Labels, Chart Legend and Point Marks.

Labels are stored at Series XLabel array property.

You can access and modify XLabel point texts:

Series1.XLabel [ 0 ] := ‘Sales’ ;

Changing the Series type at runtime - Advanced

Every Chart type corresponds to a different Delphi Component.

Changing a Series type involves changing the Series component class.

That means a new Series of the new class must be created, old Series properties should be assigned to the new instance, and finally the old Series must be destroyed.

All this happens automatically when you manually change a Series type at design-time using the Chart Editor Dialog and the Gallery.

You can change a Series type at run-time calling:

ChangeSeriesTypeGallery(Self, MySeries );

Warning:

You should change your private Series components.

You can change also Series components owned by the Form,

but only if not using them after.

Var MySeries : TChartSeries ;

MySeries := Series1 ;

ChangeSeriesTypeGallery(Self, MySeries );


Printing Charts

This chapter explains how Charts are printed and which properties and methods are used to control the printing process.

Note:

Advanced. Printing methods are located in the CHART.PAS unit.

Topics in this section:

Printing

Margins

Resolution

Print, PrintLandscape....

PrintPartial

Multiple Charts per Page

Windows and printers limitations

Clipping

Rounding circles

Rotating fonts

Dotted Pen styles and Pen Width

From FAQ - Practical issues when printing TeeCharts

Introduction

Design issues

How to Print Proportionally?

Other problems

Printing Reference

More information:

Printing

Margins

When printing, you can specify which margins on the paper page should be left blank. The public PrintMargins:TRect property stores the desired paper margins expressed as percents of total page dimensions.

PrintMargins:=Rect(15,15,15,15); { default 15 % printing margins }

The TChart.ChartPrintRect:TRect function returns, after applying the printing margins, the space where the Chart component will be drawn expressed as logical canvas units (pixels or dots).

With PrintMargins you can define any area of any size inside the page.

Note:

When changing paper orientation, margins are recalculated.

Resolution

Charts are printed in metafile (WMF in 16bit, EMF in 32bit) format.

Metafiles are scaleable vector formats, so a “wysiwyg” effect can be achieved if sending to the printer how a Chart looks on screen. However, you might want to exploit the printer’s bigger resolution capabilities versus screen displays.

The TChart.PrintResolution integer property controls how a Chart is scaled when sending it to the printer. By default PrintResolution is zero. Setting it to a negative value in the percentage range from zero to -100 makes the Chart proportionally bigger so there’s more space for Axis Labels. Smaller fonts are used as they will be clearer on paper than on screen.

Setting it to a positive value makes font sizes bigger.

Print, PrintLandscape....

Several methods exist to print a Chart component:

Print;

PrintRect(Const R:TRect);

PrintOrientation(AOrientation:TPrinterOrientation);

PrintPortrait;

PrintLandscape;

All the above methods will do the same, print a Chart on a new page and eject (form feed) the page:

Chart1.Print ;

Will print a Chart1 in the current printer’s paper orientation.

With PrintRect you can specify a custom Chart size and location. The default location and size is determined by ChartPrintRect function, which applies PrintMargins margins.

Delphi’s Printers unit contains the TPrinter object used for all Chart print methods.

PrintPartial

More advanced printing control can be obtained using the following methods:

Procedure PrintPartial(Const PrinterRect:TRect);

Procedure PrintPartialCanvas( PrintCanvas:TCanvas;

                                  Const PrinterRect:TRect);

Both will print a Chart component, BUT WILL NOT create a new printer page or eject it. You can print both your own text and graphics and Chart components on the same paper page.

Multiple Charts per Page

An example of PrintPartial method is located at BASIC.PAS unit under TeeDemo project.

Four Chart components are printed on a single page, optionally with more resolution.

Windows and printer limitations

Metafiles are very good as they are small and fast and scaleable.

Some limitations occur when using metafiles, as described in Microsoft Knowledge Base ( www.mskb.com ). TeeChart inherits those limitations:

Clipping

Clipping is stored in physical co-ordinates in metafiles. This means moving or scaling a clipped metafile will not scale or move the clipping region, giving undesirable results.

TeeChart does not draw partial points, so no clipping. Drawing on zoomed Charts will probably show partial points outside the Chart axis.

Rounding circles

As metafiles can be scaled, circles will be converted to ellipses when scaling.

Rotating fonts

Rotated fonts can not be exactly aligned on non-proportionally scaled metafiles.

Dotted Pen styles and Pen Width

Non solid pens (dots, dashes), can be drawn as solid with scaled metafiles.

From FAQ - Practical issues when printing TeeCharts

This section explains how TeeChart components are printed, and describes how to improve printing.

Introduction

Design issues

How to Print Proportionally?

Other problems

Printing Reference

More information:

Introduction

The TeeChart library sends Charts to the printer using a Windows graphic format known as "metafile". This format has several advantages and disadvantages over using the bitmap format:

- It's much smaller, because graphic information is stored in vector instructions, instead of pixels. This results in a faster printing speed in most cases.

- The printer doesn't need to have more memory to print 'large' images (Charts).

- Due to be a sequence of instructions instead of a fixed array of pixels, a metafile can be resized ( or "stretched" ) without losing resolution, and with greater accuracy.

- New printers support metafile format natively, via software driver or via "gdi hardware".

With Windows 32-bit (Windows 98, 2000 and Windows NT), an extended metafile format is implemented. This is known as "enhanced metafile". Metafiles have the extension:  "*.wmf" and enhanced metafiles:  "*.emf".

Design issues

The main goal of using metafiles in TeeChart, is to provide "wysiwyg" (what you see is what you get). That is, printed Charts should look as close as possible to how they look at screen.

To do this, TeeChart creates a metafile of the Chart image, and then sends this metafile to the printer. At this point, the Windows GDI module and the Windows Printer driver will take care of "painting" the Chart image on paper. This involves "stretching" or "resizing" the metafile, from screen coordinates to printer logical pixels.

Example:

A Chart on screen is at rectangle:

 Left  : 100

 Top   : 100

 Right : 300

 Bottom: 400

And it gets printed at this paper rectangle:

 Left  : 400

 Top   : 1000

 Right : 1200

 Bottom: 1500

In this example, the Chart should be rescaled both

in width and height:

screen Width = 300 - 100 = 200

paper Width = 1200 - 400 = 800

relation screen / paper = 800 / 200 = 4  <---

screen Height = 400 - 100 = 300

paper Height = 1500 - 1000 = 500

relation screen / paper = 500 / 300 = 1.666...  <---

The problem is the relation between the horizontal and vertical increments is not the same:

 4 <> 1.666...

This means the Chart will be expanded more in the horizontal dimension than in the vertical dimension. In this case, Windows increases font sizes and pen widths using the new dimensions.

Note: Windows 16-bit ( 3.1, 3.11 ) do not resize fonts as it does Windows 32-bit (95 and NT).

Text can overlap other Chart sections and look bad positioned. To fix this, see below "How to print proportionally?"

Windows 32-bit does a better job using the enhanced metafile format, so text dimensions are calculated precisely.

How to Print Proportionally?

Some printers can show problems when printing Charts *without* using proportional printer margins. Specially in Windows 16-bit with Delphi 1.0

The attached code can be used generically in your applications to calculate the optimal printer

printer margins so the relation between Chart Width and Height on screen is the same as on paper.

Another approach is to resize the Chart onscreen to match the proportion of the printer paper:

Chart1.Height:=Round(1.0*Printer.PageHeight*Chart1.Width/Printer.PageWidth);

Chart1.Print;

Other problems

Increasing resolution:

The metafile format is not aware of the "resolution" concept. This is means resolution information is not stored inside the metafile image. You can modify the Chart "resolution" *before* printing,

by setting this property:

Chart1.PrintResolution := -100 ;

Negative values (like -100 above), represent the porcentual increment in resolution. Zero means "wysiwyg".

More resolution is obtained by making all Chart fonts smaller and thinner lines. The metafile size is bigger when using more resolution. Increasing resolution can improve inaccuracy in buggy printer drivers calculations.

Printing non-solid lines:

In some printer / windows combinations, non-solid pen lines such as "dot" or "dash" will be printed as solid. This happens specially in some HP Laserjet printers. It seems the only workaround is to set the Chart Pen Width properties to Zero:

Chart1.LeftAxis.Grid.Width := 0;

Increasing resolution ( see above ) can make the printer to show non-solid lines.

Colors:

Many printers accept only a subset of the available Colors. This means setting a Chart color to a non-supported palette color may result in that color not being used by the printer, thus not drawing anything. In this situations, try with "well known" solid colors like "clRed, clBlue, clYellow, clGreen".

Some printers include a "Color Mapping" configuration dialog. (At Printer Properties dialog).

Printing directly:

Drawing a Chart directly onto a Printer GDI Handle or Canvas is also possible. The following code does it:

 Uses Printers;

 With Printer do

 begin

   BeginDoc;

   try

     Chart1.Draw( Canvas, Rect( 0,0,PageWidth,PageHeight ) );

   finally

     EndDoc;

   end;

 end;

You will see several problems printing directly:

-- The Chart background is gray color ( instead of white ).

-- Font sizes are extremely small.

-- There are many axis grid lines.

-- Lines are very thin.

One way to solve the above problems is using the metafile printing mode, described in this document. Another way (much more complicated) is to change all Font sizes and pen Width properties.

Printer driver settings:

Try to use always the latest "good" printer driver version. Try changing the Windows Printer driver resolution settings, and the spooler method (in Windows NT) to both "EMF" and "RAW" modes. "EMF" means all output is sent to the printer in metafile format.

Printing Reference

See the help file for extended information and examples on the following properties and methods

Printing Properties:

Properties involved in Chart printing are:

Chart1.PrintMargins

  The percentual space at the four sides of the paper page.

Chart1.PrintResolution

  The relation between screen dimensions and paper dimensions.

Printing methods:

The TeeChart control has several methods designed for printing:

Methods that print *and* eject the printed page:

These are the default and more used TeeChart printing methods.

Chart1.Print

  Uses default paper orientation and margins.

Chart1.PrintPortrait

  Sets paper in Portrait and uses default margins.

Chart1.PrintLandscape

  Sets paper in Landscape and uses default margins.

Chart1.PrintRect

  Uses default paper orientation and the Rect parameter to position the Chart on the page.

Methods that do not eject the printed page:

These methods allow printing more than one Chart in the same paper page, or print other things and Chart components on the same page.

With these methods you need to call Printer.BeginDoc and EndDoc yourself. See Delphi TPrinter documentation and the UPRINT.PAS and BASIC.PAS units in TeeChart TEEDEMO project.

Chart1.PrintPartial

   Draws a Chart to the Printer Canvas at the passed rectangle.

Chart1.PrintPartialCanvas

   Draws a Chart to the passed Canvas at the passed rectangle.

Related methods and properties:

Not directly involved with printing, but useful for advanced printing:

Chart1.Draw

   Draws a Chart to the passed Canvas, in screen "mode".

   "Screen mode" means with gray background and without

   using the metafile format.

   This method draws directly to the Canvas.

Chart1.TeeCreateMetafile

   Function that returns a metafile image of the Chart,

   with the passed Rect coordinates.

Chart1.Metafiling

   Boolean property indicating the Chart is now drawing

   onto a metafile image.

Chart1.Printing

   Boolean property indicating the Chart is now drawing

   onto a Printer Canvas.

More information:

Information about printing and metafiles can be found at Microsoft Windows 32-bit SDK help file:"Win32.hlp"

Use the "Help Contents" (not the index) and scroll-down up to the Metafiles chapter.

See the Delphi's TMetafile and TMetafileCanvas objects in Delphi's helpfile.


Chart Zoom and Scroll

Scrolling and Zooming a Chart is simply setting its Axis scales to the desired values. After zooming or scrolling a Chart, all Series will repaint their points in their new positions.

Note: Pie Series can’t be scrolled or zoomed. You can control Pie dimensions using Chart margins or Pie custom radius properties.

Topics in this section:

Zoom

Animated Zoom

Zooming by code

Undoing Zoom

Zoom Events

Scrolling

Scroll event

Controlling scroll

Keyboard Scrolling

Zoom

Charts can be zoomed programmatically or by user interaction with mouse dragging. See the Chart Zoom Class. The Chart Zoom.Allow property controls if users can apply zoom (default is True):

Chart1.Zoom.Allow:=True;

Users can zoom drawing a rectangle around the Chart area they want to see in detail.

Note:

Dragging should be done from top / left to bottom down. Dragging in the opposite direction resets axis scales ( no zoom ).

You can decide which mouse button and / or keys must be pressed to draw the zoomed area rectangle (degault is Left Mousebutton):

Chart1.Zoom.MouseButton:= mbMiddle;

As soon as users release the mouse button, TeeChart repaints to show the zoomed area.

Animated Zoom

You can control if TeeChart will calculate zoom positions immediately or it will be calculating zoom in short “steps” until reaching the desired zoom window.

This makes an “animated” zoom effect, which helps to identify better the zoomed area. This code activates animated zoom:

Chart1.Zoom.Animated:=True;

Set the AnimatedZoomSteps property to the desired number of intermediate zooms:

Chart1.Zoom.AnimatedSteps:=7;

Advanced:

You can control how linear the animated zoom steps are, using the global variable AnimatedZoomFactor, from 1 to n:

AnimatedZoomFactor:=2.0;

Zooming by code

You can zoom in or zoom out a Chart using any of these methods:

ZoomRect adjusts axis scales to show the TRect parameter area. The rectangle is expressed in screen pixel co-ordinates. Rectangle areas inside Chart1.ChartRect rectangle will zoom in, while area outside ChartRect will zoom out.

Chart1.ZoomRect( Rect( 100, 100, 200, 200 ) );

ZoomPercent sets Chart zoom to a percentual value. This example sets Zoom to 110 % percent to zoom in :

Chart1.ZoomPercent( 110 );

To reset zoom:

Chart1.ZoomPercent( 100 );

The above methods work independently, you can use both at the same time.

Undoing Zoom

The UndoZoom method resets axis scales to their automatic Minimum and Maximum values:

Chart1.UndoZoom;

This will display all Series points, undoing any previous zoom in or zoom out operation, either by code or using the mouse.

Note:

If you want axis scales to be at specific values after undoing zoom, you can use the Chart OnUndoZoom event, documented below.

The Zoomed boolean property returns if all four Chart Axis are automatic or not. If not Chart1.Zoomed then Chart1.ZoomPercent( 150 );

Zoom Events

The OnZoom event is triggered whenever zoom is applied to a Chart, either manually or programmatically:

procedure TForm1.Chart1Zoom(Sender: TObject);

begin

    Button1.Visible:=True ;    { make visible the 	“no-zoom” button }

end;

The OnUndoZoom event is called when undoing zoom, by code or by mouse.

Scrolling

Scrolling is very similar to zoom. Axis scales are incremented or decremented and the whole Chart component is repainted to show Series points at their new positions.

The Chart AllowPanning property controls if users can scroll Chart contents by dragging the mouse.  Its possible values are:

pmNone	No scroll is allowed.

pmHorizontal,

pmVertical 	Allow scroll only on these directions.

pmBoth 	Allow complete scroll over all directions.

Example:

Chart1.AllowPanning := pmNone ;  { no scroll is 	allowed }

Like Zoom, the following control mouse and keyboard  requirements to start scrolling:

Chart1.ScrollMouseButton := mbRight; { button used to scroll }

{Global variable}

TeeScrollKeyShift    : [ ssCtrl ];  { CONTROL key should be pressed to start scroll }

You can programmatically scroll a Chart, using the Axis Scroll method:

Procedure Scroll(Const Offset:Double;

CheckLimits:Boolean);

Example:

Chart1.BottomAxis.Scroll(  1000, True );

The above code increments BottomAxis scales by 1000. This is the same as doing:

With Chart1.BottomAxis do SetMinMax(Minimum+1000, Maximum+1000);

and setting BottomAxis Automatic property to False.

The Chart will repaint and the horizontal bottom axis will be “scrolled” to the left a quantity of “1000” in axis scales.

The “CheckLimits” boolean parameter instructs the axis to scroll ONLY if there are more Series points in the scrolling direction.

Scroll event

The Chart OnScroll event is fired every time users scroll manually the Chart.

procedure TForm1.Chart1Scroll(Sender: TObject);

begin

    Label1.Caption := ‘This Chart has scrolled ! ‘ ;

end;

Controlling scroll

The OnAllowScroll event can be used to programmatically accept or refuse a planned scroll:

procedure TForm1.Chart1AllowScroll(Sender: TChartAxis; var AMin,

  AMax: Double; var AllowScroll: Boolean);

begin

  if Sender = Chart1.BottomAxis then

     if AMax > 1000 then AllowScroll := False ;

end;

The above code refuses user scrolling if attempting to set bottom axis maximum to a value greater than 1000. The same checking can be performed over the DateTime axis:

if Sender = Chart1.BottomAxis then

     if AMax > EncodeDate( 2000, 12, 31 ) then AllowScroll := False ;

Keyboard Scrolling

To scroll with arrow keys, first, the Form KeyPreview property should be set to True.

At the KeyDown event, and depending on the pressed arrow key, the four Chart axis are scrolled using the Axis Scroll method.


Real-Time Charting and Speed

Two big rules apply to speed performance in real-time Charting:

1. Plot as few points as possible

2. Use the fastest possible hardware.

Together, these two rules really make a big speed difference when drawing Charts many times continuously.

Some other suggestions are:

- Use 2D.  Three dimensional Charts are slower to paint than 2D.

- Make Charts small.  Bigger Charts need more pixels to be filled.

- Remove Chart Legend and Titles when possible.

- Use default fonts and font sizes.

- Use FastLineSeries for fastest way to plot many points.

- Use solid pens and brushes styles.

- Avoid using circular shapes or circular bar styles.

- Don’t use background bitmaps or gradient fill effects.

- Set Chart BevelInner and BevelOuter properties to bvNone

- When possible, set Chart1.AxisVisible to False to remove axis.

- Set your video mode resolution and colour depth to the optimum values, according to your video card.

- A combination of 800x600 x 256 colours can be faster than 1024x768 x 32k colours, on average video cards.

- Use Windows 95 or Windows NT with accelerated drivers for your video card.

BufferedDisplay

This public property controls how Charts are internally drawn. When True, the default, Charts are drawn into an internal hidden bitmap.  When drawing is finished, this internal bitmap is transferred to the screen in one single operation. The result is non-flickering animation.

In some circumstances, setting BufferedDisplay to False can accelerate Chart redrawing. It depends on CPU and video card speed, and on the number of points plotted.

The bad news is that drawing directly to screen produces flickering, but can be helpful for really heavy redrawing applications.

When running tests try to use the same test project. Remember to use exactly the same data values in your tests with your real Charts.  Use always the same number of points and the same point values when comparing speed results. Run the tests many times to obtain a fair statistical result and restart completely between tests.


Functions

A function may be defined to use one of most Series types as a ‘carrier’ Series and to act upon other Series to create its source data. When the function is defined it behaves as any other Series. Functions may thus be built upon other functions. Only in its definition of data source is a function different from other Series as it contains information that relates it statistically to other data sources by formula, sum, etc.

Topics in this Section:

Adding a function with the Chart editor

Deleting a function with the Chart editor

Changing a FunctionType with the Chart editor

Adding a function by code

Deleting a function by code

Period

Adding a function with the Chart editor

Functions may be added using the Chart editor at design time. Similarly to adding a Series you may use the TeeChart Gallery to choose the function. In the Gallery all functions are initially displayed as LineSeries functions - you may change Series type after initially adding the function.

When you have added the function go to the DataSource tab of the Series page. Here you may choose which input Series (or Series) to add to the function. The first Series in the selected listbox, reading from top to bottom, is the Series on which the operation is performed in the case of function which doesn’t treat each member of the list homogeneously.

Eg. Subtract.

Fig. 1. Subtract function defined in the Chart editor
In the Chart editor screen you see Series3 being defined with inputs Series1 and Series2. The Series order in the list defines which Series is doing the subtraction.

Here:	Series3:= Series1 - Series2

Deleting a function with the Chart editor

Alternatively you may delete the Series you have added as carrier for the function (delete Series from the first page of the Chart editor) or you may redefine the Series as having a different datasource in the DataSource tab of the Series page.

Changing a FunctionType with the Chart editor

The option to change the FunctionType is in the DataSource tab of the Series page for the function Series. The drop down combobox contains a list of all function types - You may choose any from the list. Copy will directly copy the input Series (duplicating the Series).

Adding a function by code

Function is a component. When you add a new function you are adding a Series, defining a new function and setting it as FunctionType for the Series.

Series1.SetFunction(TAddTeeFunction.Create(Self));

See the online help for a description of how to add each of the different types of function. Each function uses the same Series method, SetFunction.

Deleting a function by code

To delete a function from a Series either delete the Series or use the SetFunction method to de-allocate the connection between the Series and the Function.

Series1.SetFunction(nil);

Period

You may find the Period property extremely useful when working with functions. It is used to define the frequency for which the function re-calculates.

Example

We have 6 data points (eg. bars of a Bar Series) with values:

3, 8, 6, 2, 9 and 12

We define a function Series with Period 0 (default when only one Series is input to the Function) the average drawn is:

6.667

With Period set to 2 we get 3 values of average as output from the function:

5.5, 4 and 10.5

These values will plot centrally in their period range, ie. The 1st  value between bars 1 and 2 of the input Series, 2nd value between bars 3 and 4, etc..

You may define Period by selecting the function in the Object Inspector or you may modify Period at runtime using FunctionType.

Eg. Where Series 2 is the function Series:

Series2.FunctionType.Period:=2


TeeChart Series Types

TeeChart Gallery

TeeChart Library includes the most typical Chart Series types.

Each type has its own specific properties and events to customize your Charts.

Most importantly you can derive new subcomponents from any Series type, thus creating any NEW Chart types.

TeeChart includes the following Chart Series types (To see a visual representation of these Series go to the TeeChart User Guide):

Standard types:

 Line

 HorizLine

 Area

 Point (scatter)

 Bar,Pyramid,Cilinder...

 Horizontal Bar,Pyramid,Cilinder...

 Pie

 Shapes

 Fast Line

 Arrows

Gantt

Bubble

All Series are derived from the "pseudo-abstract" TChartSeries class.

TChartSeries hides all the logic complexity leaving the developer to code the "drawing" and "aesthetic" parts of a given Series type.

See TTeeFunction for an outline description of available statistical functions.

Some advanced Series features include custom scaling and margining. Other "pseudo-abstract" components are available for component developers:

Period


Example code

TeeChart Pro v5 VCL examples may be found in the Examples folder below the default TeeChart installation folder. A compiled version of the demo (compiled using packages) may be accessed via the TeeChart prgram manager group. Please see the FAQ  at the Steema web, www.steema.com, for more coded examples.

The Guide to Information Sources document accessible via the TeeChart prgram manager group offers a detailed review of other TeeChart information sources.