简体   繁体   中英

how to add value in 'y' on same 'x' point in c# chart

I am trying to create a column chart based on a string array. if more than 1 strings correspond to same string value it should just add up the number and use same bar for representation of similar strings. However this code of mine results in representation on different bars (each having 1 as their value):

    private void plot_chart(string[] DTCs)
    {
        foreach (string str in DTCs)
        {
            bool doNotaddSeries = false;

            foreach (var ser in chart3.Series)
            {
                if (str == ser.Name)    //series already exists
                {
                    doNotaddSeries = true;
                    ser.Points.AddY(1);
                    //MessageBox.Show(str + " exists");
                    break;
                }
            }

            if (!doNotaddSeries)
            {
                chart3.Series.Add(str);
                chart3.Series[str].Points.AddY(1);
            }

            doNotaddSeries = false;
        }
    }

what I want is (lets say) if i have:

    str[0]="abc"
    str[1]="def"
    str[2]="abc"

i want "abc" to be represented on single bar with a value of 2 on y. whereas "def" should have 1 value on y axis. What I am getting is "abc" being represented as 2 different bars but similar representation of color in legend

Just use linq GroupBy to process it for you then add them after

var DTCs = new [] {"abc", "def", "abc"};
var points = DTCs.GroupBy(str => str).Select(group => new
    {
        x = group.Key,
        y = group.Count()
     });

// loop through points adding them to the chart
foreach (var p in points)
{    
    // Assume this is correct for your chart object
    chart3.Series.Add(p.x);
    chart3.Series[p.x].Points.AddY(p.y);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM