Как привязать subaxis в teechart к данным

от admin

Как привязать subaxis в teechart к данным

Несколько вертикальных осей с дополнительной меткой — Teechart

Как привязать subaxis в teechart к данным

TeeChart Pro will automatically define all Axis labelling for you and offers plenty of flexibility to tailor any specific requirements you may have. TeeChart Pro offers true Multiple Axes. These are available at design or run time and offer countless possibilities and flexibility for Axis definition. See the section in this tutorial for more information.

Axes control — Key areas
Additional Axes
Axis events
Axes control — Key areas
Scales

Axis scales are set automatically when you add Series data to your Chart. You may change from the defaults at design time or at runtime by using Axis properties.

Non date-time data
When adding a new Series, the Scales section of the Axis Page of the Chart Editor will show Automatic selected and other options greyed out. All values shown are numeric.
Date-time data
When a Series has datetime set to true (for that axis) on the Series, General page, the Scales section of the Axis Page of the Chart Editor will show Automatic selected and other options greyed out. Values are shown with Date-time values.

Automatic selects the best axis scale range to fit your data. If you turn Automatic off the scales section will ungrey options and you can change Axis values. Important, remember to select the Axis that you wish to configure from the list of Axes on the left of the page.

Add a Line Series to a Chart add a Command Button with the following code:

Running the code in the button will draw a Line Series with 40 random values. Go to the Chart Editor at design time. Turn Automatic ‘off’ in the Bottom Axis scales section of the Axis page. You may now configure Maximum and minimum values for the Axis scale. Running the code again will show values depending on the values you configured for the Axis. Using the right button of of the mouse you may scroll to see the remaining values.

Setting axis scales by code
You can change the Maximum and Minimum at runtime using this code:

You may set Axis scale Maximum and Minimum to automatic individually. e.g:

Offset
You may set Axes to have Offsets (in pixels) for both Minimum and Maximum scales.

Increment

You may tailor the intervals for the Axis. Select the Desired Increment combobox from the Scales section of the Axis page and add the increment you require. You may change this by code at runtime:

Datetime data

If your data is datetime (You may set the data to datetime for your Series by going to the Series, General page), the Chart, Axis page, scales section will show datetime range. Select the increment from the range shown in the Desired Increment combobox.
add some sample data

Change the Increment at runtime:

See the Axis.ExactDateTime property for more information about date axis labelling

When changing axis label frequency, bear in mind that TeeChart will avoid label overlap according to the setting of the LabelsSeparation property. This means that if the label frequency is too high for the labels to fit, then TeeChart will allocate ‘best fit’. Changing the label angle and label separation are 2 options that may help you fit the labels you require. See the Labels section and LabelsAngle property.

Titles

Titles are set in the Titles section of the Axis page. You may change the Title text for the Axis and its font. The angle may be selected from values 0, 90, 180, 270 degrees. For runtime see Axis Title Class.

Labels

See the AxisLabels Class (IAxislabels interface) for a resume of Labels properties.

When changing axis label frequency, bear in mind that TeeChart will avoid label overlap according to the setting of the Labels.separation property. This means that if the label frequency is too high for the labels to fit, then TeeChart will allocate ‘best fit’. Changing the label angle and label separation are 2 options that may help you fit the labels you require. See the Labels.Angle property.

Label formats
You may apply all standard number and date formats to Axis labels. The Axis page, Labels section contains the field «Values format». If your data is datetime the field name changes to «Date time format». In the Editor drag the help «?» icon onto the field to get a full listing of options. At runtime use:

