在C#中向图表添加水平线

10

我正在使用 System.Windows.Forms.DataVisualization.Chart 绘制一些x,y散点数据,就像这样:

chart1.Series["Series2"].Points.AddXY(stringX, doubleY);
  1. 我想在那个图表上添加一条水平线,其形式为y = constant。 我该怎么做?请注意,x轴是一个字符串

  2. 实际上,x轴是时间(hh:mm:ss)。我将其转换为字符串以进行绘图,因为如果我使用图表的x轴(XValueType)的DateTime格式,则不会显示秒数。我能否更正这个问题以显示秒数,以便我可以直接用DateTime作为x和double作为y进行绘图?


您可以使用StripLine来实现相同的结果,请参考:https://dev59.com/fVjUa4cB1Zd3GeqPUMCX - Dayan
2个回答

20

对于第2点,您仍然可以将XValueType设置为DateTime,但需要在LabelStyle中使用适当的格式。

chart1.Series[SeriesName].XValueType = ChartValueType.DateTime;
// Use the required format. I used the below format as example.
chart1.ChartAreas[ChartName].AxisX.LabelStyle.Format = "dd/mm/yy hh:mm:ss";

对于第一点,需要在图表区域的Y轴上添加一个StripLine

StripLine stripline = new StripLine();
stripline.Interval = 0;
stripline.IntervalOffset = average value of the y axis; eg:35
stripline.StripWidth = 1;
stripline.BackColor = Color.Blue;
chart1.ChartAreas[ChartAreaName].AxisY.StripLines.Add(stripline);

chart1.ChartAreas[ChartName].AxisY.StripLines.Add(stripline); 中的 ChartName 是什么? - Silver
@Silver,实际上是ChartAreaName而不是ChartName...我已经更正了代码...感谢你指出。 - Junaith
默认的ChartAreaName名称为“ChartArea1”。 - Seabass77

0

我会添加另一个系列,其X值相同,但Y值为常数,代表平均值。

double avgY = {average of Y points}

在你的循环中:

chart1.Series["Series3"].Points.AddXY(stringX, avgY);

不会添加一条水平线,它会在指定位置添加一个峰值。 - Matthis Kohli

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接