TAChart Tutorial: Function Series

From Free Pascal wiki
Revision as of 18:24, 23 September 2012 by Wp (talk | contribs) (Created page with "*** UNDER CONSTRUCTION *** == Introduction == In this tutorial, we want to learn how to draw mathematical functions by means of [[TAChart_documentation#FunctionSeries|<code>...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search
      • UNDER CONSTRUCTION ***

Introduction

In this tutorial, we want to learn how to draw mathematical functions by means of TFuncSeries. This is a series type that - at first sight - looks like an ordinary line series. But in the background, it is completely different. It does not get its data from a ChartSource, but from a mathematical function. Whenever the series needs data it calls the event handler for OnCalculate where the user can pass the function values for an x value requested. This saves memory for storage of the function values. But most of all, it allows to calculate the function values, depending on zooming level and chart size, at sufficiently narrow intervals, such that the series curve is smooth even at high magnifications.

Preparation

Let us start a new project with a standard TChart component on it. Do any modifications to its properties that you want to. I'll be using here the following settings:

  • Align: alClient
  • BackColor: clWhite
  • Title: Text: 'Mathematical functions', Visible: true, Font.Style: fsBold
  • BottomAxis: Grid.Color: clSilver, Title.Caption: 'x', Title.Visible: true, Title.LabelFont.Style: fsBold
  • LeftAxis: Grid.Color: clSilver, Title.Caption: 'y', Title.Visible: true, Title.LabelFont.Style: fsBold

The resulting form is displayed in the following image on the left:

FuncSeries1.png

Adding a TFuncSeries

At first, let's draw a sine function, y = sin(x). We double-click on the chart, the series editor opens ("Edit series"). Click on "Add" and select "Function series" from the drop-down list. This chart will display a line going from the left-bottom to the right-top corner as a representative of the FuncSeries.

Since we will plot the sine function, we rename the series as "SinFuncSeries". And we could give it a red color. FuncSeries don't have a SeriesColor property, but we can use the property Pen for our purpose: Set Pen.Color to clRed.

Now we go to the page "Events" of the object inspector, and double-click on the event "OnCalculate". This is the place where we define the function. OnCalculate is called whenever the series needs the y value for a given x value:

procedure TForm1.SinFuncSeriesCalculate(const AX: Double; out AY: Double);
begin
  AY := sin(AX);
end;


FuncSeries2.png

When we compile we'll see the sine funtion. Since we did not yet set up the axes the function runs only between -1 and +1 which is the default value for an empty x axis extent.