I have a chart
with type columns
. How will I add a background color to the Y Axis? like the gray color in this graph? Is this possible? I am using
Short of painting the gray columns, (which is painfully hard to get right) I see two options:
ChartAreas
to get the designed effect.Here is a solution that uses StackedColumn
.
You need to do a few things to make it work:
You need to know the y value (max) of how far the grey columns should go.
You need to add a dummy series for them.
You need to set all series to StackedColumn
You need to set the special property StackedGroupName so that the series you want to be stacked have the same name.
Here is an example:
Here is the code:
chart3.Series.Clear();
Series s1 = chart3.Series.Add("S1");
s1.ChartType = SeriesChartType.StackedColumn;
Series s2 = chart3.Series.Add("S2");
s2.ChartType = SeriesChartType.StackedColumn;
Series s0 = chart3.Series.Add("S0");
s0.ChartType = SeriesChartType.StackedColumn;
s0.Color = Color.LightGray;
s0.IsVisibleInLegend = false;
s0["StackedGroupName"] = "Group1";
s1["StackedGroupName"] = "Group1";
s2["StackedGroupName"] = "Group2";
for (int j = 0; j < data.Columns.Count; j++)
{
for (int i = 0; i < data.Rows.Count; i++)
{
double vy = Convert.ToDouble(data.Rows[i][j].ToString());
chart3.Series[i].Points.AddXY(j, vy);
if (i==0) s0.Points.AddXY(j, 800 - vy);
}
}
List<string> mn = new List<string>() { "J", "F", "M", "A" };
for (int i = 0; i < s0.Points.Count; i++)
{
s0.Points[i].AxisLabel = mn[i];
}
A few more notes:
For stacking to work the columns need to have numeric x-values. Make sure to change your code to some useful values!!
I simply took the loop index and added labels afterwards. You could also take a month and use a suitable DateTime format. I have also adapted the loop to fit my table layout
I didn't add any other styling and I have not used any data binding. Not sure what that line means in your code.
The dummy Series s0
gets dummy values calculated from a max - yvalue
.
I trusted my values and did a Convert
without TryParse
. Pick your way!
The 2nd series s2
is not not in a stacking group with any other series, so it stands alone.
The order of the series in the legend is reversed to make them look like the stacks. You can reverse the order in which you add them if you like..
You may want to study this post which dicusses a few common issues with stacking.
Your other option would be to overlay two chartareas precisely and set their points and their colors so that the combined effect looks like your image. Here is an example that overlays two pie-like charts..