Create a stacked bar chart

20,567

The source code above seems to be from the MS Chart Samples application. Looking at the MS example stacked bar chart on screen, and the source code above, its obvious that the sample code is inadequate and does not show us how to do stacked bar charts.

You can either programmatically create and attach a series:

Series s1 = new Series("LightBlue");
s1.ChartType = SeriesChartType.StackedBar100;
chart1.Series.Add(s1);

or alternatively, you can define the series in your ASPX file and simple add Y values to each series in the code behind:

Random  random = new Random();
for(int pointIndex = 0; pointIndex < 10; pointIndex++)
{
    Chart1.Series["Series1"].Points.AddY(Math.Round((double)random.Next(45, 95),0));
    Chart1.Series["Series2"].Points.AddY(Math.Round((double)random.Next(5, 75),0));
    Chart1.Series["Series3"].Points.AddY(Math.Round((double)random.Next(5, 95),0));
    Chart1.Series["Series4"].Points.AddY(Math.Round((double)random.Next(35, 95),0));
}

In the MS Chart Samples web solution, have a look at

/ChartTypes/BarColumnCharts/Stacked/stackedchart.aspx

it should have all you need.

Share:
20,567
m4n07
Author by

m4n07

Updated on June 16, 2020

Comments

  • m4n07
    m4n07 almost 4 years

    I'm trying to create a stacked bar chart , But I'm getting an error in the lines that has ".Series " (How to define the Series ? )

        SeriesChartType chart1 = new SeriesChartType();
    
        // Populate series data
        Random random = new Random();
    
        for (int pointIndex = 0; pointIndex < 10; pointIndex++)
        {
            chart1.Series["LightBlue"].Points.AddY(random.Next(45, 95));
        }
    
        // Set chart type
        chart1.Series["LightBlue"].ChartType = SeriesChartType.StackedArea100;
    
        // Show point labels
        chart1.Series["LightBlue"].IsValueShownAsLabel = true;
    
        // Disable X axis margin
        chart1.ChartAreas["Default"].AxisX.IsMarginVisible = false;
    
        // Set the first two series to be grouped into Group1
        chart1.Series["LightBlue"]["StackedGroupName"] = "Group1";
        chart1.Series["Gold"]["StackedGroupName"] = "Group1";
    
        // Set the last two series to be grouped into Group2
        chart1.Series["Red"]["StackedGroupName"] = "Group2";
        chart1.Series["DarkBlue"]["StackedGroupName"] = "Group2";