如何为Core Plot图表的坐标轴提供标签?

17
我正在使用Core Plot框架,并尝试通过示例应用程序进行工作。有没有关于使用这个框架的教程?
具体来说,在图表中如何为X轴和Y轴提供标签?
2个回答

34

很不幸,由于该框架的API尚未稳定,因此没有太多教程可供使用,而存在的一些教程已经过时。实际示例应用程序确实是学习如何使用该框架的最佳来源。

例如,要提供自定义轴标签,请查看CPTestApp-iPhone的 CPTestAppBarChartController.m 源文件。该示例中的条形图具有以下代码定义的自定义X轴标签:

// Define some custom labels for the data elements
x.labelRotation = M_PI/4;
x.labelingPolicy = CPAxisLabelingPolicyNone;
NSArray *customTickLocations = [NSArray arrayWithObjects:[NSDecimalNumber numberWithInt:1], [NSDecimalNumber numberWithInt:5], [NSDecimalNumber numberWithInt:10], [NSDecimalNumber numberWithInt:15], nil];
NSArray *xAxisLabels = [NSArray arrayWithObjects:@"Label A", @"Label B", @"Label C", @"Label D", @"Label E", nil];
NSUInteger labelLocation = 0;
NSMutableArray *customLabels = [NSMutableArray arrayWithCapacity:[xAxisLabels count]];
for (NSNumber *tickLocation in customTickLocations) {
    CPAxisLabel *newLabel = [[CPAxisLabel alloc] initWithText: [xAxisLabels objectAtIndex:labelLocation++] textStyle:x.labelTextStyle];
    newLabel.tickLocation = [tickLocation decimalValue];
    newLabel.offset = x.labelOffset + x.majorTickLength;
    newLabel.rotation = M_PI/4;
    [customLabels addObject:newLabel];
    [newLabel release];
}

x.axisLabels =  [NSSet setWithArray:customLabels];

首先,您将轴标签策略设置为CPAxisLabelingPolicyNone,让框架知道您将提供自定义标签,然后创建一个带有相应位置的标签数组,最后将该标签数组分配给X轴上的axisLabels属性。


customTickLocations 包含 5、10... 这些值,与 x 轴范围有关。如果我的 x 轴包含以秒为单位的值,那么在我的情况下 customTickLocations 中应该是什么值呢?谢谢。 - Pooja
1
@Pooja 自定义标签可以像答案中所述的那样添加到饼图中...不用谢。您可以按照此SO答案中提到的方式处理自定义刻度位置...不用谢! - tipycalFlow

1
为了提供定制化的标签,您可以将格式化器分配给轴的labelFormatter属性。您可以使用配置为您喜好的NSNumberFormatter,例如:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
// ... configure formatter

CPTXYAxis *y = axisSet.yAxis;
y.labelFormatter = formatter;

或者,如果您需要更具体的格式设置,您可以子类化NSNumberFormatter并覆盖stringForObjectValue:方法以进行所需的确切格式设置。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接