.NET图表控件:如何使用LineAnnotation?

时间:2013-10-25 12:06:20

标签: c# charts annotations line .net-4.5

我有一个包含一个系列的工作折线图。现在我想在其上绘制一个自定义行。我想在图表坐标(如系列中的数据点)中设置此行的起点和终点,而不是以像素为单位。据我所知,到目前为止,LineAnnotation可能会完成这项工作,但我无法弄清楚如何做到这一点,到现在为止它根本没有显示任何东西。

我也尝试了一个Horizo​​ntalLineAnnotation,这个效果很好并且显示了一条水平线,但这不是我需要的:

double lineHeight = -35;
HorizontalLineAnnotation ann = new HorizontalLineAnnotation();
ann.AxisX = tc.ChartAreas[0].AxisX;
ann.AxisY = tc.ChartAreas[0].AxisY;
ann.IsSizeAlwaysRelative = false;
ann.AnchorY = lineHeight;
ann.IsInfinitive = true;
ann.ClipToChartArea = tc.ChartAreas[0].Name;
ann.LineColor = Color.Red; ann.LineWidth = 3;
tc.Annotations.Add(ann);

这段代码给了我这个结果: enter image description here

我想要实现的目标就像这样(只是一个例子): enter image description here

我尝试了这段代码,但我看不出如何正确设置坐标:

double lineHeight = -30;
LineAnnotation ann = new LineAnnotation();
ann.AxisX = tc.ChartAreas[0].AxisX;
ann.AxisY = tc.ChartAreas[0].AxisY;
ann.IsSizeAlwaysRelative = true;
ann.AnchorY = lineHeight;
ann.ClipToChartArea = tc.ChartAreas[0].Name;
ann.LineColor = Color.Red; ann.LineWidth = 3;
ann.Width = 200;
ann.X = 2;
ann.Y = -40;
tc.Annotations.Add(ann);

此代码不显示任何内容。假设我想从(数据)坐标(2,-40)到(2.8,-32)绘制一条红线,如上图所示 - 我该如何实现呢?

提前致谢!

3 个答案:

答案 0 :(得分:2)

我相信上面的代码只需要分配给AnchorX的值。以下适用于我:

LineAnnotation annotation = new LineAnnotation();
annotation.IsSizeAlwaysRelative = false;
annotation.AxisX = chart1.ChartAreas[0].AxisX;
annotation.AxisY = chart1.ChartAreas[0].AxisY;
annotation.AnchorX = 5;
annotation.AnchorY = 100;
annotation.Height = 2.5;
annotation.Width = 3;
annotation.LineWidth = 2;
annotation.StartCap = LineAnchorCapStyle.None;
annotation.EndCap = LineAnchorCapStyle.None;
chart1.Annotations.Add(annotation);

答案 1 :(得分:1)

您应该使用AnchorDataPoint属性。例如:

ann.AnchorDataPoint = tc.Series[0].Points[0];

确保将AnchorX和AnchorY设置为NaN。

答案 2 :(得分:1)

我个人放弃了笨拙的图表控件中的行注释。 相反,我使用的技术是添加另一个Series来表示该行。 所以我只是做以下事情:

private void Line(Point start, Point end)
{
    chart1.Series.Add("line");
    chart1.Series["line"].ChartType = SeriesChartType.Line;
    chart1.Series["line"].Color = System.Drawing.Color.Red;
    chart1.Series["line"].Points.AddXY(start.X, start.Y);
    chart1.Series["line"].Points.AddXY(end.X, end.Y);
}

这很容易实现,即使在调整图表大小时也没有锚点问题。