TAChart Tutorial: Getting started/fr

From Lazarus wiki
Revision as of 22:55, 9 February 2015 by LazarusBob (talk | contribs) (Created page with "== Introduction == file:tachart_getting_started_step6.png Si vous voulez ajouter un tracé ou un graphique à votre fiche Lazarus vous devriez jeter un oeil sur [[TAChar...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search

Introduction

tachart getting started step6.png

Si vous voulez ajouter un tracé ou un graphique à votre fiche Lazarus vous devriez jeter un oeil sur TAChart. C'est le paquet standard Lazarus pour dessiner des tracés et des graphqiues.

Dans ce tutoriel nous allons dessiner quelques fonctions mathématiques élémentaires avec TAChart. Nous allons créer un graphique avec 3 séries de lignes pour ces fonctions

  • y=cos(x),
  • y=sin(x), et
  • y=cos(x)*sin(x).

Il sera peut-être nécessaire d'expliquer les termes "séries" et "graphques" ici: le diagrame entier est le "graphique" (chart), et chacune des fonctions sera affichée comme une courbe appelée "séries". Nous allons connecter les points de données avec des sections de lignes, d'où nous utiliserons les "séries de lignes". TAChart, bien sûr, permet d'utiliser de nombreux autres types de séries, par exemples les séries de barres, les séries de surface, les séries de camberts, ou même des types avancés comme les splines ou les séries adaptatives (fit).

Ce qui est requis?

Ce guide sera très élémentaire. Bien sûr, vous aures besoin de la connaissance de base du langage Pascal Object de le l'EDI Lazarus.

TAChart est inclus dans Lazarus, il n'y a donc pas besoin de rechercher ce paquet sur internet. Cependant n'utilisez pas une version trop ancienne de Lazarus du fait que TAChart est activement développé et certaines fonctionnalités peuvent changer entre deux versions.

Le mieux est de suivre ce tutoriel pas-à-pas. mais si vous le voulez vous pouvez utiliser le code source du projet achevé à la fin de cet article.

Un nouveau projet

TAChart component palette.png

Pour commencer, nous créons un nouveau projet dans Lazarus et dans la palette composants nous sélectionnons la page "Chart". Cliquez sur l'icon la plus à gauche, le composant TChart et ajoutez-le sur la fiche. Vous verrez un diagramme vide avec les axes standards x et y.

TAChart GettingStarted Step1.png

Ajouter des séries

Ajoutons maintenant des séries. Pour cela, double-cliquez sur le chart (ou cliquez-droit et sélectionnez "Edit series" depuis le menu contextuel). L'éditeur de séries TAChart apparait. Il est encore vide mais vous pouvez sélectionner "Ajouter" vous verrez un menu avec tous les types de séries disponibles dans le paquet TAChart. Sélectionnez le "line series". Répétez deux fois pour créer, au total, trois séries de lignes qui sont assignées au chart. Elles ne sont pas encore affichées sur le chart parce qu'elles ne possèdent pas encore de données. Pas de données, pas d'affichage. Nous allons arranger cela dans une minute.

TAChart GettingStarted Step1a.png

Avant de faire cela jetons un oeil à l'arborescence de l'inspecteur d'objet. TAChart utilise une architecture assez complexe de classes et de conteneurs, il est donc important de comprenre l'arborescence de l'objet. Au stade actuel de notre projet nous pouvons voir que le composant TChart et ses enfants, les trois séries de lignes et le AxisList avec les axes Left et Bottom comme enfants également. Les noms de séries sont construites en rapport avec Chart<number><SeriesType><Number>.

tachart getting started object tree.png

Why don't we give them more descriptive names, like SinSeries, CosSeries, and SinCosSeries? For this purpose, click on each series, and change the series Name in the corresponding field of the object inspector below.

Adding data

Now it's time to add data. The easiest option is to create the data along with the form, i.e. we write a handler for the forms's OnCreate event. Of course, in a "real" project, you will add data at other occasions, for example after a button click which might initiate a calculation or read data from a file.

procedure TForm1.FormCreate(Sender: TObject);
const
  N = 100;
  MIN = -10;
  MAX = 10;
var
  i: Integer;
  x: Double;
begin
  for i:=0 to N-1 do begin
    x := MIN + (MAX - MIN) * i /(N - 1);
    SinSeries.AddXY(x, sin(x));
    CosSeries.AddXY(x, cos(x));
    SinCosSeries.AddXY(x, sin(x)*cos(x));
  end;
end;

This procedure creates 100 data points for each series. The x values are calculated to be equidistant between MIN and MAX, i.e. -10 and 10. The important lines are the calls to the AddXY method of each series. This method takes the x and y coordinates of each data point and adds them to an internal list. There are also overloaded versions of this method where you can also pass a text label for each data point, as well as an individual color, but we don't need this feature here.

The mentioned list is a so-called chart source - this is a class which provides the data for plotting. You can use the built-in chart source, or you can link the series to a separate one. There is a variety of chart sources in the component palette, like

  • TListChartSource which stores the data in a list (this type is used by our series internally)
  • TDBChartSource which interfaces to the records and fields in a database
  • TUserDefinedChartSource which gives a very general access to data, for example, stored in an array of user-defined records
  • TCalculatedChartSource which allows to analyze one series and display the results in another one.

But enough on chart sources - the built-in source is sufficient for this introductory project.

tachart getting started step2.png

Ok, let's compile the program. We see the three curves, and the x axis automatically covers our data range between -10 and 10. Well - not too bad, but far from being perfect: The diagram is very confusing, we cannot distinguish between the individual lines, and we cannot tell which series belongs to which function.

Formatting the series

Why don't we change the color of each series? To do this select each series in the object tree and, in the object inspector below, change the property SeriesColor as you want it to be - SeriesColor is the color of the lines connecting the data points.

When you recompile you will see the series colored. But we still cannot distinguish between the different functions. What we need is a legend.

Adding a legend

Highlight the chart and, in the object inspector, scroll down to Legend and open the sub-properties. At the end, there is Visible which is false by default - so, set it to true, and recompile.

tachart getting started step3.png

Well, it's getting better. What is missing, is an explanatory text for each series, like y = sin(x). For this purpose each series has a property Title - this is the text which will appear in the legend for each entry along with the symbol for the corresponding series. Therefore you have to go through all series again and use the object inspector to set Title to y=sin(x), y=cos(x), and y=sin(x)*cos(x), respectively.

tachart getting started step4.png tachart getting started step4a.png

Now when you recompile, the chart is almost perfect. Almost - because the legend is quite large, and the diagram is squeezed into the remaining space. Of course, we could increase the size of the form. But can we also put the legend underneath the diagram? No problem: go back to the chart's property Legend and set Alignment to laBottomCenter. You should also set ColumnCount to 3, otherwise the legend items will be in a column instead of in a row.

tachart getting started step5.png

Ah! -- the third legend entry is truncated because the window is not wide enough. Align the chart to alClient and increase the width of the window a bit.

Fine-tuning

A few more things can still be improved: The axes should have a title, like "x axis" and "y axis", respectively, and there should also be a title above the chart.

To set the title for the x axis select in the object tree the item Bottom of the AxisList child component of TChart, or go to Bottom axis in the object inspector. Open the sub-properties where you'll find Title which has sub-properties again. The text in the field Caption will be displayed as a title above the chart. Don't forget to set Visible to true. You may also want to set the font style of the title to bold - you find that property under LabelFont. Repeat the same with Left axis.

Essentially the same procedure can be used to set the chart title: Scroll to the chart's property Title, enter the title in the field Text (you may even use a multi-line text here), and set Visible to true again.

And finally, you might prefer to use a white background of the chart area, this is changed by the property BackColor of TChart. And maybe the grid should be less emphasized, i.e. it might look better with color clSilver. Use the left and bottom axes property Grid.Color to change that.

Finished!

In the end, our chart looks like this. Neat, isn't it? And it was not difficult at all...

If you want to learn more about TAChart have a look at the official TAChart documentation, and study some of the many demos that come with TAChart. They can be found in the folder components\tachart\demo of your Lazarus installation.

tachart getting started step6.png

Source code

The source code of this tutorial project can be found in the folder tutorials/getting_started of trunk TAChart installations.

Project file

program project1;

{$mode objfpc}{$H+}

uses
  {$IFDEF UNIX}{$IFDEF UseCThreads}
  cthreads,
  {$ENDIF}{$ENDIF}
  Interfaces, // this includes the LCL widgetset
  Forms, Unit1, tachartlazaruspkg
  { you can add units after this };

{$R *.res}

begin
  RequireDerivedFormResource := True;
  Application.Initialize;
  Application.CreateForm(TForm1, Form1);
  Application.Run;
end.

Unit1.pas

unit Unit1;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, FileUtil, TAGraph, TASeries, Forms, Controls, Graphics,
  Dialogs;

type

  { TForm1 }

  TForm1 = class(TForm)
    Chart1: TChart;
    SinSeries: TLineSeries;
    CosSeries: TLineSeries;
    SinCosSeries: TLineSeries;
    procedure FormCreate(Sender: TObject);
  private
    { private declarations }
  public
    { public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.lfm}

{ TForm1 }

procedure TForm1.FormCreate(Sender: TObject);
const
  N = 100;
  MIN = -10;
  MAX = 10;
var
  i: Integer;
  x: Double;
begin
  for i:=0 to N - 1 do begin
    x := MIN + (MAX - MIN) * i / (N - 1);
    SinSeries.AddXY(x, sin(x));
    CosSeries.AddXY(x, cos(x));
    SinCosSeries.AddXY(x, sin(x)*cos(x));
  end;

end;

end.

Unit.lfm

object Form1: TForm1
  Left = 14
  Height = 244
  Top = 137
  Width = 347
  Caption = 'Form1'
  ClientHeight = 244
  ClientWidth = 347
  OnCreate = FormCreate
  LCLVersion = '1.1'
  object Chart1: TChart
    Left = 0
    Height = 244
    Top = 0
    Width = 347
    AxisList = <    
      item
        Grid.Color = clSilver
        Minors = <>
        Title.LabelFont.Orientation = 900
        Title.LabelFont.Style = [fsBold]
        Title.Visible = True
        Title.Caption = 'y axis'
      end    
      item
        Grid.Color = clSilver
        Alignment = calBottom
        Minors = <>
        Title.LabelFont.Style = [fsBold]
        Title.Visible = True
        Title.Caption = 'x axis'
      end>
    BackColor = clWhite
    Foot.Brush.Color = clBtnFace
    Foot.Font.Color = clBlue
    Legend.Alignment = laBottomCenter
    Legend.ColumnCount = 3
    Legend.Visible = True
    Title.Brush.Color = clBtnFace
    Title.Font.Color = clBlue
    Title.Font.Style = [fsBold]
    Title.Text.Strings = (
      'My first chart'
    )
    Title.Visible = True
    Align = alClient
    ParentColor = False
    object SinSeries: TLineSeries
      Title = 'y=sin(x)'
      LinePen.Color = clRed
    end
    object CosSeries: TLineSeries
      Title = 'y=cos(x)'
      LinePen.Color = clBlue
    end
    object SinCosSeries: TLineSeries
      Title = 'y=sin(x)*cos(x)'
      LinePen.Color = clGreen
    end
  end
end