首页 > 解决方案 > 将月份放在 MajorGrid 上,将天数放在 MinorGrid 上(范围条形图)

问题描述

我有这个甘特图:

图表图像

我想在 MajorGrid 上显示月份和在 MinorGrid 上显示天数,我尝试更改间隔但没有任何改变

编辑:我想要的是这样的:

标签: c#charts

解决方案


您可以像这样添加两行自定义标签:

ay.LabelStyle.Angle = 0;
ay.IsLabelAutoFit = true;
DateTime d1 = DateTime.FromOADate(ay.Minimum);
DateTime d2 = DateTime.FromOADate(ay.Maximum);
int dc = (int)(d2 - d1).TotalDays;
//double dspace = d2.ToOADate() - d1.ToOADate();  // we need a suitable number later (*)
dspace = 10;    // seems to work better when zooming in..
for (int i = 0; i < dc; i++)
{
    DateTime dt = d1.AddDays(i);
    double dd = dt.ToOADate();
    CustomLabel cl = new CustomLabel();
    cl.Text = dt.Day + "";
    cl.FromPosition = dd - dspace;  //(*)
    cl.ToPosition = dd + dspace;   //(*)
    cl.RowIndex = 0;              // 1st row of labels

    ay.CustomLabels.Add(cl);

    if (dt.Day == 1)  // place month name at the 1st day
    {
        cl = new CustomLabel();
        string month = d1.AddDays(i).ToString("MMMM");
        cl.Text = month;
        cl.FromPosition = dd - dspace;  //(*)
        cl.ToPosition = dd + dspace;   //(*)
        cl.RowIndex = 1;              // 2nd row
        ay.CustomLabels.Add(cl);
    }
}

哪里Axis ay = ca.AxisY;var ca = chart1.ChartAreas[0];

结果:

在此处输入图像描述

黄色矩形是在 PrePaint 事件中绘制的。例子:

private void chart1_PrePaint(object sender, ChartPaintEventArgs e)
{
    Series s = chart1.Series[0];
    if (s.Points.Count <= 0) return;
    Graphics g = e.ChartGraphics.Graphics;

    var ca = chart1.ChartAreas[0];
    Axis ay = ca.AxisY;
    DateTime d1 = DateTime.FromOADate(ay.Minimum);
    DateTime d2 = DateTime.FromOADate(ay.Maximum);

    int x1 = (int)ay.ValueToPixelPosition(ay.Minimum);
    int x2 = (int)ay.ValueToPixelPosition(ay.Maximum);
    int y = (int)ca.AxisX.ValueToPixelPosition(ca.AxisX.Minimum);
    using (SolidBrush b = new SolidBrush(Color.FromArgb(11, 222, 222, 111)))
        g.FillRectangle(b, x1, y, x2 - x1, 60);  // 60 pixels large, calculate what you need!
}

我不得不承认我不知所措。也许一个(更多)涉及的油漆代码会接近你的例子..


推荐阅读