How do I create a chart in Visual Studio Windows Form whose minimum and maximum values are not numbers but strings?

前端 未结 1 1444
孤独总比滥情好
孤独总比滥情好 2021-01-17 06:06

I am trying to create charts in Visual Studio 2015 Windows Forms Application that will chart the data from a sensor and display each point with the time it was received in t

相关标签:
1条回答
  • 2021-01-17 06:52

    You should never use strings for x-values, unless they are actually meaningless, like city or person names.

    Strings are copied to the axis-labels but otherwise converted to doubles coming out as 0s (!!); this means you can't use them for anything.

    But you may want to use them for:

    • formatting (you need that)
    • setting display ranges (you want that, too)
    • setting zoom ranges
    • tooltips
    • calculations
    • expressions
    • etc..

    So you should add them either as numbers or as DateTimes. Here is an example and the result:

    Series s = chart.Series[0];
    // string[] vec = new string[7] 
    // { "11:00", "12:00", "1:00", "2:00", "3:00", "4:00", "5:00" };
    TimeSpan[] tvec = new TimeSpan[7] 
              { new TimeSpan( 11, 0, 0), new TimeSpan( 12, 0, 0), new TimeSpan( 13, 0, 0),
                new TimeSpan( 14, 0, 0) ,new TimeSpan( 15, 0, 0) ,new TimeSpan( 16, 0, 0),
                new TimeSpan( 17, 0, 0)  };
    
    DateTime d0 = new DateTime(0);
    
    foreach (var t in tvec)
        s.Points.AddXY(d0.Add(t), t.Hours);
    
    ChartArea ca = chart.ChartAreas[0];
    s.XValueType = ChartValueType.DateTime;
    ca.AxisX.LabelStyle.Format = "h:mm";
    
    ca.AxisX.Minimum = d0.Add(tvec.First()).ToOADate();
    ca.AxisX.Maximum = d0.Add(tvec.Last()).ToOADate();
    

    A few further notes:

    • Do take note of the special conversion function ToOADate and the complementary FromOADate!
    • To create the TimeSpans we need to use the 24h format.
    • You can display the times as in the 24h format by using the "H:mm" format string.
    • I would use a List<Tmespan> and fill it in a loop or even with LINQ:

     List<TimeSpan> tvec = Enumerable.Range(11, 7).Select(x => new TimeSpan(x, 0, 0)).ToList();
    
    0 讨论(0)
提交回复
热议问题