2017-02-07 182 views
0

我正在使用最新版本的CorePlot创建基于this website的教程的折线图。不过,我很困惑我如何根据数组实际设置数据源。本质上,散点图需要绘制数组中所有值的图形,其中y轴是数组中每个元素的值,而x轴是数组中每个元素的索引。我怎样才能做到这一点?如何设置数据源?

.m文件:

- (void)viewDidLoad 
{ 
[super viewDidLoad]; 

CPTGraphHostingView* hostView = [[CPTGraphHostingView alloc] initWithFrame:self.view.frame]; 
[self.view addSubview: hostView]; 

CPTGraph* graph = [[CPTXYGraph alloc] initWithFrame:hostView.bounds]; 
hostView.hostedGraph = graph; 

CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *) graph.defaultPlotSpace; 

[plotSpace setYRange: [CPTPlotRange plotRangeWithLocation:@0 length:@16]]; 
[plotSpace setXRange: [CPTPlotRange plotRangeWithLocation:@-4 length:@8]]; 

CPTScatterPlot* plot = [[CPTScatterPlot alloc] initWithFrame:CGRectZero]; 

plot.dataSource = self; 

[graph addPlot:plot toPlotSpace:graph.defaultPlotSpace]; 
} 

- (NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plotnumberOfRecords 
{ 
return 9; 
} 

- (NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index 
{ 
int x = index - 4; 

if(fieldEnum == CPTScatterPlotFieldX) 
{ 
    return [NSNumber numberWithInt: x]; 
} 

else 
{ 
    return [NSNumber numberWithInt: x * x]; 
} 
} 

@end 

.h文件中:

@interface FirstViewController : UIViewController 

@end 

@interface CorePlotExampleViewController : UIViewController <CPTScatterPlotDataSource> 

@end 

回答

1

你没有表现出其中包含数据的阵列设置,但假设它是NSNumberNSArray,你只需要在您的numberForPlot方法中返回正确的x和y值,如下所示:

if (fieldEnum == CPTScatterPlotFieldX) 
{ 
    // x values go from -4 to 4 (based on how you set up your plot space Xrange) 
    return [NSNumber numberWithInt:(index - 4)]; 
} 
else 
{ 
    // y value is the contents of the array at the given index 
    return [dataArray objectAtIndex:index]; 
} 
相关问题