图表中一个轴上的不同标签类型 [英] Different label types on one axis in chart

查看:146
本文介绍了图表中一个轴上的不同标签类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用程序中使用 System.Windows.Forms.DataVisualization.Charting ,我想在我的X轴上添加不同的标签类型,代表时间轴。例如,我想对标签使用HH:mm格式,但是当 00:00 时喜欢显示dd.MM格式。我尝试添加cutom标签,但它根本没有效果。

I'm using System.Windows.Forms.DataVisualization.Charting in my app and I want to add different label types on my X axis which is representing a timeline. For example, I want to use "HH:mm" format for labels but when it's 00:00 I'd like to show "dd.MM" format instead. I tried to add cutom labels but it has no effect at all.

var area = new ChartArea();
area.AxisX.LabelStyle.Format = "HH:mm";
area.AxisX.Interval = 1 / 24.0;
area.AxisX.CustomLabels.Add(1.0, DateTimeIntervalType.Days, "dd.MM");


推荐答案

添加 CustomLabels 帮助;但是如果您希望它们显示单独的格式,则必须将它们单独添加到每个 DataPoint

Adding CustomLabels will help; however if you want them to show an individual format you will have to add them individually to each DataPoint!

这样做并不像人们所希望的那么简单;有几个重载,但没有一个真的很容易使用。最简单的方法是imo,使用一个 FromPosition ToPosition ;然后应以之间 DataPoints 的方式进行设置;

Doing so is not quite as simple as one could wish for; there are several overloads but none is really easy to use. The simplest way, imo, is to use one with a FromPosition and a ToPosition; these should then to be set in a way that they hit right between the DataPoints; this way they will be centered nicely..

请注意,由于X值真的 DateTimes ,总是在图表中,转换为 doubles ,我们需要将它们转换回 DateTime 以获得正确的格式, 。

Note that as the X-Values are really DateTimes, but as always in a chart, converted to doubles we need to convert them back to DateTime for correct formatting and also use their values to calculate the middle or rather half an interval..

这里是一个例子:

// prepare the test chart..
chart1.ChartAreas.Clear();
ChartArea CA = chart1.ChartAreas.Add("CA1");
Random R = new Random(123);
chart1.Series.Clear();
CA.AxisX.MajorTickMark.Interval = 1;
Series S = chart1.Series.Add("S1");
S.Points.Clear();
S.ChartType = SeriesChartType.Column;
S.SetCustomProperty("PixelPointWidth", "10");
// some random data:
DateTime dt0 = new DateTime(2015, 05, 01);
for (int i = 0; i< 40; i++)
{
    int p = S.Points.AddXY(dt0.AddHours(i), R.Next(100));
}


// each custom label will be placed centered in a range
// so we need an amount of half an interval..
// this assumes equal spacing..
double ih = (S.Points[0].XValue - S.Points[1].XValue) / 2d;

// now we add a custom label to each data point
for (int i = 0; i < S.Points.Count; i++)
{
    DataPoint pt = S.Points[i];
    string s = (DateTime.FromOADate(pt.XValue)).ToString("HH:mm");
    bool midnite = s == "00:00";

    if (midnite) s = DateTime.FromOADate(pt.XValue).ToString("dd.MM.yyyy");
    CustomLabel CL = CA.AxisX.CustomLabels.Add(pt.XValue - ih, pt.XValue + ih, s);
    CL.ForeColor = midnite ? Color.Blue : Color.Black;
}

这篇关于图表中一个轴上的不同标签类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