1
votes

I'm attempting use the C# Chart object to build a chart of data points. For each data point in an array, I would like to plot the point on the chart and have the bars "grow" as the points are added. So when I generate 1000 random numbers, I want to set 1,000 points on the chart all starting at zero with their values increasing by one each time. In attempting to do this, I have noticed that the chart just builds all at one time instead of adding each point and "growing" the bars. Any suggestion on how to make the bars animate? I know the chart is an image, so I don't mind if it is redrawn each time, but I can't even quite figure out a way to do that.

Here is an example of my code:

for (int i = 1; i <= numberOfRolls; i++)
{
    int number = randomNumber();
    myNumberDictionary[number] += 1;

    foreach (var point in MyChart.Series["MySeries"].Points)
    {
        point.SetValueXY(Convert.ToInt32(point.XValue), myNumberDictionary[Convert.ToInt32(point.XValue)]);
    }
}

Any suggestions?

1
For each data point added to the chart, I would like to add the point to the chart - that sentence makes no sense. - Tarec
Cannot edit: every iteration you're taking random element of myNumberArray (whatever it does) and increase its value by 1. Then in internal foreach loop your setting every point's Y position to the proper rolls list element. What do those do? - Tarec
Sorry. Fixed it. Essentially I want to plot the points each time and render a new chart every time a point is plotted. - Frank Johnson
But whad does your code mean? point.SetValueXY is pointless, because in every iteration of for loop it does exactly the same. And myNumberDictionary[number] += 1 increases by 1 some RANDOM myNumberDictionary element. What are those 2 collections holding? - Tarec
Did you try using Refresh() method of a Chart object? However in winforms bitmap-based animation are never a good idea. - Tarec

1 Answers

0
votes

If you execute your task on the UI thread the drawing will wait until your task finishes. To refresh your chart (UI) when adding a new point, you to need to do it in a separate thread.

Here is an example of how to achieve it.

for (int i = 1; i <= numberOfRolls; i++)
{
    int number = randomNumber();
    myNumberDictionary[number] += 1;

    foreach (var point in MyChart.Series["MySeries"].Points)
    {
            var startNew = Task.Factory.StartNew(() =>
             {
                 Invoke(new Action(() =>
                   point.SetValueXY(Convert.ToInt32(point.XValue),
                   myNumberDictionary[Convert.ToInt32(point.XValue)]);
             });
    }
}