Core Plot for iOS - Data labels on Bar plot are displayed twice

1k Views Asked by At

I'm fairly new to CorePlot library. In one of our app we're drawing chart's bar graphs using CorePlot. We also display data labels for each of the Bar graph in the chart. I'm using labelOffset to set its position within the bar graph (i.e. labelOffset= -10.0) However, when one of the bar graph in the chart is too small to house the data label within the bar, then I'm setting labelOffset = 10.0, so that it can appear above the bar as default.

But, I'm seeing this weird behaviour with the CPTPlot, wherein its drawing the data label twice on the bar graph. Here is a screenshot:

enter image description here

Here is a code snipet:

    -(CPTTextLayer *)dataLabelForPlot:(CPTPlot *)plot recordIndex:(NSUInteger)index
    {
    plot.labelFormatter = nil;
    plot. labelTextStyle = nil;
    if (self.showValuesAsPlotLabels)
    {
if (self.showValuesAsPlotLabels)
{
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];

    [numberFormatter setGeneratesDecimalNumbers:NO];
    [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
    [numberFormatter setMaximumFractionDigits:2];
    [numberFormatter setMinimumFractionDigits:2];

    CGFloat yValue = [self.chartData[index][1] floatValue];
    //return [NSString stringWithFormat:@"%f", yValue];
    NSString *labelStr = [numberFormatter stringFromNumber:@(yValue)];
    /* Check to see how tall is bar chart so that we can accordingly position data label */
    CGFloat yBaseOffsetValue = self.yAxisIntervalLength;
    CGFloat compareValue = (yBaseOffsetValue * self.divisor);
    UIColor *dataLabelColor;
    float dataLabelOffset = -10.0f;
    if (yValue > compareValue) {
        dataLabelColor = [UIColor whiteColor];
        plot.labelOffset = dataLabelOffset;
    } else {
        dataLabelColor = [UIColor blackColor];
        plot.labelOffset = (0.0f - dataLabelOffset);
    }
       return [[CPTTextLayer alloc] initWithText:labelStr style:[CPTTextStyle textStyleWithAttributes:@{NSForegroundColorAttributeName: dataLabelColor}]];
  }

  if (self.plotLabels == nil || self.plotLabels.count < index)
  {
       return nil;
  }

   NSString *identifier = (self.plotLabels)[index];

   CPTTextLayer *label = [[CPTTextLayer alloc] initWithText:identifier];

   return label;
}

what am I missing or doing wrong here?

Thanks in adavance.

EDIT After Eric's suggestion, I've tried using plot.identifier to check for plot specific yValues and then return labelOffset and textStyle of dataLabel accordingly. However, I see the following behaviour on the bar plot now: enter image description here

I'm thinking that, dataLabelForPlot:recordIndex: is sort of using the same instance of CPTTextLayer? Is there a way that I can have separate instances of CPTTextLayer for each different CPTBarPlot?


Thanks

0

There are 0 best solutions below