Search code examples
c#winformsmschart

MSChart Winforms. How to remove blank points?


I use the MSChart control for creating candlestick chart (namespace System.Windows.Forms.DataVisualization.Charting). I added two points in friday and two points in monday. Total four points.

In result, I see four candlesticks and many blank points therebetween. How to remove it?

Thanks.

var area = chart1.ChartAreas.Add("area1");                
area.AxisX.LabelStyle.Format = "yyyy.MM.dd HH:mm";

var series = new Series("prices", 4);

series.ChartArea = "area1";
series.ChartType = SeriesChartType.Candlestick;
series.XValueType = ChartValueType.DateTime;
series["OpenCloseStyle"] = "Triangle";
series["ShowOpenClose"] = "Both";
series["PointWidth"] = "0.6";
series["PriceUpColor"] = "Green";
series["PriceDownColor"] = "Red";

series.Points.AddXY(new DateTime(2016, 4, 25, 12, 0, 0), 2, 0.5, 0.7, 1.8);
series.Points.AddXY(new DateTime(2016, 4, 25, 11, 0, 0), 2, 0.5, 0.7, 1.8);
series.Points.AddXY(new DateTime(2016, 4, 22, 12, 0, 0), 2, 0.5, 0.7, 1.8);
series.Points.AddXY(new DateTime(2016, 4, 22, 11, 0, 0), 2, 0.5, 0.7, 1.8);                

this.chart1.Series.Add(series);

enter image description here


Solution

  • This can be solved by telling the Chart, or rather the Series, that you want to use the X-Values as such (i.e. as numbers) but not for placing the DataPoints.

    Here is what you have to add:

      series.IsXValueIndexed = true;
    

    This means that you can still format them or use them in other ways like calculations but the placement is strictly lined up as if their values were indices 0,1,2... or as if you had added them as strings, leading to the x-values actually all be 0, as so many newbies do.

    Now your chart looks like this (here):

    enter image description here

    As has been noted the gap you saw was not caused by empty points. To create an Empty DataPoint you would do something like this:

    series.Points[2].IsEmpty = true;
    

    And tell the series how to treat them:

    series.EmptyPointStyle.Color = Color.Transparent;
    series.EmptyPointStyle.AxisLabel = " ";
    

    Note The DataPoints you added were not ordered by date. Therefore they now appear unordered. The best way to fix it is to order them before you add them.

    If you can't do that you can sort them like this:

    var sorted = series.Points.OrderBy(x => x.XValue).ToList();  // a sorted copy
    series.Points.Clear();
    foreach (DataPoint dp in sorted) series.Points.Add(dp);
    

    enter image description here

    Ordered with one Empty Point