Control visual styles of individual gridlines

2019-07-30 11:24发布

问题:

I have a c# RangeBar chart with about 25 labels on the AxisX. Depending on my live data, some of these labels have visible data points in the chart. Typically about 3/4 of the 25 labels don't have any data points. All horizontal gridlines are enabled, which makes the chart a bit cluttered. Especially for data points that are further away on the AxisY, it's difficult to distinguish at a glance to what label on the AxisX they belong.

My idea is to differentiate the AxisX labels that have visible data points either by giving their gridline a different color, a different style, or to completely remove gridlines of AxisX labels that have no corresponding data points. Is this even possible? Because all controllable properties and documentation I have found so far is regarding gridline styles of the entire chart.

Btw: Only showing AxisX labels that have data points is not an option. Thanks in advance.

回答1:

To reduce clutter you could use the axis.Interval property.

But each line will still have the same style, either of major or of the minor lines.

You could add VerticalLineAnnotations for selected points or try StripLines. Both can be styled freely.

Here is an example of a normal line chart, with lines randomly added to a few points:

The same result can be achieved by either Annotations or Striplines. The blue lines are StripLine and the red ones Annotations. Here are two functions to add a colored line to a DataPoint:

void AddStripLine(Chart chart, ChartArea ca, DataPoint dp, Color col)
{
    Axis ax = ca.AxisX;
    StripLine sl = new StripLine();
    sl.BorderColor = col;
    sl.IntervalOffset = dp.XValue;
    sl.Interval = 0;
    sl.StripWidth  = 0;
    sl.BorderWidth  = 1;
    ax.StripLines.Add(sl);
}

If you look very closely you'll see that the only visual difference is that the former are below, the latter above all other chart elements.

void AddAnnotation(Chart chart, ChartArea ca, DataPoint dp, Color col)
{
    Axis ay = ca.AxisY;
    VerticalLineAnnotation vl = new VerticalLineAnnotation();
    vl.LineColor = col;
    vl.AnchorDataPoint = dp;
    vl.IsInfinitive = true;
    vl.LineWidth = 1;
    vl.Height = ay.Maximum - ay.Minimum;
    vl.ClipToChartArea = ca.Name;
    chart.Annotations.Add(vl);
}

For Bar charts use HorizontalLineAnnotations and anchor to the correct axis...

Using Annotatons is in fact the more natural way, since each is an individual object. StripLines are too, but are repeated at intervals . To avoid visible repetiton each needs to have suitable offsets and intervals to be determined for each. But it isn't hard to do either way.

Also note that the both types of lines lines are anchored to their DataPoints and will move with them e.g. when chart is resized..