2012-10-07 141 views
4

我正在使用核心图条形图绘制公司的增长率。我希望将公司的股票代码作为标签,以x轴为中心,位于的下方。不幸的是,我花了很多时间寻找一种方法来正确地将x标签居中,但是使用我的代码没有成功。我怎样才能让x轴标签正确居中?核心图:x轴上的自定义标签条形图

我的图表设置是如下:

CPTBarPlot *barPlot  = [CPTBarPlot tubularBarPlotWithColor:[CPTColor blueColor] horizontalBars:NO]; 

barPlot.baseValue  = CPTDecimalFromInt(0); 
barPlot.barOffset  = CPTDecimalFromFloat(0.5f); 
barPlot.barWidth  = CPTDecimalFromFloat(0.5f); 

double xAxisStart = 0; 
double xAxisLength = self.companies.count; 

double yAxisStart = 0; 
double yAxisLength = 0.5; 

CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)graph.defaultPlotSpace; 
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(xAxisStart) length:CPTDecimalFromDouble(xAxisLength + 1.0)] ; 
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(yAxisStart) length:CPTDecimalFromDouble(yAxisLength)] ; 

barPlot.plotRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(+0.0) length:CPTDecimalFromDouble(xAxisLength)] ; 

在下面的代码片段中,我试图用自定义标签,但没有成功。如下图示例图表。

xAxis.labelingPolicy = CPTAxisLabelingPolicyNone; 

NSMutableArray *customLabels = [[NSMutableArray alloc]init]; 

[self.companies enumerateObjectsUsingBlock:^(IBCompany *company, NSUInteger idx, BOOL *stop) { 
    NSString *labelText = company.contrSymbol; 
    CPTAxisLabel *label = [[CPTAxisLabel alloc] initWithText:labelText textStyle:xAxis.labelTextStyle]; 
    label.tickLocation = CPTDecimalFromDouble(idx + 0.5); 
    label.offset = xAxis.labelOffset + xAxis.majorTickLength; 
    label.rotation = M_PI * 2; 
    [customLabels addObject:label]; 
    }]; 
    xAxis.axisLabels = [NSSet setWithArray:customLabels]; 

barcharts with incorrect label positioning

请注意,我对条形图指数与开始:

-(NSArray *)numbersForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndexRange:(NSRange)indexRange 
    { 
    if ([plot.identifier isEqual:plotIdentifier]) {; 

    if (fieldEnum == CPTScatterPlotFieldX) { 
     NSMutableArray *indexArray = [[NSMutableArray alloc] init]; 

     [self.companies enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { 
      [indexArray addObject:[NSDecimalNumber numberWithInt: idx + 1]]; 
     }]; 
     return [indexArray copy]; 
    } 
    else if (fieldEnum == CPTScatterPlotFieldY) { 
     // .. 
    } 
} 
else return nil; // should be considered as ERROR 

}

回答

5
  1. 您应当使用习惯得到dat中右侧图的字段标识符来源。对于条形图,您应该使用CPTBarPlotFieldBarLocationCPTBarPlotFieldBarTip。在这种情况下,没有任何区别,但对于其他类型的地块并非总是如此。例如,水平条形图的x和y坐标是相反的。

  2. 数据源始终返回相同的数据集。您需要检查indexRange参数并且只返回请求的范围。

  3. x轴的绘图范围在0和4之间。标签为0.5,1.5和2.5。 plotRange是什么搞乱酒吧间距。将其设置为默认值nil,您应该看到您想要的外观。从plotRange docs

如果提供了一个绘图范围,该酒吧在整个绘图范围均匀分布的。如果plotRange为零,则条形位置由Cocoa绑定或条形图数据源提供。如果位置不是由绑定或数据源提供的,则第一个小节将放置在零(0)处,随后的小节将位于连续的正整数坐标处。