I'm trying to plot a simple chart in a C# windows form application. The data to plot this chart will be fed run-time. Problem is it does not plot unique points on the chart with reference to the X-axis values. For example for two points (5,1) and (5,3), it shows the '5' value on the X axis twice.
I tried looking for solutions for similar questions, but none helped. Here's how my code looks: (I've purposefully moved the declarations inside the click event handler for easier reference)
private void button1_Click(object sender, EventArgs e)
{
Series series3 = new Series
{
Name = "Series3",
Color = System.Drawing.Color.Red,
IsVisibleInLegend = false,
IsXValueIndexed = true,
ChartType = SeriesChartType.Line
};
double startPosition = 2;
double endPosition = 4;
double startForceLow = 1;
double startForceHigh = 3;
double endForceLow = 5;
double endForceHigh = 7;
chart1.Series.Clear();
this.chart1.Series.Add(series3);
double[] xPoints = { startPosition, startPosition, endPosition, endPosition, startPosition };
double[] yPoints = { startForceLow, startForceHigh, endForceHigh, endForceLow, startForceLow };
//Adding individual points too does not work
//series3.Points.AddXY(startPosition, startForceLow);
//series3.Points.AddXY(startPosition, startForceHigh);
//series3.Points.AddXY(endPosition, endForceHigh);
//series3.Points.AddXY(endPosition, endForceLow);
//series3.Points.AddXY(startPosition, startForceLow);
chart1.Series["Series3"].XValueType = ChartValueType.Double;
chart1.Series["Series3"].YValueType = ChartValueType.Double;
chart1.Series["Series3"].Points.DataBindXY(xPoints, yPoints);
chart1.Invalidate();
}
The reason is that you have told the chart to ignore the X-Values
and use their indices for placing them instead:
IsXValueIndexed = true
Delete the line or set the property to its default false
!
Result:
See here on MSDN for the explanation:
True if the indices of data points that belong to the series will be used for X-values; false if they will not. The default value is false.
There are rare cases where this is useful, but yours is not one of them. In fact Line
charts hardly ever are; some charts however make good use of it..:
All data points in a series use sequential indices, and if this property is true then data points will be plotted sequentially, regardless of their associated X-values. This means that there will be no "missing" data points.
...
...
This is useful when you do not want to have missing data points for intervals that you know you will not have data for, such as weekends.Important
If you are displaying multiple series and at least one series uses indexed X-values, then all series must be aligned—that is, have the same number of data points—and the corresponding points must have the same X-values.