我有这个代码:
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:我稍微改变了我的问题,我现在想缩放图表以显示过去一小时/一天的点数
最佳答案
将点存储在单独的字典和图表中。然后你可以在你想要最近的点时查询字典。
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;
}
关于c# - 如何查看每秒更新的图表中的最后 10 个数据点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7096098/