MultiLine labels
Axis labels can be displayed as multi-line text instead of a single line of text. Lines are separated using the carriage-return ascii character ( #13 ).

Example Example for DateTime labels:

The following will show the Bottom Axis labels in two lines of text, one showing the month and day, and the second line showing the year:
Feb-28 Mar-1 .. 1999 1999 ..

If you set the Labels.MultiLine property to True, the axis will automatically split labels in lines where it finds a space.

Dividing the Label into two:

‘mm/dd’ for the first line
‘hh:mm’ for the second line

At run-time you can always split the label into lines programatically, using the OnGetAxisLabel event:

The global «TeeSplitInLines» procedure converts all spaces in «LabelText» to line separators (returns).

The axis Labels.Angle property ( label rotation in degree angles 0, 90, 180 or 270 ), can also be used with multi-line axis labels.

Customising Axis labels
Further Label control may be obtained by using Axis events. The events permit you to activate/deactivate/change any individual Axis label. The following example modifies each Label, putting a textual phrase in front of the point index value.

See the section entitled Axis events for more information about customising labels with Axis events.

Axes labels may be modified at specific positions with custom text and formatting without the need to use TeeChart events, making them much easier to modify serverside in ASP scenarios.

Logarithmic Labels
Normal Logarithmic labelling may be set in the following way:

Labels will be set according to the Logarithmic base (default 10) thus, in this case giving labels at 1,10,100,1000,10000.

Ticks and Minor

There are 3 tick types and 2 types of Grid. You may change the length, width and colour of each tick and Grid type. Changes can be made to Ticks, their associated Grid and Inner Ticks via the �Ticks� tab; changes to Minor Ticks and their associated Grid can be made via the �Minor� tab.

Axis position

Axes have a property to modify where each axis is to be located. In this example, the axis is moved 50% of the total Chart width, so it is shown at the chart center:

Additional Axes
Copying axes

TeeChart offers 5 axes to be associated with data Series, Left, Top, Bottom, Right and Depth. When you add a new series to a Chart you may define to which of the axes the Series should be related (Go to the Series tab, General page). You may repeat anyone (or all) of the front 4 axes at any place on the Chart by using the Axis Customdraw method. Note that this method makes a copy of your Axis, it does not add a new Custom Axis. See the next section, Multiple Custom Axes, for more information.

Custom axes

In this example, TeeChart will plot the New axes, one horizontal and one vertical in the centre of your Chart. When you scroll the Chart (dragging with right mouse button), the new vertical axis will always remain central to the Chart, the new horizontal axis will move up and down with vertical scrolling. The new axes are exact copies of the default axes.

Multiple Custom Axes

Together with the PositionPercent and stretching properties, it�s possible to have unlimited axes floating anywhere on the chart. Scroll, zoom, and axis hit-detection also apply to custom-created axes. Creating extra axes is now possible both at designtime via the Chart Editor and at runtime via a few lines of code:

Via the Chart Editor

TeeChart offers you the ability to create custom axes at designtime enabling them to be saved in TeeChart’s tee file format. To achieve this, open the Chart Editor and click on the Axis tab and then select the «+» button to add a Custom Axis. Then select the Position tab making sure you have your new Custom Axis highlighted. The Horizontal checkbox on this page allows you to define your new Custom Axis as an horizontal axis or to leave it as the default vertical axis. The rest of this page and the other tabs in the Axis page can be used to change the Scales, Increment, Titles, Labels, Ticks, Minor Ticks and Position of the Custom Axis as explained above. To associate this new Custom Axis with the Data Series you desire select the Series tab and go to the General page where the dropdown Comboboxes ‘Horizontal Axis’ and ‘Vertical Axis’ will enable you to select your new Custom Axis depending on whether you previously defined it as vertical or horizontal.

You are able to then position the new Axis in overall relation to the Chart by using the StartPosition and EndPosition properties.

These figures are expressed as percentages of the Chart Rectangle with 0 (zero) (in the case of a vertical Axis) being Top. These properties can be applied to the Standard Axes to create completely partitioned ‘SubCharts’ within the Chart.

The above 2 coded examples when combined with the following data:

. will show the following Chart:

Multiple axes

Options are limitless! We advise caution when using Custom Axes as it is easy to start filling the screen with new axes and to lose track of which one you wish to manage !

Axis events

Axis events offer runtime flexibility to modify Axis Labels and present user interactivity on Axis Clicks.

OnClickAxis

See the OnClickAxis event.

OnGetAxisLabel

Can be used to modify Axis Labels. See the OnGetAxisLabel event.

OnGetNextAxisLabel

Can be used to decide which Axis Labels should be displayed. See the OnGetNextAxisLabel event. You should use the MoreLabels Boolean property to include/exclude Axis Labels.

Как привязать subaxis в teechart к данным

Тип файла: jpg Graphic.JPG (21.1 Кб, 40 просмотров)

Как привязать subaxis в teechart к данным

Perl. Just code it!

Perl. Just code it!

Эскизы прикрепленных изображений
Прикрепленное изображение

positions.
The key is the Chart.OnGetNextAxisLabel event.
This event is called continuosly for each Axis Label until user decides
to stop.
At each call, you can specify the exact Axis value where a Label must be
drawn.

In this example, this event is used to set the BottomAxis labels to the
first (1) day in month: 1/1/96, 2/1/96, 3/1/96. 12/1/96

This don’t needs necessarily to be datetime values.
You can also set the Axis Labels in non-datetime axis.

WARNING:
Remember to set the Stop boolean variable to TRUE when no more labels are
needed.
Remember also that using this event will NOT calculate Label used space or
any Font size adjustment.
TeeChart Axis will draw all labels you specify.
>
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, Chart, Series, ExtCtrls, StdCtrls, Teengine, Buttons,
TeeProcs;

type
TAxisLabelsForm = class(TForm)
Chart1: TChart;
LineSeries1: TLineSeries;
Panel1: TPanel;
RadioGroup1: TRadioGroup;
PointSeries1: TPointSeries;
BitBtn3: TBitBtn;
Memo1: TMemo;
procedure FormCreate(Sender: TObject);
procedure RadioGroup1Click(Sender: TObject);
procedure Chart1GetNextAxisLabel(Sender: TChartAxis;
LabelIndex: Longint; var LabelValue: Double; var Stop: Boolean);
private

procedure TAxisLabelsForm.FormCreate(Sender: TObject);
var t:Longint;
begin
DefaultLabels:=False;

LineSeries1.Clear;
PointSeries1.Clear;
for t:=1 to 100 do
Begin
LineSeries1.AddXY( Date+t, 200+Random(700),»,clTeeColor);
PointSeries1.AddXY( Date+t, 200+Random(700),»,clTeeColor);
end;
end;

procedure TAxisLabelsForm.Chart1GetNextAxisLabel(Sender: TChartAxis;
LabelIndex: Longint; var LabelValue: Double; var Stop: Boolean);

var year,month,day:Word;
begin
if not DefaultLabels then
Begin
if Sender=Chart1.BottomAxis then
Begin

Setting this axis increment:

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

Eliminates the need for the following code.
>

end
else
if Sender=Chart1.LeftAxis then
Begin
labels only for positive values, starting at zero and
with 250 label increment.
>
if LabelValue>=250 then LabelValue:=LabelValue+250
else LabelValue:=250;
End;

Как привязать subaxis в teechart к данным

TeeChart Pro will automatically define all Axis labelling for you and offers plenty of flexibility to tailor any specific requirements you may have. TeeChart Pro offers true Multiple Axes. These are available at design or run time and offer countless possibilities and flexibility for Axis definition. See the section in this tutorial for more information.

Axes control — Key areas

Additional Axes

Axis events

Axes control — Key areas

Scales

Axis scales are set automatically when you add Series data to your Chart. You may change from the defaults at design time or at runtime by using Axis properties.

Automatic selects the best axis scale range to fit your data. If you turn Automatic off the Scales section will activate options and you can change Axis values. Important, remember to select the Axis that you wish to configure from the Axis menu on the left of the page.

Add a Line Series to a Chart add a Command Button with the following code:

Running the code in the button will draw a Line Series with 40 random values.

Go to the Chart Editor at design time. Turn Automatic ‘off’ in the Bottom Axis scales section of the Axis page. You may now configure Maximum and minimum values for the Axis scale. Running the code again will show values depending on the values you configured for the Axis. Using the right mouse button you may scroll to see the remaining values.

Setting axis scales by code
You can change the Maximum and Minimum at runtime using this code:

You may set Axis scale Maximum and Minimum to automatic individually. eg:

Increment

You may tailor the intervals for the Axis. Select the Desired Increment combobox from the Scales section of the Axis page and add the increment you require. You may change this by code at runtime:

Datetime data
If your data is datetime (You may set the data to datetime for your Series by going to the Series, General page), the Chart, Axis page and scales section will show a datetime range. Select the from the range shown in the Desired Increment combobox.
add some sample data

Change the Increment at runtime:

See the Axis.ExactDateTime property for more information about date axis labelling.

When changing axis label frequency, bear in mind that TeeChart will avoid label overlap according to the setting of the LabelsSeparation property. This means that if the label frequency is too high for the labels to fit, then TeeChart will allocate ‘best fit’. Changing the label angle and label separation are 2 options that may help you fit the labels you require. See the Labels section and LabelsAngle property.

Titles

Titles are set in the Titles section of the Axis page. You may change the Title text for the Axis and its font. The angle may be selected from values 0, 90, 180, 270 degrees. For runtime see the TChartAxisTitle Component.

Labels

When changing axis label frequency, bear in mind that TeeChart will avoid label overlap according to the setting of the LabelsSeparation property. This means that if the label frequency is too high for the labels to fit, then TeeChart will allocate a ‘best fit’. Changing the label angle and label separation are 2 options that may help you fit the labels you require. See the Labels section and the LabelsAngle property.

Label formats
You may apply all standard number and date formats to Axis labels. The Axis page, Labels section contains the field «Values format». If your data is datetime the field name changes to «Date time format». In the Editor drag the help «?» icon onto the field to get a full listing of options. at runtime use:

MultiLine labels
Axis labels can be displayed as multi-line text instead of a single line of text. Lines are separated using the TeeLineSeparator global constant, which by default is the carriage-return ascii character ( #13 ).

Example Example for DateTime labels:

The following will show the Bottom Axis labels in two lines of text, one showing the month and day, and the second line showing the year:
Feb-28 Mar-1 .. 1998 1998 ..

If you set the LabelsMultiLine property to True, the axis will automatically split labels into separate lines where spaces are found.

Dividing the Label into two:

‘mm/dd’ for the first line
‘hh:mm’ for the second line

At run-time you can always split the label into lines programmatically, using the OnGetAxisLabel event:

The axis LabelsAngle property ( label rotation in degree angles 0, 90, 180 or 270 ), can also be used with multi-line axis labels.

Customising Axis labels
Further Label control may be obtained by using Axis events. The events permit you to activate/deactivate/change any individual Axis label. The following example modifies each Label, putting a textual phrase in front of the point index value.

See the section entitled Axis events for more information about customising labels with Axis events.

Ticks

There are 3 tick types. You can change the length, width and colour of each tick type. If the tick width is set to 1 (default) then you may change the style to one of several line types (dot, dash, etc.). Style will be ignored if width is greater than 1.

Axis position

Axes have a property which modifies where each axis is to be located. In this example, the axis is moved to 50% of the total Chart width, so it is shown at the chart center:

Additional Axes

Copying axes

TeeChart offers 5 axes to be associated with data Series: Left, Top, Bottom, Right and Depth. When you add a new series to a Chart you may define to which of the axes the Series should be related (Go to the Series tab, General page). You may repeat any one (or all) of the 4 front axes at any place on the Chart by using the Axis Customdraw method. Note that this method makes a copy of your Axis, it does not add a new Custom Axis. See the next section, Multiple Custom Axes, for more information.

You will find this example, called «CustAxisProject1», with the TeeChart sample code:

Custom axes

In this example, TeeChart will plot the New axes, one horizontal and one vertical in the centre of your Chart. When you scroll the Chart (dragging with right mouse button), the new vertical axis will always remain central to the Chart, the new horizontal axis will move up and down with vertical scrolling. The new axes are exact copies of the default axes.

Multiple Custom Axes

Together with the PositionPercent and stretching properties, it�s possible to have unlimited axes floating anywhere on the chart. Scroll , zoom , and axis hit-detection also apply to custom-created axes. Creating extra axes is now possible both at designtime via the Chart Editor and at runtime via a few lines of code:

Via the Chart Editor
TeeChart offers you the ability to create custom axes at designtime enabling them to be saved in TeeChart’s tee file format. To achieve this, open the Chart Editor and click on the Axis tab and then select the «+» button to add a Custom Axis. Then select the Position tab making sure you have your new Custom Axis highlighted. The Horizontal checkbox on this page allows you to define your new Custom Axis as an horizontal axis or to leave it as the default vertical axis. The rest of this page and the other tabs in the Axis page can be used to change the Scales, Increment, Titles, Labels, Ticks, Minor Ticks and Position of the Custom Axis as explained above. To associate this new Custom Axis with the Data Series you desire select the Series tab and go to the General page where the dropdown Comboboxes ‘Horizontal Axis’ and ‘Vertical Axis’ will enable you to select your new Custom Axis depending on whether you previously defined it as vertical or horizontal.

You are able to then position the new Axis in overall relation to the Chart by using the StartPosition and EndPosition properties.

These figures are expressed as percentages of the Chart Rectangle with 0 (zero) (in the case of a vertical Axis) being Top. These properties can be applied to the Standard Axes to create completely partitioned ‘SubCharts’ within the Chart.

The above 2 coded examples when combined with the following data:

. will show the following Chart:

Multiple axes

Another technique for adding Custom Axes would be the following which uses the Axis List as the focal point by using the List Add then by accessing the Axis by Index:

Options are limitless! We advise caution when using Custom Axes as it is easy to start filling the screen with new axes and to lose track of which one you wish to manage !

Axis events

Axis events offer runtime flexibility to modify Axis Labels and offer interactivity to the user on Axis Clicks.

OnClickAxis
OnGetAxisLabel

Can be used to modify Axis Labels. See the OnGetAxisLabel event.

OnGetNextAxisLabel

Can be used to decide which Axis Labels should be displayed. See the OnGetNextAxisLabel event. You should use the Stop Boolean property to include/exclude Axis Labels.

The above example will start labelling at ‘5’ on the Bottom Axis labelling every 5 points. Other Axes’ Labels are unaffected.

Как привязать subaxis в teechart к данным

Как привязать subaxis в teechart к данным

TeeChart Pro will automatically define all Axis labelling for you and offers plenty of flexibility to tailor any specific requirements you may have. TeeChart Pro offers true Multiple Axes. These are available at design or run time and offer countless possibilities and flexibility for Axis definition. See the section in this tutorial for more information.

Axes control — Key areas
Additional Axes
Axis events
Axes control — Key areas
Scales

Axis scales are set automatically when you add Series data to your Chart. You may change from the defaults at design time or at runtime by using Axis properties.

Automatic selects the best axis scale range to fit your data. If you turn Automatic off the Scales section will activate options and you can change Axis values. Important, remember to select the Axis that you wish to configure from the Axis menu on the left of the page.

Add a Line Series to a Chart add a Command Button with the following code:

Running the code in the button will draw a Line Series with 40 random values.

Go to the Chart Editor at design time. Turn Automatic ‘off’ in the Bottom Axis scales section of the Axis page. You may now configure Maximum and minimum values for the Axis scale. Running the code again will show values depending on the values you configured for the Axis. Using the right mouse button you may scroll to see the remaining values.

Setting axis scales by code
You can change the Maximum and Minimum at runtime using this code:

You may set Axis scale Maximum and Minimum to automatic individually. eg:

Increment

You may tailor the intervals for the Axis. Select the Desired Increment combobox from the Scales section of the Axis page and add the increment you require. You may change this by code at runtime:

Datetime data
If your data is datetime (You may set the data to datetime for your Series by going to the Series, General page), the Chart, Axis page and scales section will show a datetime range. Select the from the range shown in the Desired Increment combobox.
add some sample data

Change the Increment at runtime:

See the Axis.ExactDateTime property for more information about date axis labelling.

When changing axis label frequency, bear in mind that TeeChart will avoid label overlap according to the setting of the LabelsSeparation property. This means that if the label frequency is too high for the labels to fit, then TeeChart will allocate ‘best fit’. Changing the label angle and label separation are 2 options that may help you fit the labels you require. See the Labels section and LabelsAngle property.

Titles

Titles are set in the Titles section of the Axis page. You may change the Title text for the Axis and its font. The angle may be selected from values 0, 90, 180, 270 degrees. For runtime see the TChartAxisTitle Component.

Labels

When changing axis label frequency, bear in mind that TeeChart will avoid label overlap according to the setting of the LabelsSeparation property. This means that if the label frequency is too high for the labels to fit, then TeeChart will allocate a ‘best fit’. Changing the label angle and label separation are 2 options that may help you fit the labels you require. See the Labels section and the LabelsAngle property.

Label formats
You may apply all standard number and date formats to Axis labels. The Axis page, Labels section contains the field «Values format». If your data is datetime the field name changes to «Date time format». In the Editor drag the help «?» icon onto the field to get a full listing of options. at runtime use:

MultiLine labels
Axis labels can be displayed as multi-line text instead of a single line of text. Lines are separated using the TeeLineSeparator global constant, which by default is the carriage-return ascii character ( #13 ).

Example Example for DateTime labels:

The following will show the Bottom Axis labels in two lines of text, one showing the month and day, and the second line showing the year:
Feb-28 Mar-1 .. 1998 1998 ..

If you set the LabelsMultiLine property to True, the axis will automatically split labels into separate lines where spaces are found.

Dividing the Label into two:

‘mm/dd’ for the first line
‘hh:mm’ for the second line

At run-time you can always split the label into lines programmatically, using the OnGetAxisLabel event:

The axis LabelsAngle property ( label rotation in degree angles 0, 90, 180 or 270 ), can also be used with multi-line axis labels.

Customising Axis labels
Further Label control may be obtained by using Axis events. The events permit you to activate/deactivate/change any individual Axis label. The following example modifies each Label, putting a textual phrase in front of the point index value.

See the section entitled Axis events for more information about customising labels with Axis events.

Ticks

There are 3 tick types. You can change the length, width and colour of each tick type. If the tick width is set to 1 (default) then you may change the style to one of several line types (dot, dash, etc.). Style will be ignored if width is greater than 1.

Axis position

Axes have a property which modifies where each axis is to be located. In this example, the axis is moved to 50% of the total Chart width, so it is shown at the chart center:

Additional Axes
Copying axes

TeeChart offers 5 axes to be associated with data Series: Left, Top, Bottom, Right and Depth. When you add a new series to a Chart you may define to which of the axes the Series should be related (Go to the Series tab, General page). You may repeat any one (or all) of the 4 front axes at any place on the Chart by using the Axis Customdraw method. Note that this method makes a copy of your Axis, it does not add a new Custom Axis. See the next section, Multiple Custom Axes, for more information.

You will find this example, called «CustAxisProject1», with the TeeChart sample code:

Custom axes

In this example, TeeChart will plot the New axes, one horizontal and one vertical in the centre of your Chart. When you scroll the Chart (dragging with right mouse button), the new vertical axis will always remain central to the Chart, the new horizontal axis will move up and down with vertical scrolling. The new axes are exact copies of the default axes.

Multiple Custom Axes

Together with the PositionPercent and stretching properties, it�s possible to have unlimited axes floating anywhere on the chart. Scroll , zoom , and axis hit-detection also apply to custom-created axes. Creating extra axes is now possible both at designtime via the Chart Editor and at runtime via a few lines of code:

Via the Chart Editor
TeeChart offers you the ability to create custom axes at designtime enabling them to be saved in TeeChart’s tee file format. To achieve this, open the Chart Editor and click on the Axis tab and then select the «+» button to add a Custom Axis. Then select the Position tab making sure you have your new Custom Axis highlighted. The Horizontal checkbox on this page allows you to define your new Custom Axis as an horizontal axis or to leave it as the default vertical axis. The rest of this page and the other tabs in the Axis page can be used to change the Scales, Increment, Titles, Labels, Ticks, Minor Ticks and Position of the Custom Axis as explained above. To associate this new Custom Axis with the Data Series you desire select the Series tab and go to the General page where the dropdown Comboboxes ‘Horizontal Axis’ and ‘Vertical Axis’ will enable you to select your new Custom Axis depending on whether you previously defined it as vertical or horizontal.

You are able to then position the new Axis in overall relation to the Chart by using the StartPosition and EndPosition properties.

These figures are expressed as percentages of the Chart Rectangle with 0 (zero) (in the case of a vertical Axis) being Top. These properties can be applied to the Standard Axes to create completely partitioned ‘SubCharts’ within the Chart.

The above 2 coded examples when combined with the following data:

. will show the following Chart:

Multiple axes

Another technique for adding Custom Axes would be the following which uses the Axis List as the focal point by using the List Add then by accessing the Axis by Index:

Options are limitless! We advise caution when using Custom Axes as it is easy to start filling the screen with new axes and to lose track of which one you wish to manage !

Axis events

Axis events offer runtime flexibility to modify Axis Labels and offer interactivity to the user on Axis Clicks.

OnClickAxis
OnGetAxisLabel

Can be used to modify Axis Labels. See the OnGetAxisLabel event.

OnGetNextAxisLabel

Can be used to decide which Axis Labels should be displayed. See the OnGetNextAxisLabel event. You should use the Stop Boolean property to include/exclude Axis Labels.

The above example will start labelling at ‘5’ on the Bottom Axis labelling every 5 points. Other Axes’ Labels are unaffected.

Как привязать subaxis в teechart к данным

TeeChart Pro will automatically define all Axis labelling for you and offers plenty of flexibility to tailor any specific requirements you may have. TeeChart Pro offers true Multiple Axes. These are available at design or run time and offer countless possibilities and flexibility for Axis definition. See the section in this tutorial for more information.

Axes control — Key areas
Additional Axes
Axes control — Key areas
Scales

Axis scales are set automatically when you add Series data to your Chart. You may change from the defaults at design time by code or at runtime by using Axis methods.

When adding a new Series, the Scales section of the Axis Page of the Chart Editor will show Visible and Automatic selected and Inverted unchecked. In the bottom part of the editor there are two tabs, Maximum and Minimum. Here you can set the Offset values to displace the chart along the selected axis when Auto is unchecked.

Automatic selects the best axis scale range to fit your data. If you turn Automatic off, the Scales section will activate options and you can change Axis values. Important, remember to select the Axis that you wish to configure from the Axis list at the left of the page.

Add a Line Series to a Chart add a Command Button with the following code:

Running the code in the button will draw a Line Series with 40 random values. You may now configure Maximum and Minimum values for the Axis scale.

Running the code again will show values depending on the values you configured for the Axis. Using the right button of of the mouse you may scroll to see the remaining values.

You may set Axis scale Maximum and Minimum to automatic individually. eg:

Increment

You may tailor the intervals for the Axis. Select the Desired Increment combobox from the Scales section of the Axis page and add the increment you require. You may change this by code at runtime:

Datetime data

If your data is datetime (You may set the data to DateTime for your Series by going to the Series, General page, as seen in this image.), the Chart, Axis page and scales section will show a datetime range. Select from the range shown in the Desired Increment combobox.

add some sample data

Change the Increment at runtime:

See the Axis.ExactDateTime method for more information about date axis labelling.

When changing axis label frequency, bear in mind that TeeChart will avoid label overlap according to the setting of the LabelsSeparation method. This means that if the label frequency is too high for the labels to fit, then TeeChart will allocate ‘best fit’. Changing the label angle and label separation are 2 options that may help you fit the labels you require. See the Labels section and LabelsAngle method.

Titles

Titles are set in the Titles section of the Axis page. You may change the Title text for the Axis and its font. The angle may be selected from values 0, 90, 180, 270 degrees. For runtime see the TChartAxisTitle Component.

Labels

When changing axis label frequency, bear in mind that TeeChart will avoid label overlap according to the setting of the LabelsSeparation method. This means that if the label frequency is too high for the labels to fit, then TeeChart will allocate a ‘best fit’. Changing the label angle and label separation are 2 options that may help you fit the labels you require. See the Labels section and the LabelsAngle method.

Label formats
You may apply all standard number and date formats to Axis labels. The Axis page, Labels section contains the field «Values format». If your data is datetime the field name changes to «Date time format». In the Editor drag the help «?» icon onto the field to get a full listing of options. at runtime use:

Читать:
Где у робота пылесоса датчик

MultiLine labels
Axis labels can be displayed as multi-line text instead of a single line of text. Lines are separated using the TeeLineSeparator global constant, which by default is the carriage-return ascii character ( #13 ).

Example Example for DateTime labels:

Ticks

There are 3 tick types. You can change the length, width and colour of each tick type. If the tick width is set to 1 (default) then you may change the style to one of several line types (dot, dash, etc.). Style will be ignored if width is greater than 1.

Axis position

Axes have a method which modifies where each axis is to be located. In this example, the axis is moved to 50% of the total Chart width, so it is shown at the chart center:

Additional Axes
Copying axes

TeeChart offers 5 axes to be associated with data Series: Left, Top, Bottom, Right and Depth. When you add a new series to a Chart you may define to which of the axes the Series should be related (Go to the Series tab, General page). You may repeat any one (or all) of the 4 front axes at any place on the Chart by using the Axis Customdraw method. Note that this method makes a copy of your Axis, it does not add a new Custom Axis.

Custom axes

In this example, TeeChart will plot the New axes, one horizontal and one vertical in the centre of your Chart. When you scroll the Chart (dragging with right mouse button), the new vertical axis will always remain central to the Chart, the new horizontal axis will move up and down with vertical scrolling. The new axes are exact copies of the default axes.

Multiple Custom Axes (Pro version only)

Together with the PositionPercent and stretching properties, it�s possible to have unlimited axes floating anywhere on the chart. Scroll , zoom , and axis hit-detection also apply to custom-created axes. Creating extra axes is now possible both at designtime via the Chart Editor and at runtime via a few lines of code:

Via the Chart Editor
TeeChart offers you the ability to create custom axes at designtime enabling them to be saved in TeeChart’s tee file format. To achieve this, open the Chart Editor and click on the Axis tab and then select the «+» button to add a Custom Axis. Then select the Position tab making sure you have your new Custom Axis highlighted. The Horizontal checkbox on this page allows you to define your new Custom Axis as an horizontal axis or to leave it as the default vertical axis. The rest of this page and the other tabs in the Axis page can be used to change the Scales, Increment, Titles, Labels, Ticks, Minor Ticks and Position of the Custom Axis as explained above. To associate this new Custom Axis with the Data Series you desire select the Series tab and go to the General page where the dropdown Comboboxes ‘Horizontal Axis’ and ‘Vertical Axis’ will enable you to select your new Custom Axis depending on whether you previously defined it as vertical or horizontal.

Example You are able to then position the new Axis in overall relation to the Chart by
using the StartPosition and EndPosition methods. These figures are expressed as percentages of the Chart Rectangle with 0 (zero) (in the case of a
vertical Axis) being Top. These properties can be applied to the Standard Axes to create
completely partitioned ‘SubCharts’ within the Chart.

The above coded example will show the following Chart:

Multiple axes

Options are limitless! We advise caution when using Custom Axes as it is easy to start filling the screen with new axes and to lose track of which one you wish to manage !

Как привязать subaxis в teechart к данным

TeeChart Pro автоматически определит все теги Axis для пользователей и обеспечит достаточную гибкость для настройки любых конкретных требований, которые могут предъявляться пользователями. TeeChart Pro обеспечивает истинную многоосность. Они могут быть использованы во время проектирования или выполнения и предоставляют бесчисленные возможности и гибкость для определения оси. В этом учебном пособии будет представлено применение управления осями:

Зоны клавиш управления Axis

Scales——Увеличить
При добавлении данных ряда в диаграмму масштаб оси устанавливается автоматически, и пользователи могут использовать свойство Axis для изменения значения по умолчанию во время разработки или выполнения.

teechart

Данные не дата-время-данные не дата-время

При добавлении новой серии в разделе «Масштабы» на странице «Ось» редактора TeeChart будут отображаться «Выбранные автоматически» и другие серые параметры. Все отображаемые значения являются числовыми.

teechart

Когда серия устанавливает дату и время в true на странице «Серии -> Общие» (для этой оси), в разделе «Шкалы» на странице осей редактора TeeChart будет отображаться «Авто (выбирается автоматически) ) И другие серые варианты. Значение отображается как значение даты и времени.
Автоматический выбор оптимального диапазона шкалы оси в соответствии с данными пользователя, используемыми при проектированииTeeChartРедактор добавляет ряд линий на диаграмму, а затем добавляет командную кнопку, используя следующий код:

Выполнение кода в кнопке нарисует серию строк с 40 случайными значениями. Перейти на время проектированияTeeChartРедактор, в разделе «Шкалы нижней оси» страницы «Ось» установите «Авто» на «Выкл». Теперь вы можете настроить максимальное и минимальное значения шкалы оси. Повторный запуск кода отобразит значение в зависимости от значения, настроенного пользователем для Axis. Используйте правую кнопку мыши для прокрутки оставшихся значений.  

Setting axis scales by code

Измените максимальный и минимальный коды:

Установите максимальную и минимальную шкалу оси на автоматические коды:

Приращение-пошаговый
Пользователи могут настроить интервал оси, выбрать поле со списком «Требуемое увеличение» в разделе «Масштабы» на странице «Ось» и добавить требуемый прирост, код:

Данные даты и времени: данные даты

Если данные имеют дату-время (вы можете установить дату на серию-дату, перейдя в «Серии», «Общие»), часть масштаба страницы «Диаграмма-> Ось» отобразит диапазон даты и времени. Выберите приращение из диапазона, отображаемого в поле со списком «Требуемый прирост», и добавьте несколько примеров данных:

Измените приращение во время выполнения:

Для получения дополнительной информации о метках оси даты см. Свойство AxisLabels.ExactDateTime.

нота:

При изменении частоты метки оси,TeeChartМетки будут избегаться в соответствии с настройкой свойства AxisLabels.Separation. Это означает, что если частота тега слишком высока, чтобы соответствовать тегу, то TeeChart назначит «наилучшее соответствие». Изменение угла надписи и разделение надписей — это два варианта, которые могут помочь пользователям установить необходимые надписи.
Титулы-Title
Заголовок задается в титульной части страницы Axis. Пользователь может изменить текст заголовка Axis и его свойства шрифта и тени, а также указать угол и размер текста заголовка.
нота:

При изменении частоты метки оси,TeeChartМетки будут избегаться в соответствии с настройкой свойства AxisLabels.Separation. Это означает, что если частота тега слишком высока, чтобы соответствовать тегу, то TeeChart назначит «наилучшее соответствие». Изменение угла надписи и разделение надписей — это два варианта, которые могут помочь пользователям установить необходимые надписи.
Формат этикетки:

Пользователи могут применять все стандартные форматы чисел и дат к тегам Axis. Раздел «Метки» страницы «Ось» содержит поле «Формат значений». Если данные являются датой и временем, имя поля будет изменено на «Формат даты и времени», а код будет использоваться во время выполнения:

Или для данных даты и времени

MultiLine теги

Метки осей могут отображаться в виде многострочного текста вместо однострочного текста, используя символ LineSeparator () для разделения строк.

Примеры тегов DateTime:
Далее будут отображаться метки нижней оси в двух строках текста, один месяц и дата, а вторая строка года:
Feb-28 Mar-1 ..
2003 2003 ..

Если для свойства AxisLabels.MultiLine установлено значение True, метка в строке будет автоматически разделена пробелами, что будет эффективно разделять метку на две части:

Первая строка: «мм / дд»

Вторая строка: «чч: мм»
Во время выполнения вы всегда можете использовать событие OnGetAxisLabel для программного разделения метки на несколько строк:

В приведенном выше примере глобальный процесс «TeeSplitInLines» преобразует все пробелы в «LabelText» в разделители строк (возврат), а свойство AxisLabels.Angle оси также можно использовать для меток многострочных осей.

Настройка меток оси — настраиваемые метки оси
Вы можете получить дополнительный контроль над метками, используя события Axis. Событие позволяет пользователю активировать / деактивировать / изменить любую метку Оси. В следующем примере изменяется каждая метка, помещая текстовую фразу перед значением индекса точки:

Логарифмические метки-индексные метки

Нормальная логарифмическая метка может быть установлена ​​следующими способами:

Метка будет установлена ​​в соответствии с основанием логарифма (по умолчанию 10), поэтому в этом случае метка будет обозначена как 1,10,100,1000,10000.

Тики и минор тик и минор

teechart

Существует 3 типа флажков и 2 типа сеток. Пользователь может изменять длину, ширину и цвет каждой шкалы и типа сетки. Тики и связанные с ними сетки и внутренние тики можно изменить с помощью вкладки «Тики», второстепенные тики и связанные с ними сетки можно изменить с помощью вкладки «Незначительные». Новая функция TeeChart Pro версии 5 — это возможность изменять масштаб и стиль сетки с шириной больше 1 (по умолчанию).

Положение оси —— Положение оси
Ось имеет модификации, в которых расположена каждая осьдолжностьИмущество. В этом примере ось переместилась на 50% ширины диаграммы, поэтому она отображается в центре диаграммы:

Дополнительные оси-дополнительные оси

Копирование осей-копирование осей

TeeChartОбеспечивает 5 рядов осей, связанных с данными: слева (слева), сверху (сверху), снизу (снизу), справа (справа) и глубиной (глубоко). При добавлении новой серии в диаграмму пользователь может определить, с какими осями должен быть связан ряд (перейдите на страницу «Общие» вкладки «Серия»), и вы можете использовать метод Axis Customdraw, чтобы повторить первые 4 в любом месте диаграммы Любая (или все) из осей. Этот метод копирует Axis, но не добавляет новую пользовательскую ось.
Пример:

Пример кода выше создаст следующее изображение:

teechart

Пользовательская ось

В этом примере TeeChart нарисует новую ось, одну горизонтальную и одну вертикальную в центре диаграммы. Когда пользователь прокручивает диаграмму (перетаскивая ее правой кнопкой мыши), новая вертикальная ось всегда будет оставаться в центре диаграммы, новая горизонтальная ось будет прокручиваться вертикально и перемещаться вверх и вниз, а новая ось является точной копией оси по умолчанию.

Несколько пользовательских осей
Вместе с атрибутами PositionPercent и Stretch вы можете перемещать бесконечную ось в любую позицию на диаграмме. Прокрутка, масштабирование и обнаружение попадания осей также применяются к осям, созданным пользователем. Теперь вы можете создавать дополнительные оси во время разработки с помощью редактора TeeChart или создавать дополнительные оси во время выполнения с помощью нескольких строк кода:

С помощью редактора диаграмм

teechart

TeeChartПредоставьте пользователям возможность создавать собственные оси во время разработки, чтобы они моглиTeeChartСохраните формат файла футболки. Откройте редактор диаграмм и перейдите на вкладку «Ось», затем нажмите кнопку «+», чтобы добавить пользовательскую ось. Затем выберите вкладку «Положение», чтобы новая ось была выделена. Флажок «Горизонтальный» на этой странице позволяет пользователю определить новую пользовательскую ось в качестве горизонтальной оси или оставить ее в качестве вертикальной оси по умолчанию. Как упоминалось выше, оставшуюся часть этой страницы и другие вкладки на странице Оси можно использовать для изменения масштаба, приращения, заголовка, метки, масштаба, вспомогательного масштаба и положения пользовательской оси. Чтобы связать эту новую пользовательскую ось с нужным рядом данных, выберите вкладку «Серии» и перейдите на страницу «Общие», где выпадающий список «Горизонтальная ось (горизонтальная ось)» «И« Вертикальная ось »позволит пользователю выбрать новую пользовательскую ось в зависимости от того, определил ли пользователь ранее ее как вертикальную или горизонтальную ось.
Код:

Приведенный выше пример кодирования покажет следующую диаграмму:

teechart

Несколько осей-несколько осей

Варианты не ограничены! Рекомендуется соблюдать осторожность при использовании пользовательских осей, потому что легко начать заполнять экран новыми осями и не может отследить ось, которой хочет управлять пользователь!

События Оси

События Axis обеспечивают гибкость времени выполнения.Можно изменять метки Axis и отображать интерактивность пользователя на кликах Axis.

Как привязать subaxis в teechart к данным

TeeChart Pro will automatically define all Axis labelling for you and offers plenty of flexibility to tailor any specific requirements you may have. TeeChart Pro offers true Multiple Axes. These are available at design or run time and offer countless possibilities and flexibility for Axis definition. See the section in this tutorial for more information.

Axes control — Key areas
Additional Axes
Axis events
Axes control — Key areas
Scales

Axis scales are set automatically when you add Series data to your Chart. You may change from the defaults at design time or at runtime by using Axis properties.

Automatic selects the best axis scale range to fit your data. If you turn Automatic off the Scales section will activate options and you can change Axis values. Important, remember to select the Axis that you wish to configure from the Axis menu on the left of the page.

Add a Line Series to a Chart add a Command Button with the following code:

Running the code in the button will draw a Line Series with 40 random values.

Go to the Chart Editor at design time. Turn Automatic ‘off’ in the Bottom Axis scales section of the Axis page. You may now configure Maximum and minimum values for the Axis scale. Running the code again will show values depending on the values you configured for the Axis. Using the right mouse button you may scroll to see the remaining values.

Setting axis scales by code
You can change the Maximum and Minimum at runtime using this code:

You may set Axis scale Maximum and Minimum to automatic individually. eg:

Increment

You may tailor the intervals for the Axis. Select the Desired Increment combobox from the Scales section of the Axis page and add the increment you require. You may change this by code at runtime:

Datetime data
If your data is datetime (You may set the data to datetime for your Series by going to the Series, General page), the Chart, Axis page and scales section will show a datetime range. Select the from the range shown in the Desired Increment combobox.
add some sample data

Change the Increment at runtime:

See the Axis.ExactDateTime property for more information about date axis labelling.

When changing axis label frequency, bear in mind that TeeChart will avoid label overlap according to the setting of the LabelsSeparation property. This means that if the label frequency is too high for the labels to fit, then TeeChart will allocate ‘best fit’. Changing the label angle and label separation are 2 options that may help you fit the labels you require. See the Labels section and LabelsAngle property.

Titles

Titles are set in the Titles section of the Axis page. You may change the Title text for the Axis and its font. The angle may be selected from values 0, 90, 180, 270 degrees. For runtime see the TChartAxisTitle Component.

Labels

When changing axis label frequency, bear in mind that TeeChart will avoid label overlap according to the setting of the LabelsSeparation property. This means that if the label frequency is too high for the labels to fit, then TeeChart will allocate a ‘best fit’. Changing the label angle and label separation are 2 options that may help you fit the labels you require. See the Labels section and the LabelsAngle property.

Label formats
You may apply all standard number and date formats to Axis labels. The Axis page, Labels section contains the field «Values format». If your data is datetime the field name changes to «Date time format». In the Editor drag the help «?» icon onto the field to get a full listing of options. at runtime use:

MultiLine labels
Axis labels can be displayed as multi-line text instead of a single line of text. Lines are separated using the TeeLineSeparator global constant, which by default is the carriage-return ascii character ( #13 ).

Example Example for DateTime labels:

The following will show the Bottom Axis labels in two lines of text, one showing the month and day, and the second line showing the year:
Feb-28 Mar-1 .. 1998 1998 ..

If you set the LabelsMultiLine property to True, the axis will automatically split labels into separate lines where spaces are found.

Dividing the Label into two:

‘mm/dd’ for the first line
‘hh:mm’ for the second line

At run-time you can always split the label into lines programmatically, using the OnGetAxisLabel event:

The axis LabelsAngle property ( label rotation in degree angles 0, 90, 180 or 270 ), can also be used with multi-line axis labels.

Customising Axis labels
Further Label control may be obtained by using Axis events. The events permit you to activate/deactivate/change any individual Axis label. The following example modifies each Label, putting a textual phrase in front of the point index value.

See the section entitled Axis events for more information about customising labels with Axis events.

Ticks

There are 3 tick types. You can change the length, width and colour of each tick type. If the tick width is set to 1 (default) then you may change the style to one of several line types (dot, dash, etc.). Style will be ignored if width is greater than 1.

Axis position

Axes have a property which modifies where each axis is to be located. In this example, the axis is moved to 50% of the total Chart width, so it is shown at the chart center:

Additional Axes
Copying axes

TeeChart offers 5 axes to be associated with data Series: Left, Top, Bottom, Right and Depth. When you add a new series to a Chart you may define to which of the axes the Series should be related (Go to the Series tab, General page). You may repeat any one (or all) of the 4 front axes at any place on the Chart by using the Axis Customdraw method. Note that this method makes a copy of your Axis, it does not add a new Custom Axis. See the next section, Multiple Custom Axes, for more information.

You will find this example, called «CustAxisProject1», with the TeeChart sample code:

Custom axes

In this example, TeeChart will plot the New axes, one horizontal and one vertical in the centre of your Chart. When you scroll the Chart (dragging with right mouse button), the new vertical axis will always remain central to the Chart, the new horizontal axis will move up and down with vertical scrolling. The new axes are exact copies of the default axes.

Multiple Custom Axes

Together with the PositionPercent and stretching properties, it�s possible to have unlimited axes floating anywhere on the chart. Scroll , zoom , and axis hit-detection also apply to custom-created axes. Creating extra axes is now possible both at designtime via the Chart Editor and at runtime via a few lines of code:

Via the Chart Editor
TeeChart offers you the ability to create custom axes at designtime enabling them to be saved in TeeChart’s tee file format. To achieve this, open the Chart Editor and click on the Axis tab and then select the «+» button to add a Custom Axis. Then select the Position tab making sure you have your new Custom Axis highlighted. The Horizontal checkbox on this page allows you to define your new Custom Axis as an horizontal axis or to leave it as the default vertical axis. The rest of this page and the other tabs in the Axis page can be used to change the Scales, Increment, Titles, Labels, Ticks, Minor Ticks and Position of the Custom Axis as explained above. To associate this new Custom Axis with the Data Series you desire select the Series tab and go to the General page where the dropdown Comboboxes ‘Horizontal Axis’ and ‘Vertical Axis’ will enable you to select your new Custom Axis depending on whether you previously defined it as vertical or horizontal.

You are able to then position the new Axis in overall relation to the Chart by using the StartPosition and EndPosition properties.

These figures are expressed as percentages of the Chart Rectangle with 0 (zero) (in the case of a vertical Axis) being Top. These properties can be applied to the Standard Axes to create completely partitioned ‘SubCharts’ within the Chart.

The above 2 coded examples when combined with the following data:

. will show the following Chart:

Multiple axes

Another technique for adding Custom Axes would be the following which uses the Axis List as the focal point by using the List Add then by accessing the Axis by Index:

Options are limitless! We advise caution when using Custom Axes as it is easy to start filling the screen with new axes and to lose track of which one you wish to manage !

Axis events

Axis events offer runtime flexibility to modify Axis Labels and offer interactivity to the user on Axis Clicks.

OnClickAxis
OnGetAxisLabel

Can be used to modify Axis Labels. See the OnGetAxisLabel event.

OnGetNextAxisLabel

Can be used to decide which Axis Labels should be displayed. See the OnGetNextAxisLabel event. You should use the Stop Boolean property to include/exclude Axis Labels.

The above example will start labelling at ‘5’ on the Bottom Axis labelling every 5 points. Other Axes’ Labels are unaffected.

1. Теоретические сведения

Графический способ представления информации является одним из наиболее мощных средств визуального анализа данных. С помощью графиков и диаграмм можно легко выявить закономерности и тенденции изменения данных, неочевидные при анализе данных, представленных в табличной форме.

В системе Delphi есть несколько компонентов, предназначенных для отображения данных в виде графиков и диаграмм:

компоненты Chartfx и VtChart, находящиеся на странице ActiveX палитры компонентов;

набор компонентов из пакета TeeChart:

TChart — основной компонент пакета TeeChart, используемый для отображения в графическом виде данных, получаемых не из баз данных. Расположен на странице Additional палитры компонентов. Все остальные компоненты пакета TeeChart являются наследниками этого компонента;

TDBChart используется для отображения в графическом виде данных, получаемых из различных источников, в том числе и из баз данных. Расположен на странице Data Controls палитры компонентов;

TDecisionGraph используется для отображения в графическом виде данных, получаемых из многомерного куба данных сформированного с помощью компонентов, находящихся на странице Decision Cube палитры компонентов;

TQRChart используется для отображения графиков в отчете. Расположен на странице QReport палитры компонентов.

Компонент TDBChart, в отличие от всех других компонентов визуализации данных, связывается не с источником данных (например, компонентом типа TDataSource), а напрямую с компонентом набора данных (например, TTable или TQuery). Он включает в себя набор объектов TСhartSeries, инкапсулирующих множество данных и ряд параметров, определяющих вид отображения информации.

Для построения диаграмм и графиков необходимо подготовить исходные данные, на основе которых они будут строиться. Эти данные могут находиться в таблице базы данных, представленной компонентом TTable, или формироваться SQL-запросом, заданным в компоненте TQuery.

2. Технология настройки компонента tdbChart

Рассмотрим технологию настройки компонента TDBChart на примере графического представления сведений, хранящихся в таблице Animals.dbf из базы данных DBDEMOS. Сведения включают в себя название (NAME), размер (SIZE), вес(WEIGHT) и ареал обитания (AREA) животных.

Технология состоит из следующих этапов:

Поместить в форму приложения, созданного в системе Delphi, компоненты TTable и TDBChart.

Связать компонент TTable с таблицей Animals.dbf из базы данных DBDEMOS.

Рис.1. Окно редактора свойств TeeChart

Рис.2. Диаграмма с двумя сериями

астроить компонент TDBChart с помощью специального редактора свойств TeeChart (рис.1), который вызывается двойным щелчком мыши на компоненте TDBChart, размещенным в форме. Редактор позволяет устанавливать свойства графика и его серий. Серией называется набор точек графика. На графике серии соответствует отдельная линия или набор столбцов. Например, на рис.2 показана диаграмма, состоящая из двух серий: 1-я показывает размер животных, а 2-я — их вес.

Окно редактора свойств (см. рис.1) представляет собой табулированный блокнот. Для нового графика (или диаграммы) первой всегда показывается страница с закладкой Chart, на которой открыта страница с закладкой Series.

Каждая из закладок на странице Chart предназначена для установки параметров того или иного компонента графика.

Series — содержит серии графика (или диаграммы).

General — служит для установки общих параметров графика, таких как его объемность, отступы от краев, возможность увеличения (Zoom) и др.

Рис.3. Страница установки свойств осей

xis — используется для определения осей графика (рис.3). С помощью переключателей Axis можно выбрать нужную ось графика — левую, правую, верхнюю или нижнюю. На странице с закладкой Scales устанавливаются свойства масштаба значений по выбранной оси. Страница с закладкой Title используется для задания текста заголовка по выбранной оси, угла его расположения и шрифта, которым выводится заголовок. Страница с закладкой Labels служит для определения параметров меток, связанных с осями, а на странице с закладкой Tiks устанавливаются параметры линий оси и координатной сетки.

Titles — содержит средства для определения текста заголовка графика, его шрифта, выравнивания и др.

Legend — определяет параметры легенды — области, в которой приводится поясняющая информация (см. рис.2).

Panel — определяет параметры панели, на которой располагается график.

Paging — определяет параметры многостраничного графика.

Walls — определяет параметры левой, нижней и задней «стенок» графика.

3D — определяет параметры объемности и ориентации графика.

Создать экземпляр класса TChartSeries, нажав кнопку Add, расположенную на странице Chart/Series в окне редактора свойств TeeChart (см. рис.1). При этом откроется окно диалога (рис.4), в котором следует выбрать тип создаваемой диаграммы. Для нашего примера выберем круговую диаграмму типа Pie.

Указать компонент набора данных, в котором находится информация для построения диаграммы (или графика). Для этого перейти на страницу Series в окне редактора свойств TeeChart (см. рис.1), выбрать на ней закладку Data Source и с помощью выпадающего списка, размещенного на активизированной странице Data Source, задать тип источника информации DataSet.

Рис.4. Окно выбора типа диаграммы

осле этого на этой странице появится ряд элементов управления (рис.5), с помощью которых задаются следующие параметры:

имя набора данных — выпадающий список Dataset;

имя поля из выбранного набора данных, значения которого будут использоватьсяв качестве меток на диаграмме, — выпадающий список Labels;

Рис.5. Настройка параметров источника информации

мя поля, данные из которого будут использоваться при построении диаграммы, — выпадающий список Pie.

Кроме закладки Data Source, на странице Series имеются закладки Format, General, Marks. С помощью Format определяются свойства палитры, линий графика и т.д., с помощью General задаются форматы данных, а закладка Marks предназначена для установки марок — значений над точками или сегментами серии. Марки отображаются на графике или диаграмме, если отмечен перключатель Visible (рис.6). Переключатели Style определяют вид марок (на рис.6 в качестве марок задано использование меток Label).

Рис.6. Определение вида марок серии

адать название диаграммы (например, «Диаграмма сравнения размеров животных») и параметры ее отображения (шрифт, цвет и т.п.) на странице Chart/Titles в окне редактора свойств TeeChart (рис.7).

Задать процедуры обработки событий формы приложения OnShow и OnClose. В первой процедуре открыть набор данных, во второй — закрыть его.

Откомпилировать и запустить приложение на выполнение.

Рис.7. Задание заголовка диаграммы

нешней вид главного окна приложения показан на рис.8.

Рис.8. Окно приложения с созданной диаграммой

Работа с другими типами диаграмм принципиально не отличается от рассмотренного примера. Единственной особенностью для некоторых типов диаграмм (таких, как гистограммы (Bar) и графики (Line и Fast Line)) является необходимость указывать поля таблицы базы данных, которые соответствуют осям абсцисс (X) и ординат (Y).

Рассмотрим особенности технологии создания столбчатой диаграммы (гистограммы Bar) на примере отображения тех же сведений, что и на круговой диаграмме. Последовательность действий, необходимых для реализации этого варианта диаграмм, во многом совпадает с приведенными ранее для построения круговой диаграммы. Поэтому будут отмечены только особенности подключения компонента набора данных TTable к компоненту TDBChart.

Поместить в форму компоненты TTable и TDBChart. Компонент TTable связать с таблицей Animals.dbf из базы данных DBDEMOS, а в компоненте TDBChart с помощью редактора свойств TeeChart создать серию, выбрав тип диаграммы Bar (см. рис.4).

Связать источник данных с компонентом TDBChart и задать поля, соответствующие осям абсцисс и ординат. Необходимые параметры задаются на странице Series/Data Source, которая для диаграмм типа Bar в отличие от предыдущего примера имеет дополнительный выпадающий список Х, с помощью которого задается поле, соответствующее оси абсцисс, если оно отлично от поля, указанного в качестве метки (рис.9).

Откомпилировать и выполнить приложение. Диаграмма будет иметь вид, близкий к приведенному на рис.10.

Каталог статей Delphi Report

A TeeChart Pro Function is a Series, that can be of almost any Series Type, to which an algebraic function is applied and for which the datasource is another Chart Series.

All Functions derive from the TTeeFunction Component and inherit TeeFunction’s Period property.

TeeChart Pro includes the following list of predefined functions. Please see the TeeChart Editor Gallery and Helpfile for a full list of all Function Types:

Function Type

No. of inputs

Description

Several Function types support only one input Series. However it is possible to chain link Functions, thus, for example, taking the average of several Series in your Chart to create an Average Function Series, then identify the Trend of the average by using the Average Function as the input to the Trend Function.

Adding a Function

With the Chart Editor, on the First Chart page, select the Add button as if to add a new Series to the Chart. In the TeeChart Gallery choose the Functions tab to select the Function you require. Each Function is presented as a Line Series, you may change the Series Type associated with the Function later by choosing the Change button on the first Chart Page. Function definitions are easily changed afterwards on the Datasource page of the Function Series. Here, just as easily, you may change the definition of a normal Series that you have added to the Chart to that of a Function (Function is really a definition of datasource, not a definition of Series Type).

The image below shows the Datasource page when editing a Function. The Line Series (Name «Series2», Title «Average») is defined. The left listbox at the bottom of the Datasource page shows other Series in the Chart available for input (here «Series1»).

Assuming we start with a completely empty Chart here are the steps in code to build a simple Series-Function related Chart.

We can add another Function to tell us something about the previous Function

Defining a datasource

The examples in the previous section highlight the use of Datasource for poulating a Function by code. Series use Datasource for defining the input for a Function or to define a Series TDataset datasource (see the Tutorial about accessing databases).

Using the Chart Editor, after adding a Function, the Function Series’ Datasource page will show a list of available series for inclusion in the function definition. Here you may change the Function Type you wish to apply to the Series and select Series from the Left listBox «Available» and add them to the right Listbox,»Selected».

Datasource by code uses the Series.Datasource property.

Suppose we have 2 data Series in a Chart added in at design-time via the TeeChart Editor. We add a Function composed of the average of the 2 Series:

We add points to the 2 Series:

Notice that the Function doesn’t display. You need to use the checkDataSource method to read in values for the Function.

Function definitions may be changed at runtime to allocate a new Function to the Series simply by redefining the Series.DataSource method:

Function Period

Period is an important method for working with Functions because the Period defines the range of points across which a Function is cyclically applied.

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) the average drawn is:

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

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 Chart Editor or you may modify Period at runtime using FunctionType.

Eg. Where Series 2 is the function series:

Below are 2 Charts that highlight the effect of an applied Period

Period Style

Period can be defined to be a range. This is very useful when using DateTime series and we want to express the «Period» of the function as a TimeStep. The property «PeriodStyle» controls how is «Period» expressed.

For example you can now plot the «monthly average of sales» function just using a normal «Average» function on a date-time source series and setting the function period to «one month»:

This will result in several points, each one showing the «average» of each month of data in the BarSeries. It’s mandatory that points in the source Series should be sorted by date when calculating functions on datetime periods. The range can also be used for non-datetime series:

This will calculate an average for each group of points inside every «6» interval.
(Points with X >=6, X<6 will be used to calculate the first average, points with X >=6, X<12 will be used to calculate the second average and so on. ).
Notice this is different than calculating an average for every 6 points.

Use the Period Alignment property to align the function Points within the Series range. The following will plot the Function point at the end of a monthly Period:

Period = Month.TotalDays and PeriodAligns.First
As you can see from the picture below, the «average» is plotted at the end of the month.

Period = Month.TotalDays and PeriodAligns.Last
In this case the «average» is plotted at the beginning of the month.

Deriving custom functions

Creating a new Function component is simply creating a new component derived from Function class (it also can be derived from an existing function ). There are 2 important virtual methods in TTeeFunction that can be overridden to create a new Function type.

1) Function.Calculate: public virtual double Calculate(Series Source,int First,int Last)

2) Function.CalculateMany: public virtual double CalculateMany(ArrayList SourceSeries, int ValueIndex)

The Calculate method is used to calculate function result if only one series is datasource. CalculateMany is used to calculate function result if multiple series can be datasource.

Example : Creating new SquareSum Funtion.

Let’s decide we need a SquareSum Function to return the «sum of squares».

This function can have only one datasource or multiple datasources, so we’ll override the Calculate and CalculateMany methods.

The FirstIndex and EndIndex variables are used to «loop» all SourceSeries points to calculate the sum of squares.

The «ValueList» method is used to extract the mandatory Steema.TeeChart.ValueList to make the class work with Series types like HorizBarSeries where «XValues» holds the point values and not «YValues».

The «Calculate» method is used when the Series has only one Series as DataSource. When Series have more than one Series as datasources, the «CalculateMany» method is called.

«CalculateMany» will get called once for each point in the source Series, starting from zero and ending with the minimum point count of all datasources.

It is very important to understand the difference between Calculate and CalculateMany. «Calculate» is called when there is only one datasource and it’s called only once. «CalculateMany» is called several times (one for each point) when there are more than one Series as datasources.

Похожие статьи