5

我有这个代码:

private void timer_Tick(object sender, EventArgs e)
    {
        timer.Stop();
        for (int i = 0; i < TOTAL_SENSORS; i++)
        {
            DateTime d = DateTime.Now;
            devices[i].Value = float.Parse(serialPort.ReadLine());
            if (chart1.Series[i].Points.Count > MAX_POINTS)
            {
                //see the most recent points
            }
            chart1.Series[i].Points.AddXY(d, devices[i].Value);
        }
        timer.Start();
    }

我的这部分代码是计时器的滴答事件,我在其中绘制图表,我需要在每个滴答时更新它。我不断添加点,当点数达到 MAX_POINTS(10) 时,它会删除第一个点在结尾。

问题是当它达到 MAX_POINTS 时,它开始在末尾删除点并且图形不会自动滚动。所有点都被删除,没有新点被添加。

请帮助我并说出我需要改变图表以按照我所说的方式工作。

编辑 1:我正在使用 Windows 窗体。

编辑 2: AddXY 和 RemoveAt 不是我的,它们来自积分集合。

编辑3:我也想知道如何拥有一个“范围”并查看最后一小时或上周或上个月的数据。

编辑 4:我稍微改变了我的问题,我现在想缩放图表以显示最后一小时/天的点

4

2 回答 2

9

将这些点存储在单独的字典和图表中。然后,您可以在需要最新点时查询字典。

Dictionary<DateTime, float> points = new Dictionary<DateTime, float>();

然后在您致电后直接添加此行AddXY()

points.Add(d, devices[i].Value);

如果要使字典与图表保持同步,请同时从字典中删除第一个元素:

points.Remove(points.Keys[0]);

要查询字典,可以使用 linq: Take() Documentation Skip() Documentation

IEnumerable<KeyValuePair<DateTime, float>> mostRecent = points.Skip(points.Count - 10).Take(10);

或者你可以得到一个特定的点(假设你想要一分钟前的点)

float value = points[DateTime.Now.AddMinutes(-1)];

或者您可以遍历这些项目:

foreach(KeyValuePair<DateTime, float> point in points)
{
    DateTime time = point.Key;
    float value = point.Value;
}
于 2011-08-19T16:49:45.390 回答
5

你需要把这个:

chart1.ResetAutoValues();

调整 X 和 Y 轴刻度

于 2012-09-12T11:34:49.573 回答