Add horizontal line to chart in C#

betelgeuse picture betelgeuse · Feb 24, 2014 · Viewed 20.5k times · Source

I am using a System.Windows.Forms.DataVisualization.Chart to plot some x,y scatter data, like this:

chart1.Series["Series2"].Points.AddXY(stringX, doubleY);
  1. I would like to add to that chart an horizontal line with an average of the form y = constant. How can I do this? Please, notice that the x axis is a string

  2. Actually, the x axis is the time (hh:mm:ss). I am converting it to string to plot it because if I use the DateTime format for the x axis (XValueType) of the chart it doesn't show the seconds. Can I correct that to show the seconds so I can plot directly x as DateTime and y as double?

Answer

Junaith picture Junaith · Feb 25, 2014

For point 2, you can still set the XValueType to DateTime but with proper format in 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";

For point 1, add a StripLine to the Y-Axis of the chartarea.

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);