Page 1 of 1

Charts with Bars with Negative values

Posted: Thu Dec 19, 2024 7:36 pm
by 16596488
In the attached demo, I have a TChart that has bars, some with negative values.

The image is visible here: https://app.screencast.com/iyBZFNk6yvUsB

I have two items I need help with.

1) For the first red bar with a negative value, there is no margin between the red and the axis--how do I create a margin between the red bar and the line at the bottom?

2) For the left axis, I want the zero value line to be the darker/heavier line, and the other lines to be lighter.

How can I achieve this?

Ed Dressel

Re: Charts with Bars with Negative values

Posted: Fri Dec 20, 2024 9:29 am
by yeray
Hello Ed,
Ed Dressel wrote:
Thu Dec 19, 2024 7:36 pm
1) For the first red bar with a negative value, there is no margin between the red and the axis--how do I create a margin between the red bar and the line at the bottom?
You can add some offset to the left axis:

Code: Select all

  Chart1.Axes.Left.MaximumOffset:=10;
  Chart1.Axes.Left.MinimumOffset:=10;
Ed Dressel wrote:
Thu Dec 19, 2024 7:36 pm
2) For the left axis, I want the zero value line to be the darker/heavier line, and the other lines to be lighter.
You can move the Bottom with the PositionPercent property calculating the position of the 0 value in pixels as follows:

Code: Select all

procedure TForm1.FormCreate(Sender: TObject);
begin
  //...
  
  Chart1.Axes.Bottom.PositionUnits:=muPixels;
  Chart1.OnBeforeDrawAxes:=AxesBeforeDraw;
  Chart1.Draw;
end;

procedure TForm1.AxesBeforeDraw(Sender: TObject);
begin
  Chart1.Axes.Bottom.PositionPercent:=Chart1.ChartRect.Bottom - Chart1.Axes.Left.CalcPosValue(0);
end;
The problem is that, moving the bottom axis to the middle of the chart, then the labels are drawn behind the bars, and you probably don't want that.
There's a Axes.Behind property you can set to False, but then the left axis grid will also be drawn on top of the bars, which you probably don't want.
Then, the trick is to play with OnBeforeDrawChart and AfterDrawValues events to disable and enable those properties. Ie:

Code: Select all

procedure TForm1.FormCreate(Sender: TObject);
begin
  //...
  
  Chart1.OnBeforeDrawChart:=ChartBeforeDraw;
  Series1.AfterDrawValues:=SeriesAfterDraw;
end;
  
procedure TForm1.ChartBeforeDraw(Sender: TObject);
begin
  Chart1.Axes.Behind:=True;
  Chart1.Axes.Bottom.Texts.Font.Color:=clNone;
  Chart1.Axes.Left.Grid.Visible:=True;
end;

procedure TForm1.SeriesAfterDraw(Sender: TObject);
begin
  Chart1.Axes.Behind:=False;
  Chart1.Axes.Bottom.Texts.Font.Color:=clBlack;
  Chart1.Axes.Left.Grid.Visible:=False;
end;
BottomAxisMoved.png
BottomAxisMoved.png (12.78 KiB) Viewed 727 times

Re: Charts with Bars with Negative values

Posted: Fri Dec 20, 2024 3:45 pm
by 16596488
Thank you. That works well--but is there any way to move the series labels (e.g. "2 Years Before") below the chart, rather than overwriting the series)?