核心图:X轴标签在第一次绘制图形时不会出现

时间:2013-08-22 07:59:11

标签: iphone ios core-plot

我试图使用Core Plot在iPhone App中绘制一些图表。以下是App中的一个这样的图表:

enter image description here

如您所见,X轴标签只显示1,2,3 ...标签,而我已配置相应的日期显示在其中。此图表每隔几分钟重新绘制一次。当它重新绘制时,它会正确显示x轴标签(即日期值),如下所示:

enter image description here

而第一次,它只显示1,2,3 ....

如何设置X轴标签?

我在'numberOfRecordsForPlot'中进行,而不是在为图表设置所有其他参数(如颜色,填充等)时。这是因为我只有在为图表设置颜色等后才能获得绘图的值,&所以在numberOfRecordsForPlot()中,我计算两个轴的轴范围(取决于每隔几分钟得到的值),并计算自定义刻度位置& x轴标签&把它放在那里。这是代码片段:

-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot {
...
...

NSArray *customTickLocations = [NSArray arrayWithObjects :
                                [NSDecimalNumber numberWithInt:0],
                                [NSDecimalNumber numberWithInt:1],
                                [NSDecimalNumber numberWithInt:2],
                                [NSDecimalNumber numberWithInt:3],
                                [NSDecimalNumber numberWithInt:4],
                                nil];
// assume that we are plotting 5 points at a time
NSMutableArray *xAxisLabels = [[NSMutableArray alloc] init];
for (int i=0; i<self.arrayKeys.count ; i++) {

    NSString *myData = [dict objectForKey:[self.arrayKeys objectAtIndex:i]];
    if ((myData == nil) || (myData == NULL)) {
        NSLog(@"WARN : Invalid data");
        continue;
    }
    NSDate *date = (NSDate *) [self.arrayKeys objectAtIndex:i];
    [xAxisLabels addObject:date];
}
NSUInteger labelLocation = 0;
NSMutableArray *customLabels = [NSMutableArray arrayWithCapacity:xAxisLabels.count];
CPTMutableTextStyle *textStyle = [[CPTMutableTextStyle alloc] init];
textStyle.fontSize = 10.0;
textStyle.color = [CPTColor darkGrayColor];
for (int i=0 ; i<dictHealth.count ; i++) {
    NSNumber *tickLocation = [customTickLocations objectAtIndex:i];
    NSDateComponents *dateComponents = [self getComponentFromDate:
                                        (NSDate *)[xAxisLabels objectAtIndex:labelLocation++]];
    CPTAxisLabel *newLabel = [[CPTAxisLabel alloc]
                              initWithText:[NSString stringWithFormat:@"%d-%d-%d\n%d:%d:%d",
                                            dateComponents.year, dateComponents.month, dateComponents.day,
                                            dateComponents.hour, dateComponents.minute, dateComponents.second]
                              textStyle:textStyle];
    newLabel.tickLocation = [tickLocation decimalValue];
    newLabel.offset = 7.5;
    newLabel.rotation = M_PI/3;
    [customLabels addObject:newLabel];
}
axisSet.xAxis.axisLabels =  [NSSet setWithArray:customLabels];

...
...
}

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

不要在数据源中进行大量计算或图形配置。在数据加载周期中,可以多次调用-numberOfRecordsForPlot:。在查询数据的数据源时,它应该已经知道有多少数据可用。计算数据计数应该像读取实例变量或检索集合的count一样简单。

设置轴通常是视图控制器的功能。如果您需要在接收新数据时调整绘图空间范围并创建新的轴标签,请在控制器中进行。

绘图数据与其显示方式无关。如果在获得任何数据之前绘制图形,请在创建时为绘图范围和轴标签指定一些合理的默认值。在您要绘制数据之前,让-numberOfRecordsForPlot:返回零(0)。当您收到要显示的数据时,让控制器更新绘图范围和轴,并告诉绘图它使用-reloadData-insertDataAtIndex:numberOfRecords:显示新数据。