4

我正在使用 Core Plot条形图来绘制公司增长率。我希望将公司的股票代码作为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];

标签位置不正确的条形图

请注意,我的条形图索引以1开头:

-(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

}

4

1 回答 1

5
  1. 您应该养成在数据源中为正确的绘图类型使用字段标识符的习惯。对于条形图,您应该使用CPTBarPlotFieldBarLocationand CPTBarPlotFieldBarTip。在这种情况下没有区别,但对于其他情节类型并不总是如此。例如,水平条形图的 x 和 y 坐标是相反的。

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

  3. x 轴的绘图范围介于 0 和 4 之间。标签位于 0.5、1.5 和 2.5 处。这plotRange就是弄乱条形间距的原因。将其设置为默认值nil,您应该获得所需的外观。从plotRange 文档

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

于 2012-10-07T20:11:49.250 回答