Recent

Author Topic: [SOLVED] Create chart with number of series known at runtime  (Read 3289 times)

tudi_x

  • Hero Member
  • *****
  • Posts: 538
[SOLVED] Create chart with number of series known at runtime
« on: October 14, 2014, 10:43:22 pm »
I am trying to write a procedure in which a chart is to be created based on the number of columns in a database table (let us say table has three columns, first two columns have values for Y series one and two and the third column for X series).
Basically I can have charts that would have a variable number of (Y) series.

Please advise how could I create these line series at run time.

Thank you

(Lazarus 1.2.4 32 bit on Windows 7 64 bit)
« Last Edit: October 16, 2014, 03:49:40 am by tudi_x »
Lazarus 2.0.2 64b on Debian LXDE 10

wp

  • Hero Member
  • *****
  • Posts: 7517
Re: Create chart with number of series known at runtime
« Reply #1 on: October 15, 2014, 12:42:13 am »
I am assuming your dataset contains five fields named "x", "y1", "y2", "y3", "y4". The dataset is linked to a Datasource.

Add a DbChartSource to the form, link it to the DataSource.
Add a button which adds a new series to the chart:
Code: [Select]
procedure TForm1.Button1Click(Sender: TObject);
begin
  // of course, you should use a more sophisticated logic here...
  case Chart1.SeriesCount of
    0: AddSeries('y1');
    1: AddSeries('y2');
    2: AddSeries('y3');
    3: AddSeries('y4');
  end;
end;

The method "AddSeries" adds a series at runtime; it copies the data from the DBChartsource to the internal ListSource of the series; you could also work with the DBChartSource directly but this requires to load the data from the server with each change of data parameters:

Code: [Select]
const
  COLORS: Array[0..3] of TColor = (clBlue, clRed, clGreen, clFuchsia);  // a color for each series

procedure TForm1.AddSeries(AFieldName: String);
var
  series: TLineSeries;
begin
  DBChartSource1.FieldX := 'x';
  DBChartSource1.FieldY := AFieldName;
  DBChartSource1.DataSource := DataSource1;

  series := TLineseries.Create(self);  // or you could create a bar series by "TBarSeries.Create", etc.
  series.SeriesColor := COLORS[Chart1.SeriesCount];
  series.ListSource.CopyFrom(DBChartSource1);
  series.Title := AFieldName;  // for the legend
  // set other properties here...
  Chart1.AddSeries(series);
end;

Since the table data are copied to the series the table can be closed afterwards.
Mainly Lazarus trunk / fpc 3.2.0 / all 32-bit on Win-10, but many more...

tudi_x

  • Hero Member
  • *****
  • Posts: 538
Re: Create chart with number of series known at runtime
« Reply #2 on: October 16, 2014, 03:47:31 am »
Thank you for putting me in the right direction.
Lazarus 2.0.2 64b on Debian LXDE 10

 

TinyPortal © 2005-2018