如何设置数据源?

时间:2022-03-08 11:44:12

I'm using the latest version of CorePlot to create a line graph based on a tutorial from this website. However, I'm confused as to how I can actually set a data source based on an array. Essentially, the scatter plot needs to graph all of the values in the array with y-axis being the value of each element in the array, and the x-axis being the index of each element in the array. How can I accomplish this?

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

.m file:

.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 file:

.h文件:

@interface FirstViewController : UIViewController

@end

@interface CorePlotExampleViewController : UIViewController  <CPTScatterPlotDataSource>

@end

1 个解决方案

#1


1  

You didn't show where the array containing your data is set up, but assuming it's an NSArray of NSNumber, you just need to return the correct x and y values in your numberForPlot method like this:

您没有显示包含数据的数组的位置,但假设它是NSNumber的NSArray,您只需要在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];
}

#1


1  

You didn't show where the array containing your data is set up, but assuming it's an NSArray of NSNumber, you just need to return the correct x and y values in your numberForPlot method like this:

您没有显示包含数据的数组的位置,但假设它是NSNumber的NSArray,您只需要在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];
}