Reputation: 629
I need to draw multiple plots in the same graph at different times. Please look at the image below:
Except that the number of plots would change dynamically. Sometimes I would only require only blue and orange datasets some times all four and some times only 3. I am able to manage for one bar plot like this.
CPTScatterPlot *plot = [[[CPTScatterPlot alloc] init] autorelease];
plot.dataSource = self;
plot.identifier = @"mainplot";
plot.dataLineStyle = lineStyle;
plot.plotSymbol = plotSymbol;
[self.graph addPlot:plot];
In my case I can put them in a for loop and do [self.graph addplot:plot]
in each iteration. But how do I manage the datasource. How do I manage the code below, if the number of datasets changes dynamically.
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index {
if ( [plot.identifier isEqual:@"mainplot"] )
{
NSValue *value = [self.graphData objectAtIndex:index];
CGPoint point = [value CGPointValue];
// FieldEnum determines if we return an X or Y value.
if ( fieldEnum == CPTScatterPlotFieldX )
{
return [NSNumber numberWithFloat:point.x];
}
else // Y-Axis
{
return [NSNumber numberWithFloat:point.y];
}
}
return [NSNumber numberWithFloat:0];
}
Upvotes: 4
Views: 2548
Reputation: 3437
I did it before and it worked! You can use an NSArray
for plots, and create some plot data and add them as objects into a NSDictionary
. for more detail you can see this sample:
NSDictionary *firstLineDic = [NSDictionary dictionaryWithObjectsAndKeys:@"firstLine", PLOT_IDENTIFIER, firstLineData, PLOT_DATA, nil];
NSDictionary *secondLineDic = [NSDictionary dictionaryWithObjectsAndKeys:@"secondLine", PLOT_IDENTIFIER, secondLineData, PLOT_DATA, nil];
NSArray *arrayData = [NSArray arrayWithObjects:firstLineDic, secondLineDic, nil];
scatterPlot = [[ScatterPlot alloc] initWithHostingView:plotView data:arrayData];
[scatterPlot initialisePlot];
Now in ScatterPlot
class write these functions:
-(id)initWithHostingView:(CPTGraphHostingView *)_hostingView data:(NSArray *)_data{
self = [super init];
if ( self != nil ) {
self.hostingView = _hostingView;
data = [[NSArray alloc] initWithArray:_data];
self.graph = nil;
}
return self;
}
-(void)initialisePlot
{
...
for (NSDictionary *dic in data) {
CPTScatterPlot *plot = [[[CPTScatterPlot alloc] init] autorelease];
plot.dataSource = self;
plot.identifier = [dic objectForKey:PLOT_IDENTIFIER];
plot.dataLineStyle = [lineStyles objectAtIndex:[dic objectForKey:PLOT_COLOR]];
plot.plotSymbol = plotSymbol;
[self.graph addPlot:plot];
}
...
}
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{
for (NSDictionary *dic in data) {
NSString *identity = [dic objectForKey:PLOT_IDENTIFIER];
if([plot.identifier isEqual:identity]){
NSArray *arr = [dic objectForKey:PLOT_DATA];
return [arr count];
}
}
return 0;
}
Upvotes: 2