Visual bug when inputting numbers too high into a Windows Form app line graph

Viewed 73

I am using C# to try to input numbers into a line graph from a text file. The numbers in the text file are big, as in -30000. Every time I input a large number into the graph, I get a visual glitch that turns the graph black. Am I doing something wrong or is it a bug?

Picture of graph when inputting large numbers

void ChartLoad()
{
    var chart = LineGraph.ChartAreas[0];

    chart.AxisX.IntervalType = 
    System.Windows.Forms.DataVisualization.Charting.DateTimeIntervalType.Number;

    chart.AxisX.LabelStyle.Format = "";
    chart.AxisY.LabelStyle.Format = "";
    chart.AxisX.LabelStyle.IsEndLabelVisible = true;

    chart.AxisX.Interval = 0.5;
    chart.AxisY.Interval = 10;

    LineGraph.Series[0].IsVisibleInLegend = false;

    LineGraph.Series.Add("Line1");
    LineGraph.Series["Line1"].ChartType = 
    System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
    LineGraph.Series["Line1"].Color = Color.Green;

    LineGraph.Series.Add("Line2");
    LineGraph.Series["Line2"].ChartType = 
    System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
    LineGraph.Series["Line2"].Color = Color.Blue;

    LineGraph.Series["Line1"].Points.AddXY(30000, 30000);
    LineGraph.Series["Line1"].Points.AddXY(-30000, -30000);
}
1 Answers

The problem is the grid. You have an amazingly small intervall compared to the range of your values. The grid is so tight that it webbes a narrow carpet of gridlines onto your chart.

You could solve it by

  1. switching of the grid:

     chart.AxisX.MinorGrid.Enabled = false;
     chart.AxisX.MajorGrid.Enabled = false;
     chart.AxisY.MajorGrid.Enabled = false;
     chart.AxisY.MinorGrid.Enabled = false;
    
  2. Or by adjusting the axes intervalls to a reasonable number depending on the range of your values. You will see immidiately a difference when you set the interval to:

     chart.AxisX.Interval = 10000;
     chart.AxisY.Interval = 10000;
    

Here is a method that could do this for you:

private void AddValuesAndAdjustInterval(string series, double xValue, double yValue)
{
    LineGraph.Series[series].Points.AddXY(xValue, yValue);

    var chart = LineGraph.ChartAreas[0];

    double maxValueX = LineGraph.Series[series].Points.Select(x=> x.XValue).Max();
    double minValueX = LineGraph.Series[series].Points.Select(x=> x.XValue).Min();
    double maxValueY = LineGraph.Series[series].Points.SelectMany(x=> x.YValues).Max();
    double minValueY = LineGraph.Series[series].Points.SelectMany(x => x.YValues).Min();
    
    int stepSize = 20; // the smaller this value the larger the grid separation

    chart.AxisX.Interval = (maxValueX - minValueX) / stepSize;
    chart.AxisY.Interval = (maxValueY - minValueY) / stepSize;
}

Now you can use it to add values:

AddValuesAndAdjustInterval("Line1", 30000, 30000);
AddValuesAndAdjustInterval("Line1", -30000, -30000);
Related