How to modify C# Chart control chartArea percentages

Xantham picture Xantham · Mar 15, 2013 · Viewed 21.5k times · Source

If I have a chart control with 2 chartAreas in it, the chart control by default puts the chartAreas on top of each other makes each area take 50% of the available size of the chart control.

Is there a way to change the chartAreas' percent so that I could say, have the top chart take 75% of the area, and the bottom chart take 25%?

Answer

Xantham picture Xantham · Mar 15, 2013

So, I eventually found it, but I do not think that it is very well documented. There each chartArea has the property ChartArea.Position. This property of the type ElementPosition, and contains 4 properties that are relevant to this problem.

Height: Gets or sets the height of a chart element.
Width: Gets or sets the width of a chart element.
X: Gets or sets the relative X-coordinate of the top-left corner of an applicable chart element.
Y: Gets or sets the relative Y-coordinate of the top-left corner of an applicable chart element.

When you dig deeper, the Height and Width properties are also stated in relative coordinates, such that you can only input 0 - 100.

Basically, you have to change each height, and each Y to move shift them. After the initial creation, it will not automatically adjust the other numbers.

For instance, if I just change the Height of chartArea[1] to something smaller, it will still be anchored where it was previously, as would make sense, leaving a lot of white space below it.

If I then increase the Height of chartArea[0], it may draw over chartArea[1] that we just resized. So then I have to set the Y of chartArea[1] to move it down, so that it is not drawn over, and the white space is gone.

So, to get something similar to what I asked in the question, I set it to:

chart1.ChartAreas[0].Position.Y = 10;
chart1.ChartAreas[0].Position.Height = 60;
chart1.ChartAreas[1].Position.Y = 70;
chart1.ChartAreas[1].Position.Height = 20;

To make this explanation a bit more clear, I will refer to the Chart control that these chartAreas are in as "the parent".

These are percentages, but for this example, let us assume that the parent's size is 100 pixels.

This sets the first chartArea start displaying at 10 px, and makes it about 60px tall. It then starts displaying the second chartArea at 70px, and makes it about 20px tall.

If this chart was 200px tall, then the proportions would be the same, but the actually pixels would be double (so setting the first chart area to 60 would make it 120px tall).

I did pad this a bit more in my real program, because this has titles overwriting axis labels, but I felt these numbers helped explain it better.