C# Chart alignment axis label

2019-02-28 10:04发布

问题:

I have some custom labels in column chart (a bit of my code):

        chart.ChartAreas[0].AxisX.IsMarginVisible = true;
        chart.ChartAreas[0].AxisX.LabelStyle.IsEndLabelVisible = true;
        chart.ChartAreas[0].AxisX.LineColor = Color.LightGray;
        chart.ChartAreas[0].AxisX.MajorGrid.LineColor = Color.LightGray;
        chart.ChartAreas[0].AxisX.LabelStyle.Angle = 0;
        chart.ChartAreas[0].AxisX.LabelStyle.Font = new Font("Trebuchet MS", 10);
        chart.ChartAreas[0].AxisX.MajorTickMark.LineColor = Color.LightGray;

        chart.ChartAreas[0].AxisX.Interval = 1;
        chart.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.Weeks;
        chart.ChartAreas[0].AxisX.IsLabelAutoFit = true;
        chart.ChartAreas[0].AxisX.LabelStyle.IsEndLabelVisible = false;


        DateTime minDate = DateTime.Parse(dt.Rows[0]["Date"].ToString());
        DateTime maxDate = DateTime.Parse(dt.Rows[dt.Rows.Count - 1]["Date"].ToString());

        for (int i = 0; i < dt.Rows.Count - 1; i++)
        {
            chart.ChartAreas[0].AxisX.CustomLabels.Add(new CustomLabel(minDate.ToOADate(),
                                                                       minDate.AddDays(6).ToOADate(),
                                                                       minDate.ToShortDateString() + "-" + minDate.AddDays(6).ToShortDateString(),
                                                                       0,
                                                                       LabelMarkStyle.None));
            minDate = minDate.AddDays(7);
        }

So since my custom lable text is so long minDate.ToShortDateString() + "-" + minDate.AddDays(6).ToShortDateString() it looks like

How can i moved to the left axis lables if i can?

回答1:

Besides shortening the content to avoid any redundancy you could try to trick the label formatter by adding a few blanks to the right, then a non-breaking space and then a \n.

Here is the result before and after:

I have used this code:

  A.AxisX.LabelStyle.Format = "MM.dd.yy";
  A.AxisX.LabelStyle.Format = "MM.dd.yy        " + ((char)160) + "\n";


标签: c# .net charts