图表为数组中的每个值添加时间

时间:2018-02-15 18:03:33

标签: c# winforms graph mschart

我得到一个int数组from a file

示例:

0: 56
1: 57
2: 58
3: 59
4: 60
5: 61
6: 62
7: 63

我使用Linq从它获取了所有数据,现在我有了一个INT-Array

如何告诉图表每个值与最后一个值相差15分钟,以便正确绘制?

X系列已经设置为“时间”

我如何阅读文件中的数据:

int[] data = File
              .ReadLines(file)
              .Select(line => line.Substring(line.IndexOf(':') + 1))
              .Where(line => !string.IsNullOrWhiteSpace(line))
              .Select(line => int.Parse(line))
              .ToArray();

              chart1.DataSource = data;

1 个答案:

答案 0 :(得分:0)

  • 第1步:确保x值实际上是有效且正确的时间。

  • 步骤2格式化轴以显示正确的间隔。

使用直接数据点添加的示例:

DateTime start = DateTime.Now;
chart.Series[0].XValueType = ChartValueType.DateTime;

//loop over x..:
  chart.Series[0].Points.AddXY(start.AddMinutes(x * 15, start), yValue);

您可以使用相同的函数将您拥有的整数转换为数据源中15分钟时间步长。

要进行格式化,您可以使用以下代码:

Axis ax = chart.ChartAreas[0].AxisX;

ax.LabelStyle.Format = "HH:mm";
ax.IntervalType = DateTimeIntervalType.Minutes;
ax.Interval = 15;

enter image description here

<强>更新

答案显示了如何将数据转换为合适的格式以及如何格式化图表。它忽略了你获取数据的方式。

你完全扔掉了第一部分线条。您也永远不会显示数据绑定的完整代码。

这是第一个读取数据的两个部分的Linq代码:

var data = File.ReadLines(file)
    .Where(line => !string.IsNullOrWhiteSpace(line))
    .Select( line => line.Split(':') )
    .Select( parts => new { x = int.Parse(parts[0]), y = int.Parse(parts[1]) } )
    .ToArray();

但是x值仍然只是整数。以下代码将其转换为DateTimes,每个int计算15分钟的间隔:

DateTime start = DateTime.Now;

var chartData = File.ReadLines(file)
    .Where(line => !string.IsNullOrWhiteSpace(line))
    .Select( line => line.Split(':') )
    .Select( parts => new { x = start.AddMinutes(int.Parse(parts[0]) * 15), y = int.Parse(parts[1]) } )
    .ToArray();

您可以将它们绑定到图表,如下所示:

s.XValueMember = "x";
s.YValueMembers = "y";
chart.DataSource = chartData;

请注意,您需要使用400+点放大图表才能看到15分钟的间隔..