CorePlot ScatterPlot labelingPolicy - ios

I am using CorePlot to plot average prices over few months.
This is what I am trying to achieve
I have been able to produce this
So clearly graph does not look plotted correctly.
Heres the code I am using in my viewController to set up the graph and plot it.
- (void)viewDidLoad {
[super viewDidLoad];
[[UIApplication sharedApplication] setStatusBarHidden:YES];
NSDictionary *jsonDataDictionary;
// Can be done async with loading timers
NSURL *url = [NSURL URLWithString:
#"http://greyloft.com/analytics/query.php?project=PARC%20VISTA&area=1200&months=5"];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if (urlData) {
NSError *error=nil;
jsonDataDictionary = [NSJSONSerialization JSONObjectWithData:urlData
options:kNilOptions
error:&error];
// We receive the order of the months in reverse order in the json i.e. most recent first.
// e.g. Feb-15, Jan-15, Dec-14 and so on
// We need to show plotting in reverse order on x axis effectively needing to reverse the array.
NSArray *reverseAvgRentals = [[jsonDataDictionary objectForKey:#"results"] objectForKey:#"average"];
_averageRentals = [[reverseAvgRentals reverseObjectEnumerator] allObjects];
_transactions = [[jsonDataDictionary objectForKey:#"results"] objectForKey:#"transactions"];
_months = [[NSMutableArray alloc] init];
_rentals = [[NSMutableArray alloc] init];
for (NSDictionary *rental in _averageRentals) {
[_months addObject:[rental objectForKey:#"month"]];
[_rentals addObject:[rental objectForKey:#"average"]];
}
// KVC to find min/max in an array
_minRental = _maxRental = 0;
_minRental = [[_rentals valueForKeyPath:#"#min.intValue"] intValue];
_maxRental = [[_rentals valueForKeyPath:#"#max.intValue"] intValue];
}}
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot {
return [_months count];
}
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index {
NSNumber *num = [[NSNumber alloc] init];
if (fieldEnum == CPTScatterPlotFieldX) {
// Simply return index as we want to return number for each month
num = [NSNumber numberWithInt:index+1];
} else {
num = [[_averageRentals objectAtIndex:index] valueForKey:#"average"];
}
return num;
}
-(void)initPlot {
[self configureHost];
[self configureGraph];
[self configurePlots];
[self configureAxes];
}
-(void)configureHost {
self.graphHostView = [(CPTGraphHostingView *) [CPTGraphHostingView alloc] initWithFrame:self.graphContainerView.bounds];
self.graphHostView.allowPinchScaling = YES;
[self.graphContainerView addSubview:self.graphHostView];
}
-(void)configureGraph {
// Create the graph
CPTGraph *graph = [[CPTXYGraph alloc] initWithFrame:self.graphHostView.bounds];
[graph applyTheme:nil];
self.graphHostView.hostedGraph = graph;
[graph.plotAreaFrame setPaddingLeft:30.0f];
[graph.plotAreaFrame setPaddingBottom:30.0f];
[graph.plotAreaFrame setPaddingTop:10.0f];
}
-(void)configurePlots {
// Get graph and plot space
CPTGraph *graph = self.graphHostView.hostedGraph;
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *) graph.defaultPlotSpace;
// 2 - Create the plot
CPTScatterPlot *rentPlot = [[CPTScatterPlot alloc] init];
rentPlot.dataSource = self;
rentPlot.identifier = #"Rent";
[graph addPlot:rentPlot toPlotSpace:plotSpace];
// 3 - Set up plot space
CGFloat xMin = 0.0f;
CGFloat xMax = [_months count];
CGFloat yMin = _minRental;
CGFloat yMax = _maxRental;
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(xMin)
length:CPTDecimalFromFloat(xMax)];
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(yMin)
length:CPTDecimalFromFloat(yMax)];
[plotSpace scaleToFitPlots:[graph allPlotSpaces]];
CPTMutablePlotRange *xRange = [plotSpace.xRange mutableCopy];
CPTMutablePlotRange *yRange = [plotSpace.yRange mutableCopy];
[xRange expandRangeByFactor:CPTDecimalFromDouble(1.4)];
[yRange expandRangeByFactor:CPTDecimalFromDouble(3.0)];
plotSpace.xRange = xRange;
plotSpace.yRange = yRange;
// 4 - Create styles and symbols
//CPTColor *orangeColor = [CPTColor colorWithComponentRed:239.0f green:92.0f blue:94.0f alpha:1.0f];
CPTColor *orangeColor = [CPTColor orangeColor];
CPTMutableLineStyle *lineStyle = [rentPlot.dataLineStyle mutableCopy];
lineStyle.lineWidth = 2.5f;
lineStyle.lineColor = orangeColor;
rentPlot.dataLineStyle = lineStyle;
CPTMutableLineStyle *symbolLineStyle = [CPTMutableLineStyle lineStyle];
symbolLineStyle.lineWidth = 2.5f;
symbolLineStyle.lineColor = orangeColor;
CPTPlotSymbol *symbol = [CPTPlotSymbol ellipsePlotSymbol];
symbol.fill = [CPTFill fillWithColor:[CPTColor colorWithComponentRed:248.0f
green:244.0f
blue:251.0f
alpha:1.0f]];
symbol.lineStyle = symbolLineStyle;
symbol.size = CGSizeMake(11.0f, 11.0f);
rentPlot.plotSymbol = symbol;
}
-(void)configureAxes {
// 1 - Create styles
CPTMutableLineStyle *axisLineStyle = [CPTMutableLineStyle lineStyle];
axisLineStyle.lineWidth = 0.0f;
CPTMutableTextStyle *axisTextStyle = [[CPTMutableTextStyle alloc] init];
axisTextStyle.color = [CPTColor grayColor];
axisTextStyle.fontName = #"Ubuntu-Bold";
axisTextStyle.fontSize = 14.0f;
CPTMutableLineStyle *majorGridLineStyle = [CPTMutableLineStyle lineStyle];
majorGridLineStyle.lineWidth = 0.75;
majorGridLineStyle.lineColor = [CPTColor lightGrayColor];
// 2 - Get axis set
CPTXYAxisSet *axisSet = (CPTXYAxisSet *) self.graphHostView.hostedGraph.axisSet;
// 3 - Configure x-axis
CPTXYAxis *x = axisSet.xAxis;
x.axisLineStyle = axisLineStyle;
x.labelingPolicy = CPTAxisLabelingPolicyNone;
x.majorIntervalLength = CPTDecimalFromDouble(1.0);
x.orthogonalCoordinateDecimal = CPTDecimalFromDouble(0.0);
x.preferredNumberOfMajorTicks = 6;
x.labelOffset = 50.0f;
x.labelTextStyle = axisTextStyle;
x.majorTickLineStyle = nil;
x.minorTickLineStyle = nil;
NSMutableSet *xLabelSet = [NSMutableSet setWithCapacity:[_months count]];
NSMutableSet *xLocationSet = [NSMutableSet setWithCapacity:[_months count]];
int location = 0;
for (NSString *month in _months) {
CPTAxisLabel *label = [[CPTAxisLabel alloc] initWithText:month textStyle:x.labelTextStyle];
label.tickLocation = CPTDecimalFromInt(location++);
[xLabelSet addObject:label];
[xLocationSet addObject:[NSNumber numberWithInteger:location]];
}
x.axisLabels = xLabelSet;
x.majorTickLocations = xLocationSet;
// 4 - Configure y-axis
CPTXYAxis *y = axisSet.yAxis;
y.axisLineStyle = axisLineStyle;
y.labelingPolicy = CPTAxisLabelingPolicyAutomatic;
y.orthogonalCoordinateDecimal = CPTDecimalFromDouble(-0.1);
y.preferredNumberOfMajorTicks = 6;
y.majorGridLineStyle = majorGridLineStyle;
y.labelTextStyle = axisTextStyle;
y.majorTickLineStyle = nil;
y.minorTickLineStyle = nil;
}
I am not getting the concept of how CorePlot will take the data provided and turn it into the required set.
Any suggestions?

As noted in my comment above, plot ranges take a location and length like NSRange. You can use the min value for the location and max - min for the length.
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromCGFloat(yMin)
length:CPTDecimalFromCGFloat(yMax - yMin)];
For your example of a range covering 1,500 to 4,000, use 1,500 for the location and 2,500 (4,000 - 1,500) for the length.

Related

ScatterPlot doens't work properly - dots isn't connected

I am developing a project using Core-Plot with Objective-C. The client asks to create a line chart (using Scatter Plot for this) where plots the number of ocurrencies x the time.
Well, after study for almost a week, this isn't working. My dots aren't connected and I don't know why.
This blue line should've been connected, since it is one plot.
Here is my code:
-(void)renderInLayer:(CPTGraphHostingView *)layerHostingView withTheme:(CPTTheme *)theme animated:(BOOL)animated{
CPTGraph *graph = [[CPTXYGraph alloc] initWithFrame:bounds];
[self addGraph:graph toHostingView:layerHostingView];
[self applyTheme:theme toGraph:graph withDefault:[CPTTheme themeNamed:kCPTDarkGradientTheme]];
graph.paddingTop = 20.0;
graph.paddingRight = 20.0;
graph.paddingLeft = 20.0;
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)graph.defaultPlotSpace;
plotSpace.allowsUserInteraction = YES;
plotSpace.delegate = self;
CPTMutableLineStyle *axesLineStyle = [CPTMutableLineStyle lineStyle];
axesLineStyle.lineWidth = 1.0f;
axesLineStyle.miterLimit = 1.0f;
axesLineStyle.lineColor = [CPTColor grayColor];
CPTTextStyle *labelTextStyle = [CPTTextStyle textStyleWithAttributes:#{ NSForegroundColorAttributeName: BoardGraphValueColor, NSFontAttributeName: BoardGraphValueFont}];
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)graph.axisSet;
NSNumberFormatter * axisFormat = [[NSNumberFormatter alloc] init];
[axisFormat setNumberStyle:NSNumberFormatterNoStyle];
CPTXYAxis *x = axisSet.xAxis;{
x.visibleRange = [CPTPlotRange plotRangeWithLocation:#(-1.0) length:#(100)];
x.labelingPolicy = CPTAxisLabelingPolicyAutomatic;
x.majorIntervalLength = #2;
x.minorTicksPerInterval = 1;
x.majorTickLineStyle = axesLineStyle;
x.minorTickLineStyle = axesLineStyle;
x.axisLineStyle = axesLineStyle;
x.plotSpace = plotSpace;
x.labelTextStyle = labelTextStyle;
x.labelFormatter = axisFormat;
x.labelOffset = 5.0;
}
CPTXYAxis *y = axisSet.yAxis;{
y.visibleRange = [CPTPlotRange plotRangeWithLocation:#(-1.0) length:#(200)];
y.labelingPolicy = CPTAxisLabelingPolicyAutomatic;
y.majorIntervalLength = #30;
y.minorTicksPerInterval = 6;
y.majorTickLineStyle = axesLineStyle;
y.minorTickLineStyle = axesLineStyle;
y.axisLineStyle = axesLineStyle;
y.plotSpace = plotSpace;
y.labelTextStyle = labelTextStyle;
y.labelFormatter = axisFormat;
y.labelOffset = 5.0;
}
graph.axisSet.axes = #[x, y];
CPTMutableLineStyle *lineStyle = [[CPTMutableLineStyle alloc] init];
lineStyle.lineWidth = 2.0;
CPTScatterPlot *scatterLinePlot = [[CPTScatterPlot alloc] init];
scatterLinePlot.areaBaseValue = #(0.0);
scatterLinePlot.identifier = #(1);
scatterLinePlot.title = #"Title";
lineStyle.lineColor = [CPTColor blueColor];
scatterLinePlot.dataLineStyle = lineStyle;
scatterLinePlot.histogramOption = self.histogramOption;
scatterLinePlot.areaBaseValue = #(0);
scatterLinePlot.delegate = self;
scatterLinePlot.plotSymbolMarginForHitDetection = 5.0;
scatterLinePlot.dataSource = self;
[graph addPlot:scatterLinePlot];
CPTPlotRange *globalYRange = [CPTPlotRange plotRangeWithLocation:#0.0
length:#12.0];
plotSpace.globalYRange = globalYRange;
[plotSpace scaleToFitEntirePlots:[graph allPlots]];}
This is the code for create just one plot, but I need to create six. I did a loop but it is working that way too.
Here's the datasource:
-(NSUInteger)numberOfRecordsForPlot:(nonnull CPTPlot *)plot{
return [self.plotData objectAtIndex:0].count;}
-(NSNumber *)numberForPlot:(nonnull CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index{
NSNumber *num = nil;
NSString *key;
NSArray *currentDataPoint;
NSString *plotIdentifier = (NSString *)plot.identifier;
if ([plotIdentifier isEqual:#(1)]){
currentDataPoint = [self.plotData objectAtIndex:0];
} else if ([plotIdentifier isEqual:#(2)]){
currentDataPoint = [self.plotData objectAtIndex:1];
} else if ([plotIdentifier isEqual:#(3)]){
currentDataPoint = [self.plotData objectAtIndex:2];
} else if ([plotIdentifier isEqual:#(4)]){
currentDataPoint = [self.plotData objectAtIndex:3];
} else if ([plotIdentifier isEqual:#(5)]){
currentDataPoint = [self.plotData objectAtIndex:4];
} else if ([plotIdentifier isEqual:#(6)]){
currentDataPoint = [self.plotData objectAtIndex:5];
}
if (fieldEnum == CPTScatterPlotFieldX) {
return #(index);
} else if (fieldEnum == CPTScatterPlotFieldY) {
key = #"count";
int number = [[[currentDataPoint objectAtIndex:index] valueForKey:key] intValue];
NSLog(#"Y value for index %lu is %d", index, number);
num = [[currentDataPoint objectAtIndex:index] valueForKey:key];
return num;}
return num;
}
What am I doing wrong?
PS: Well, another bug is the color of the bar chart. Each of this should have a different color, but it doesn't work too. The colors provided is that for the legends.
Thanks in advance.
To change the bar color for each bar, implement the -barFillForBarPlot:recordIndex: method in the datasource and return the correct fill for each index. You can also set the border line style for each bar (e.g., to use a different color) with the -barLineStyleForBarPlot:recordIndex: datasource method.
It looks like the data line is getting clipped outside the visible area. Make sure the plot data is available from the datasource when you call -scaleToFitEntirePlots:.

Coreplot annotations not in proper location - plotAreaFrame.plotArea.touchedPoint is showing NAN

I am using coreplot to display graph. Annotations are not showing above the location points.
When i debug the graph.plotAreaFrame.plotArea touchedPoints are showing NAN instead of correct points.
-(void)configureGraph {
// 1 - Create the graph
CPTGraph *graph = [[CPTXYGraph alloc] initWithFrame:CGRectMake(0.0, 0.0, 320, 260)];
[graph applyTheme:[CPTTheme themeNamed:kCPTStocksTheme]];
graph.fill = [CPTFill fillWithColor:[CPTColor clearColor]];
graph.plotAreaFrame.fill = [CPTFill fillWithColor:[CPTColor clearColor]];
// 2 - Set graph title
NSString *title = #"Speed";
//graph.title = title;
// 3 - Create and set text style
CPTMutableTextStyle *titleStyle = [CPTMutableTextStyle textStyle];
titleStyle.color = [CPTColor whiteColor];
titleStyle.fontName = #"Helvetica-Bold";
titleStyle.fontSize = 16.0f;
graph.titleTextStyle = titleStyle;
graph.titlePlotAreaFrameAnchor = CPTRectAnchorTop;
graph.titleDisplacement = CGPointMake(0.0f, 10.0f);
// 4 - Set padding for plot area
[graph.plotAreaFrame setPaddingLeft:35.0f];
[graph.plotAreaFrame setPaddingBottom:25.0f];
[graph.plotAreaFrame setPaddingTop:5.0f];
[graph.plotAreaFrame setPaddingRight:0.0f];
graph.plotAreaFrame.masksToBorder = YES;
//graph.plotAreaFrame.plotArea.delegate = self;
// 5 - Enable user interactions for plot space
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *) graph.defaultPlotSpace;
plotSpace.allowsUserInteraction = YES;
plotSpace.delegate = self;
// 2 - Create the three plots
CPTScatterPlot *aaplPlot = [[CPTScatterPlot alloc] init];
aaplPlot.dataSource = self;
aaplPlot.delegate = self;
aaplPlot.plotSymbolMarginForHitDetection = 5.0;
aaplPlot.interpolation = CPTScatterPlotInterpolationCurved;
aaplPlot.identifier = #"A";
CPTColor *aaplColor = [CPTColor colorWithComponentRed:127.0f/255.0f green:255.0f/255.0f blue:255.0f/255.0f alpha:1.0f];
[graph addPlot:aaplPlot toPlotSpace:plotSpace];
// 3 - Set up plot space
[plotSpace scaleToFitPlots:[NSArray arrayWithObjects:aaplPlot, nil]];
[plotSpace setYRange: [CPTPlotRange plotRangeWithLocation:[NSNumber numberWithInt:0] length:[NSNumber numberWithInt:maxY+10]]];
[plotSpace setXRange: [CPTPlotRange plotRangeWithLocation:[NSNumber numberWithInt:0] length:[NSNumber numberWithInt:maxX]]];
// 4 - Create styles and symbols
CPTMutableLineStyle *aaplLineStyle = [aaplPlot.dataLineStyle mutableCopy];
aaplLineStyle.lineWidth = 2.5;
aaplLineStyle.lineColor = aaplColor;
aaplPlot.dataLineStyle = aaplLineStyle;
CPTMutableLineStyle *aaplSymbolLineStyle = [CPTMutableLineStyle lineStyle];
aaplSymbolLineStyle.lineColor = aaplColor;
CPTPlotSymbol *aaplSymbol = [CPTPlotSymbol ellipsePlotSymbol];
aaplSymbol.fill = [CPTFill fillWithColor:aaplColor];
aaplSymbol.lineStyle = aaplSymbolLineStyle;
aaplSymbol.size = CGSizeMake(6.0f, 6.0f);
aaplPlot.plotSymbol = aaplSymbol;
CPTMutableTextStyle *axisTitleStyle = [CPTMutableTextStyle textStyle];
axisTitleStyle.color = [CPTColor whiteColor];
axisTitleStyle.fontName = #"Helvetica-Bold";
axisTitleStyle.fontSize = 12.0f;
CPTMutableLineStyle *axisLineStyle = [CPTMutableLineStyle lineStyle];
axisLineStyle.lineWidth = 2.0f;
axisLineStyle.lineColor = [CPTColor whiteColor];
CPTMutableTextStyle *axisTextStyle = [[CPTMutableTextStyle alloc] init];
axisTextStyle.color = [CPTColor whiteColor];
axisTextStyle.fontName = #"Helvetica-Bold";
axisTextStyle.fontSize = 11.0f;
CPTMutableLineStyle *tickLineStyle = [CPTMutableLineStyle lineStyle];
tickLineStyle.lineColor = [CPTColor whiteColor];
tickLineStyle.lineWidth = 2.0f;
CPTMutableLineStyle *gridLineStyle = [CPTMutableLineStyle lineStyle];
tickLineStyle.lineColor = [CPTColor blackColor];
tickLineStyle.lineWidth = 1.0f;
// 2 - Get axis set
CPTXYAxisSet *axisSet = (CPTXYAxisSet *) graph.axisSet;
// 3 - Configure x-axis
CPTAxis *x = axisSet.xAxis;
x.title = #"Distance --> (Points are 200 meter apart)";
x.titleTextStyle = axisTitleStyle;
x.titleOffset = 8.0f;
x.labelOffset = 0.0f;
x.axisLineStyle = axisLineStyle;
x.labelingPolicy = CPTAxisLabelingPolicyNone;
x.preferredNumberOfMajorTicks = 4;
x.labelTextStyle = axisTextStyle;
x.majorTickLineStyle = axisLineStyle;
x.majorTickLength = 0.0f;
x.minorTickLength = 0.0f;
x.tickDirection = CPTSignNegative;
CGFloat dateCount = [self.arrayOfDates count];
NSMutableSet *xLabels = [NSMutableSet setWithCapacity:dateCount];
NSMutableSet *xLocations = [NSMutableSet setWithCapacity:dateCount];
float i = 0.0;
for (int index = 0 ; index < [self.arrayOfDates count]; index++) {
float distanceX = (float)([[[self.arrayOfDates objectAtIndex:index] objectForKey:#"Distance"] floatValue]);
NSString *labelDist = [NSString stringWithFormat:#"%.2f", distanceX];
CPTAxisLabel *label = [[CPTAxisLabel alloc] initWithText:labelDist textStyle:x.labelTextStyle];
CGFloat location = i++;
label.tickLocation = [NSNumber numberWithFloat:i];
label.offset = x.majorTickLength;
if (label) {
[xLabels addObject:label];
[xLocations addObject:[NSNumber numberWithFloat:location]];
}
}
//x.axisLabels = xLabels;
//x.majorTickLocations = xLocations;
// 4 - Configure y-axis
CPTAxis *y = axisSet.yAxis;
y.title = #"Traffic Density";
y.titleTextStyle = axisTitleStyle;
y.titleOffset = 18.0f;
y.axisLineStyle = axisLineStyle;
//y.majorGridLineStyle = gridLineStyle;
y.labelingPolicy = CPTAxisLabelingPolicyNone;
y.preferredNumberOfMajorTicks = 4;
y.labelTextStyle = axisTextStyle;
y.labelOffset = 0.0f;
y.majorTickLineStyle = axisLineStyle;
y.majorTickLength = 0.0f;
y.minorTickLength = 0.0f;
y.tickDirection = CPTSignNegative;
int majorIncrement = ceil(maxY/4);
NSInteger minorIncrement = maxY/8;
CGFloat yMax = maxY; // should determine dynamically based on max price
NSMutableSet *yLabels = [NSMutableSet set];
NSMutableSet *yMajorLocations = [NSMutableSet set];
NSMutableSet *yMinorLocations = [NSMutableSet set];
for (NSInteger j = 0; j <= yMax + majorIncrement; j++) {
NSUInteger mod = j % majorIncrement;
if (mod == 0) {
CPTAxisLabel *label = [[CPTAxisLabel alloc] initWithText:[NSString stringWithFormat:#"%i", j] textStyle:y.labelTextStyle];
NSDecimal location = CPTDecimalFromInteger(j);
label.tickLocation = [NSNumber numberWithInt:j];
label.offset = -y.majorTickLength - y.labelOffset;
if (label) {
[yLabels addObject:label];
}
[yMajorLocations addObject:[NSDecimalNumber decimalNumberWithDecimal:location]];
}
}
y.axisLabels = yLabels;
y.majorTickLocations = yMajorLocations;
// Create a plot that uses the data source method
axisSet.xAxis.axisConstraints = [CPTConstraints constraintWithLowerOffset:0.0];
axisSet.xAxis.orthogonalPosition = [NSNumber numberWithInt:0];
axisSet.yAxis.axisConstraints = [CPTConstraints constraintWithLowerOffset:0.0];
self.hostView.collapsesLayers = NO;
self.hostView.hostedGraph = graph;}
This is the coreplot annotation display method.
-(void)scatterPlot:(nonnull CPTScatterPlot *)plot plotSymbolWasSelectedAtRecordIndex:(NSUInteger)index
{
CPTGraph *graph = self.hostView.hostedGraph;
CPTPlotSpaceAnnotation *annotation = self.symbolTextAnnotation;
if ( annotation ) {
[graph.plotAreaFrame.plotArea removeAnnotation:annotation];
self.symbolTextAnnotation = nil;
}
// Setup a style for the annotation
CPTMutableTextStyle *hitAnnotationTextStyle = [CPTMutableTextStyle textStyle];
hitAnnotationTextStyle.color = [CPTColor whiteColor];
hitAnnotationTextStyle.fontName = #"Helvetica-Bold";
hitAnnotationTextStyle.fontSize = 16.0;
// Determine point of symbol in plot coordinates
NSNumber *x = [NSNumber numberWithFloat:[[[self.arrayOfDates objectAtIndex:index] objectForKey:#"Distance"] floatValue]] ;
NSNumber *y = [NSNumber numberWithFloat:[[[self.arrayOfValues objectAtIndex:index] objectForKey:#"Speed"] floatValue]];
CPTNumberArray *anchorPoint = #[x, y];
// Add annotation
// First make a string for the y value
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.maximumFractionDigits = 2;
NSString *yString = [formatter stringFromNumber:y];
CPTPlotSpace *defaultSpace = graph.defaultPlotSpace;
if ( defaultSpace ) {
CPTTextLayer *textLayer = [[CPTTextLayer alloc] initWithText:yString style:hitAnnotationTextStyle];
annotation = [[CPTPlotSpaceAnnotation alloc] initWithPlotSpace:defaultSpace anchorPlotPoint:anchorPoint];
annotation.contentLayer = textLayer;
annotation.displacement = CGPointMake(0.0, 10.0);
[graph.plotAreaFrame.plotArea addAnnotation:annotation];
}
}
Please check the screenshot the points are not aligned with the points of the graph.
Data Source methods
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index {
NSInteger valueCount = [self.arrayOfDates count];
switch (fieldEnum) {
case CPTScatterPlotFieldX:
if (index < valueCount) {
distanceX += [[[self.arrayOfDates objectAtIndex:index] objectForKey:#"Distance"] floatValue];
NSLog(#"Distance = %f",distanceX);
return [NSNumber numberWithFloat:distanceX];
}
break;
case CPTScatterPlotFieldY:{
float distance = [[[self.arrayOfValues objectAtIndex:index] objectForKey:#"Speed"] floatValue];
return [NSNumber numberWithFloat:distance];
break;
}
}
return [NSDecimalNumber zero];}
When i touched the point, plotAreaFrame.plotArea.touchedPoint is NAN. Please refer this screenshot
The question doesn't show the datasource methods, but based on how the x-axis labels are set up, it looks like the x-values are plotted as the data index. Try using the following anchor point calculation when positioning the annotation:
NSNumber *y = [[self.arrayOfValues objectAtIndex:index] objectForKey:#"Speed"];
CPTNumberArray *anchorPoint = #[#(index), y];

Core-Plot multiple y axis alignment issues - possibly related to scaling

My Issues is as follows:
I'm trying to graph two data sets (One is in Feet and one is in degrees) in such a way that they can be compared (they do share a common x-axis value).
As you can see my data seems to be interlaced correctly but I'm having trouble getting the yAxises to behave as I'd like. I would like the X-Axis Max/Min to actually line up with both Y-Axises. My code is as follows:
- (void)initPlot {
[self loadCoreData];
[self configureHost];
[self configureGraph];
[self configurePlots];
[self configureAxes];
}
- (void)configureHost {
self.hostView = [(CPTGraphHostingView *) [CPTGraphHostingView alloc] initWithFrame:self.view.bounds];
self.hostView.allowPinchScaling = YES;
[self.view addSubview:self.hostView];
}
- (void)configureGraph {
// 1 - Create the graph
CPTGraph *graph = [[CPTXYGraph alloc] initWithFrame:self.hostView.bounds];
[graph applyTheme:[CPTTheme themeNamed:kCPTDarkGradientTheme]];
self.hostView.hostedGraph = graph;
// 2 - Set graph title
NSString *title = [NSString stringWithFormat:#"Altitude Plot [%# to %#]", self.flightRecording.originAirport, self.flightRecording.destinationAirport];
graph.title = title;
// 3 - Create and set text style
CPTMutableTextStyle *titleStyle = [CPTMutableTextStyle textStyle];
titleStyle.color = [CPTColor whiteColor];
titleStyle.fontName = #"Helvetica-Bold";
titleStyle.fontSize = 16.0f;
graph.titleTextStyle = titleStyle;
graph.titlePlotAreaFrameAnchor = CPTRectAnchorTop;
graph.titleDisplacement = CGPointMake(0.0f, -20.0f);
// 4 - Set padding for plot area
float padding = 10.0f;
[graph.plotAreaFrame setPaddingLeft:padding];
[graph.plotAreaFrame setPaddingBottom:50.0f];
[graph.plotAreaFrame setPaddingRight:padding];
[graph.plotAreaFrame setPaddingTop:padding];
// 5 - Enable user interactions for plot space
altSpace= (CPTXYPlotSpace *) graph.defaultPlotSpace;
altSpace.allowsUserInteraction = NO;
rollSpace = [[CPTXYPlotSpace alloc] init];
rollSpace.allowsUserInteraction = NO;
[self.hostView.hostedGraph addPlotSpace:rollSpace];
//
// pitchSpace = [[CPTXYPlotSpace alloc] init];
// pitchSpace.allowsUserInteraction = NO;
// [self.hostView.hostedGraph addPlotSpace:pitchSpace];
//
//
// slipSpace = [[CPTXYPlotSpace alloc] init];
// slipSpace.allowsUserInteraction = NO;
// [self.hostView.hostedGraph addPlotSpace:slipSpace];
//
//
// gSpace = [[CPTXYPlotSpace alloc] init];
// gSpace.allowsUserInteraction = NO;
// [self.hostView.hostedGraph addPlotSpace:gSpace];
}
- (void)configurePlots {
// 1 - Get graph and plot space
CPTGraph *graph = self.hostView.hostedGraph;
// 2 - Create the three plots
// Custom AHRS Plot
CPTScatterPlot *ahrsAltPlot = [[CPTScatterPlot alloc] init];
ahrsAltPlot.dataSource = self;
ahrsAltPlot.identifier = #"AHRSALT";
CPTColor *ahrsAltColor = [CPTColor yellowColor];
[graph addPlot:ahrsAltPlot toPlotSpace:altSpace];
CPTScatterPlot *rollPlot = [[CPTScatterPlot alloc] init];
rollPlot.dataSource = self;
rollPlot.identifier = #"ROLL";
CPTColor *rollColor = [CPTColor greenColor];
[graph addPlot:rollPlot toPlotSpace:rollSpace];
// 3 - Set up plot space
CPTMutablePlotRange *xRange = [altSpace.xRange mutableCopy];
xRange=[CPTMutablePlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0f ) length:CPTDecimalFromFloat(maxEpoch + 300.0f )];
// [xRange expandRangeByFactor:CPTDecimalFromCGFloat(1.1f)];
altSpace.xRange = xRange;
CPTMutablePlotRange *yRange = [altSpace.yRange mutableCopy];
yRange = [CPTMutablePlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0f) length:CPTDecimalFromFloat(maxAlt)];
[yRange expandRangeByFactor:CPTDecimalFromCGFloat(1.2f)];
altSpace.yRange = yRange;
rollSpace.xRange = xRange;
CPTMutablePlotRange *yRangeRoll =[CPTMutablePlotRange plotRangeWithLocation:CPTDecimalFromFloat(0 ) length:CPTDecimalFromFloat(40 )];
[yRangeRoll expandRangeByFactor:CPTDecimalFromCGFloat(1.2f)];
rollSpace.yRange = yRangeRoll;
[altSpace scaleToFitPlots:[NSArray arrayWithObjects:ahrsAltPlot, nil] ];
[rollSpace scaleToFitPlots:[NSArray arrayWithObjects:rollPlot, nil] ];
[rollSpace setYRange:yRangeRoll];
// 4 - Create styles and symbols
// AHRS Style
CPTMutableLineStyle *ahrsLineStyle = [ahrsAltPlot.dataLineStyle mutableCopy];
ahrsLineStyle.lineWidth = 2.5;
ahrsLineStyle.lineColor = [CPTColor blueColor];
ahrsAltPlot.dataLineStyle = ahrsLineStyle;
}
- (void)configureAxes {
// 1 - Create styles
CPTMutableTextStyle *axisTitleStyle = [CPTMutableTextStyle textStyle];
axisTitleStyle.color = [CPTColor whiteColor];
axisTitleStyle.fontName = #"Helvetica-Bold";
axisTitleStyle.fontSize = 12.0f;
CPTMutableLineStyle *axisLineStyle = [CPTMutableLineStyle lineStyle];
axisLineStyle.lineWidth = 2.0f;
axisLineStyle.lineColor = [CPTColor whiteColor];
CPTMutableTextStyle *axisTextStyle = [[CPTMutableTextStyle alloc] init];
axisTextStyle.color = [CPTColor whiteColor];
axisTextStyle.fontName = #"Helvetica-Bold";
axisTextStyle.fontSize = 11.0f;
CPTMutableLineStyle *tickLineStyle = [CPTMutableLineStyle lineStyle];
tickLineStyle.lineColor = [CPTColor whiteColor];
tickLineStyle.lineWidth = 2.0f;
CPTMutableLineStyle *gridLineStyle = [CPTMutableLineStyle lineStyle];
tickLineStyle.lineColor = [CPTColor blackColor];
tickLineStyle.lineWidth = 1.0f;
// 2 - Get axis set
CPTXYAxisSet *axisSet = (CPTXYAxisSet *) self.hostView.hostedGraph.axisSet;
// 3 - Configure x-axis
CPTAxis *x = axisSet.xAxis;
x.title = #"Flight Time";
x.titleTextStyle = axisTitleStyle;
x.titleOffset = 15.0f;
x.axisLineStyle = axisLineStyle;
x.labelingPolicy = CPTAxisLabelingPolicyNone;
x.labelTextStyle = axisTextStyle;
x.majorTickLineStyle = axisLineStyle;
x.majorTickLength = 4.0f;
x.tickDirection = CPTSignNegative;
NSMutableSet *xLabels = [NSMutableSet new];
NSMutableSet *xLocations = [NSMutableSet new];
NSInteger i = 0;
for (i; i < maxEpoch; i += 600) {
int hour = i / (68 * 60);
int min = i / 60;
CPTAxisLabel *label = [[CPTAxisLabel alloc] initWithText:[NSString stringWithFormat:#"%02d:%02d", hour, min] textStyle:x.labelTextStyle];
CGFloat location = i++;
label.tickLocation = CPTDecimalFromCGFloat(location);
label.offset = x.majorTickLength;
if (label) {
[xLabels addObject:label];
[xLocations addObject:[NSNumber numberWithInteger:i]];
}
}
x.axisLabels = xLabels;
x.majorTickLocations = xLocations;
// 4 - Configure y-axis
CPTAxis *y = axisSet.yAxis;
y.title = #"Altitude in Feet";
y.titleTextStyle = axisTitleStyle;
y.titleOffset = 20.0f;
y.axisLineStyle = axisLineStyle;
y.majorGridLineStyle = gridLineStyle;
y.labelingPolicy = CPTAxisLabelingPolicyNone;
y.labelTextStyle = axisTextStyle;
y.labelOffset = 21.0f;
y.majorTickLineStyle = axisLineStyle;
y.majorTickLength = 20.0f;
y.minorTickLength = 10.0f;
y.tickDirection = CPTSignNegative;
// Axis #2
CPTXYAxis *yRoll = [[CPTXYAxis alloc] init];
yRoll.title = #"Degrees";
// Styling
yRoll.titleTextStyle = axisTitleStyle;
yRoll.labelTextStyle = axisTextStyle;
yRoll.axisLineStyle = axisLineStyle;
yRoll.majorTickLineStyle = axisLineStyle;
yRoll.plotSpace = rollSpace;
yRoll.delegate = self;
yRoll.labelingPolicy = CPTAxisLabelingPolicyNone;
yRoll.coordinate = CPTCoordinateY;
yRoll.tickDirection = CPTSignNone;
yRoll.separateLayers = NO;
yRoll.tickDirection = CPTSignNegative;
yRoll.labelOffset = 21.0f;
yRoll.axisConstraints = [CPTConstraints constraintWithLowerOffset:40.0];
yRoll.orthogonalCoordinateDecimal = CPTDecimalFromFloat(0.0f);
NSMutableSet *rollLabels = [NSMutableSet new];
NSMutableSet *rollLocations = [NSMutableSet new];
for (int i =0; i <= 40; i+= 5) {
CPTAxisLabel *label = [[CPTAxisLabel alloc] initWithText:[NSString stringWithFormat:#"%02d˚", (i - 20)] textStyle:yRoll.labelTextStyle];
CGFloat location = i;
label.tickLocation = CPTDecimalFromCGFloat(location);
label.offset = -16.0f;
if (label) {
[rollLabels addObject:label];
[rollLocations addObject:[NSNumber numberWithInteger:i]];
}
}
yRoll.axisLabels = rollLabels;
yRoll.majorTickLocations = rollLocations;
NSInteger majorIncrement = 500;
NSInteger minorIncrement = 100;
CGFloat yMax = maxAlt; // should determine dynamically based on max price
NSMutableSet *yLabels = [NSMutableSet set];
NSMutableSet *yMajorLocations = [NSMutableSet set];
NSMutableSet *yMinorLocations = [NSMutableSet set];
for (NSInteger j = minorIncrement; j <= yMax; j += minorIncrement) {
NSUInteger mod = j % majorIncrement;
if (mod == 0) {
CPTAxisLabel *label = [[CPTAxisLabel alloc] initWithText:[NSString stringWithFormat:#"%i ft", j] textStyle:y.labelTextStyle];
NSDecimal location = CPTDecimalFromInteger(j);
label.tickLocation = location;
label.offset = -y.majorTickLength - y.labelOffset;
if (label) {
[yLabels addObject:label];
}
[yMajorLocations addObject:[NSDecimalNumber decimalNumberWithDecimal:location]];
} else {
[yMinorLocations addObject:[NSDecimalNumber decimalNumberWithDecimal:CPTDecimalFromInteger(j)]];
}
}
// Position the y2 axis
// y2.axisConstraints = [CPTConstraints constraintWithUpperOffset:40.0];
axisSet.yAxis.axisConstraints = [CPTConstraints constraintWithUpperOffset:40.0];
y.axisLabels = yLabels;
y.majorTickLocations = yMajorLocations;
y.minorTickLocations = yMinorLocations;
self.hostView.hostedGraph.axisSet.axes = [NSArray arrayWithObjects:x,y,yRoll,nil];
// Position floating YAxis
// y2.axisConstraints = [CPTConstraints constraintWithUpperOffset:150.0];
}
EDIT::
I tried adding the following lines and they did nothing either
y.orthogonalCoordinateDecimal = CPTDecimalFromFloat(0.0f);
x.orthogonalCoordinateDecimal = CPTDecimalFromFloat(0.0f);
I seem to be making progress actually: It appears that if I remove
yAxis2.axisConstraints = [CPTConstraints constraintWithLowerOffset:40.0];
Then my axis actually seems to pin to the x-axis (although its off the screen) now but its a start.
Problem Solved:
I had some conflicting directives going on.
In order to achieve what I needed I had to use the two calls:
yAxis2.orthogonalCoordinateDecimal = CPTDecimalFromFloat(0.0f);
y.orthogonalCoordinateDecimal = CPTDecimalFromFloat(maxEpoch); // maximum X value
x.orthogonalCoordinateDecimal = CPTDecimalFromFloat(0.0f);
Then in order to make sure everything could be seen correctly I had to play with the padding values:
float padding = 50.0f;
[graph.plotAreaFrame setPaddingLeft:padding];
[graph.plotAreaFrame setPaddingBottom:50.0f];
[graph.plotAreaFrame setPaddingRight:padding];
[graph.plotAreaFrame setPaddingTop:padding];
And I had to remove all the constraints that were messing with things:
// yAxis2.axisConstraints = [CPTConstraints constraintWithLowerOffset:40.0];
// y.axisConstraints = [CPTConstraints constraintWithUpperOffset:150.0];

Adding Coreplot Graph UIViewController to another UIViewController's view

So I am having an issue with Coreplot.
I am currently attempting to add my Coreplot graph that i implemented within one of my UIViewController's subviews.
I implemented the Coreplot graph in a UIViewCOntroller class and attempted to add the coreplot viewcontroller's ".view" to the subview of another Viewcontroller.
ScatterPlotViewController *scatterPlot = [[ScatterPlotViewController alloc] init];
[graphView addSubview:scatterPlot.view];
Where graphview is a small uiview among a few other's inside my mainview controller.
CorePlot example
The example implements a 3 graphs but currently I just implemented one (the scatter plot) without using storyboard. The graph displays fine when I ask the main view controller to push to another viewcontroller
ScatterPlotViewController *scatter = [[ScatterPlotViewController alloc] init];
[self.navigationController pushViewController:scatter animated:YES];
I am lost :(.
I tried to read several more similar questions but all lead me to using the HOSTVIEW or
graphView = [(CPTGraphHostingView *) [CPTGraphHostingView alloc] initWithFrame:CGRectMake(120, 296, 200, 120)];
graphView.backgroundColor = [UIColor redColor];
[self.view addSubview:graphView];
ScatterPlotViewController *scatterPlot = [[ScatterPlotViewController alloc] init];
[graphView.hostedGraph.hostingView addSubview:scatterPlot.hostView.inputView];
I have changed this around a few times, channging
scatterPlot.hostView.inputView to scatterPlot.view
changing
graphView.hostedGraph.hostingView to graphView.view
And several others.
Here is the entire code for the class I used, it is basically the entire code that is used in the tutorial link. I also didn't use storyboards like the tutorial. I just used the code.
.h
#import <UIKit/UIKit.h>
#import "CorePlot-CocoaTouch.h"
#import "CPDConstants.h"
#import "CPDStockPriceStore.h"
#interface ScatterPlotViewController : UIViewController <CPTPlotDataSource>
#property (nonatomic, strong) CPTGraphHostingView *hostView;
.m
#import "ScatterPlotViewController.h"
#implementation ScatterPlotViewController
#synthesize hostView = hostView_;
-(void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - UIViewController lifecycle methods
-(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[self initPlot];
}
#pragma mark - Chart behavior
-(void)initPlot {
[self configureHost];
[self configureGraph];
[self configurePlots];
[self configureAxes];
}
-(void)configureHost {
self.hostView = [(CPTGraphHostingView *) [CPTGraphHostingView alloc] initWithFrame:self.view.bounds];
self.hostView.allowPinchScaling = YES;
[self.view addSubview:self.hostView];
}
-(void)configureGraph {
// 1 - Create the graph
CPTGraph *graph = [[CPTXYGraph alloc] initWithFrame:self.hostView.bounds];
[graph applyTheme:[CPTTheme themeNamed:kCPTDarkGradientTheme]];
self.hostView.hostedGraph = graph;
// 2 - Set graph title
NSString *title = #"Portfolio Prices: April 2012";
graph.title = title;
// 3 - Create and set text style
CPTMutableTextStyle *titleStyle = [CPTMutableTextStyle textStyle];
titleStyle.color = [CPTColor whiteColor];
titleStyle.fontName = #"Helvetica-Bold";
titleStyle.fontSize = 16.0f;
graph.titleTextStyle = titleStyle;
graph.titlePlotAreaFrameAnchor = CPTRectAnchorTop;
graph.titleDisplacement = CGPointMake(0.0f, 10.0f);
// 4 - Set padding for plot area
[graph.plotAreaFrame setPaddingLeft:30.0f];
[graph.plotAreaFrame setPaddingBottom:30.0f];
// 5 - Enable user interactions for plot space
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *) graph.defaultPlotSpace;
plotSpace.allowsUserInteraction = YES;
}
-(void)configurePlots {
// 1 - Get graph and plot space
CPTGraph *graph = self.hostView.hostedGraph;
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *) graph.defaultPlotSpace;
// 2 - Create the three plots
CPTScatterPlot *aaplPlot = [[CPTScatterPlot alloc] init];
aaplPlot.dataSource = self;
aaplPlot.identifier = CPDTickerSymbolAAPL;
CPTColor *aaplColor = [CPTColor redColor];
[graph addPlot:aaplPlot toPlotSpace:plotSpace];
CPTScatterPlot *googPlot = [[CPTScatterPlot alloc] init];
googPlot.dataSource = self;
googPlot.identifier = CPDTickerSymbolGOOG;
CPTColor *googColor = [CPTColor greenColor];
[graph addPlot:googPlot toPlotSpace:plotSpace];
CPTScatterPlot *msftPlot = [[CPTScatterPlot alloc] init];
msftPlot.dataSource = self;
msftPlot.identifier = CPDTickerSymbolMSFT;
CPTColor *msftColor = [CPTColor blueColor];
[graph addPlot:msftPlot toPlotSpace:plotSpace];
// 3 - Set up plot space
[plotSpace scaleToFitPlots:[NSArray arrayWithObjects:aaplPlot, googPlot, msftPlot, nil]];
CPTMutablePlotRange *xRange = [plotSpace.xRange mutableCopy];
[xRange expandRangeByFactor:CPTDecimalFromCGFloat(1.1f)];
plotSpace.xRange = xRange;
CPTMutablePlotRange *yRange = [plotSpace.yRange mutableCopy];
[yRange expandRangeByFactor:CPTDecimalFromCGFloat(1.2f)];
plotSpace.yRange = yRange;
// 4 - Create styles and symbols
CPTMutableLineStyle *aaplLineStyle = [aaplPlot.dataLineStyle mutableCopy];
aaplLineStyle.lineWidth = 2.5;
aaplLineStyle.lineColor = aaplColor;
aaplPlot.dataLineStyle = aaplLineStyle;
CPTMutableLineStyle *aaplSymbolLineStyle = [CPTMutableLineStyle lineStyle];
aaplSymbolLineStyle.lineColor = aaplColor;
CPTPlotSymbol *aaplSymbol = [CPTPlotSymbol ellipsePlotSymbol];
aaplSymbol.fill = [CPTFill fillWithColor:aaplColor];
aaplSymbol.lineStyle = aaplSymbolLineStyle;
aaplSymbol.size = CGSizeMake(6.0f, 6.0f);
aaplPlot.plotSymbol = aaplSymbol;
CPTMutableLineStyle *googLineStyle = [googPlot.dataLineStyle mutableCopy];
googLineStyle.lineWidth = 1.0;
googLineStyle.lineColor = googColor;
googPlot.dataLineStyle = googLineStyle;
CPTMutableLineStyle *googSymbolLineStyle = [CPTMutableLineStyle lineStyle];
googSymbolLineStyle.lineColor = googColor;
CPTPlotSymbol *googSymbol = [CPTPlotSymbol starPlotSymbol];
googSymbol.fill = [CPTFill fillWithColor:googColor];
googSymbol.lineStyle = googSymbolLineStyle;
googSymbol.size = CGSizeMake(6.0f, 6.0f);
googPlot.plotSymbol = googSymbol;
CPTMutableLineStyle *msftLineStyle = [msftPlot.dataLineStyle mutableCopy];
msftLineStyle.lineWidth = 2.0;
msftLineStyle.lineColor = msftColor;
msftPlot.dataLineStyle = msftLineStyle;
CPTMutableLineStyle *msftSymbolLineStyle = [CPTMutableLineStyle lineStyle];
msftSymbolLineStyle.lineColor = msftColor;
CPTPlotSymbol *msftSymbol = [CPTPlotSymbol diamondPlotSymbol];
msftSymbol.fill = [CPTFill fillWithColor:msftColor];
msftSymbol.lineStyle = msftSymbolLineStyle;
msftSymbol.size = CGSizeMake(6.0f, 6.0f);
msftPlot.plotSymbol = msftSymbol;
}
-(void)configureAxes {
// 1 - Create styles
CPTMutableTextStyle *axisTitleStyle = [CPTMutableTextStyle textStyle];
axisTitleStyle.color = [CPTColor whiteColor];
axisTitleStyle.fontName = #"Helvetica-Bold";
axisTitleStyle.fontSize = 12.0f;
CPTMutableLineStyle *axisLineStyle = [CPTMutableLineStyle lineStyle];
axisLineStyle.lineWidth = 2.0f;
axisLineStyle.lineColor = [CPTColor whiteColor];
CPTMutableTextStyle *axisTextStyle = [[CPTMutableTextStyle alloc] init];
axisTextStyle.color = [CPTColor whiteColor];
axisTextStyle.fontName = #"Helvetica-Bold";
axisTextStyle.fontSize = 11.0f;
CPTMutableLineStyle *tickLineStyle = [CPTMutableLineStyle lineStyle];
tickLineStyle.lineColor = [CPTColor whiteColor];
tickLineStyle.lineWidth = 2.0f;
CPTMutableLineStyle *gridLineStyle = [CPTMutableLineStyle lineStyle];
tickLineStyle.lineColor = [CPTColor blackColor];
tickLineStyle.lineWidth = 1.0f;
// 2 - Get axis set
CPTXYAxisSet *axisSet = (CPTXYAxisSet *) self.hostView.hostedGraph.axisSet;
// 3 - Configure x-axis
CPTAxis *x = axisSet.xAxis;
x.title = #"Day of Month";
x.titleTextStyle = axisTitleStyle;
x.titleOffset = 15.0f;
x.axisLineStyle = axisLineStyle;
x.labelingPolicy = CPTAxisLabelingPolicyNone;
x.labelTextStyle = axisTextStyle;
x.majorTickLineStyle = axisLineStyle;
x.majorTickLength = 4.0f;
x.tickDirection = CPTSignNegative;
CGFloat dateCount = [[[CPDStockPriceStore sharedInstance] datesInMonth] count];
NSMutableSet *xLabels = [NSMutableSet setWithCapacity:dateCount];
NSMutableSet *xLocations = [NSMutableSet setWithCapacity:dateCount];
NSInteger i = 0;
for (NSString *date in [[CPDStockPriceStore sharedInstance] datesInMonth]) {
CPTAxisLabel *label = [[CPTAxisLabel alloc] initWithText:date textStyle:x.labelTextStyle];
CGFloat location = i++;
label.tickLocation = CPTDecimalFromCGFloat(location);
label.offset = x.majorTickLength;
if (label) {
[xLabels addObject:label];
[xLocations addObject:[NSNumber numberWithFloat:location]];
}
}
x.axisLabels = xLabels;
x.majorTickLocations = xLocations;
// 4 - Configure y-axis
CPTAxis *y = axisSet.yAxis;
y.title = #"Price";
y.titleTextStyle = axisTitleStyle;
y.titleOffset = -40.0f;
y.axisLineStyle = axisLineStyle;
y.majorGridLineStyle = gridLineStyle;
y.labelingPolicy = CPTAxisLabelingPolicyNone;
y.labelTextStyle = axisTextStyle;
y.labelOffset = 16.0f;
y.majorTickLineStyle = axisLineStyle;
y.majorTickLength = 4.0f;
y.minorTickLength = 2.0f;
y.tickDirection = CPTSignPositive;
NSInteger majorIncrement = 100;
NSInteger minorIncrement = 50;
CGFloat yMax = 700.0f; // should determine dynamically based on max price
NSMutableSet *yLabels = [NSMutableSet set];
NSMutableSet *yMajorLocations = [NSMutableSet set];
NSMutableSet *yMinorLocations = [NSMutableSet set];
for (NSInteger j = minorIncrement; j <= yMax; j += minorIncrement) {
NSUInteger mod = j % majorIncrement;
if (mod == 0) {
CPTAxisLabel *label = [[CPTAxisLabel alloc] initWithText:[NSString stringWithFormat:#"%i", j] textStyle:y.labelTextStyle];
NSDecimal location = CPTDecimalFromInteger(j);
label.tickLocation = location;
label.offset = -y.majorTickLength - y.labelOffset;
if (label) {
[yLabels addObject:label];
}
[yMajorLocations addObject:[NSDecimalNumber decimalNumberWithDecimal:location]];
} else {
[yMinorLocations addObject:[NSDecimalNumber decimalNumberWithDecimal:CPTDecimalFromInteger(j)]];
}
}
y.axisLabels = yLabels;
y.majorTickLocations = yMajorLocations;
y.minorTickLocations = yMinorLocations;
}
#pragma mark - Rotation
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft);
}
#pragma mark - CPTPlotDataSource methods
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot {
return [[[CPDStockPriceStore sharedInstance] datesInMonth] count];
}
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index {
NSInteger valueCount = [[[CPDStockPriceStore sharedInstance] datesInMonth] count];
switch (fieldEnum) {
case CPTScatterPlotFieldX:
if (index < valueCount) {
return [NSNumber numberWithUnsignedInteger:index];
}
break;
case CPTScatterPlotFieldY:
if ([plot.identifier isEqual:CPDTickerSymbolAAPL] == YES) {
return [[[CPDStockPriceStore sharedInstance] monthlyPrices:CPDTickerSymbolAAPL] objectAtIndex:index];
} else if ([plot.identifier isEqual:CPDTickerSymbolGOOG] == YES) {
return [[[CPDStockPriceStore sharedInstance] monthlyPrices:CPDTickerSymbolGOOG] objectAtIndex:index];
} else if ([plot.identifier isEqual:CPDTickerSymbolMSFT] == YES) {
return [[[CPDStockPriceStore sharedInstance] monthlyPrices:CPDTickerSymbolMSFT] objectAtIndex:index];
}
break;
}
return [NSDecimalNumber zero];
}
Any help is fine!!!
Just need to get this darn app working correctly :P
Placing one view controller under another requires special handling. Read the "Implementing a Container View Controller" section in the Overview of the UIViewController class docs.
Did you try (??):
ScatterPlotViewController *scatterPlot = [[ScatterPlotViewController alloc] init];
[(yourViewController *) addChildViewController:scatterPlot];
[graphView addSubview:scatterPlot.view];
[scatterPlot didMoveToParentViewController:(yourViewController *)];

Enable x-Axis (Horizontal) scroll in coreplot

I am using code from this link . And currently If I have 50 bar columns or 150 bar columns then the labels below is compressed and I would like to have horizontal scroll on x-Axis instead of having compressed x-Axis.
I have tried this:
plotSpace.xRange = CPTPlotRangeplotRangeWithLocation:CPTDecimalFromInt(-1)length:CPTDecimalFromInt(50)];
Attaching code from the file :
#import "GraphView.h"
#implementation GraphView
- (void)generateData
{
NSMutableDictionary *dataTemp = [[NSMutableDictionary alloc] init];
//Array containing all the dates that will be displayed on the X axis
dates = [NSArray arrayWithObjects:#"2012-05-01", #"2012-05-02", #"2012-05-03",
#"2012-05-04", #"2012-05-05", #"2012-05-06", #"2012-05-07", nil];
//Dictionary containing the name of the two sets and their associated color
//used for the demo
sets = [NSDictionary dictionaryWithObjectsAndKeys:[UIColor blueColor], #"Plot 1",
[UIColor redColor], #"Plot 2",
[UIColor greenColor], #"Plot 3", nil];
//Generate random data for each set of data that will be displayed for each day
//Numbers between 1 and 10
for (NSString *date in dates) {
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for (NSString *set in sets) {
NSNumber *num = [NSNumber numberWithInt:arc4random_uniform(10)+1];
[dict setObject:num forKey:set];
}
[dataTemp setObject:dict forKey:date];
}
data = [dataTemp copy];
[dataTemp release];
NSLog(#"%#", data);
}
- (void)generateLayout
{
//Create graph from theme
graph = [[CPTXYGraph alloc] initWithFrame:CGRectZero];
[graph applyTheme:[CPTTheme themeNamed:kCPTStocksTheme]];
self.hostedGraph = graph;
graph.plotAreaFrame.masksToBorder = NO;
graph.paddingLeft = 0.0f;
graph.paddingTop = 0.0f;
graph.paddingRight = 0.0f;
graph.paddingBottom = 0.0f;
CPTMutableLineStyle *borderLineStyle = [CPTMutableLineStyle lineStyle];
borderLineStyle.lineColor = [CPTColor whiteColor];
borderLineStyle.lineWidth = 2.0f;
graph.plotAreaFrame.borderLineStyle = borderLineStyle;
graph.plotAreaFrame.paddingTop = 10.0;
graph.plotAreaFrame.paddingRight = 10.0;
graph.plotAreaFrame.paddingBottom = 80.0;
graph.plotAreaFrame.paddingLeft = 70.0;
//Add plot space
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)graph.defaultPlotSpace;
plotSpace.delegate = self;
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(0)
length:CPTDecimalFromInt(10 * sets.count)];
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(-1)
length:CPTDecimalFromInt(8)];
//Grid line styles
CPTMutableLineStyle *majorGridLineStyle = [CPTMutableLineStyle lineStyle];
majorGridLineStyle.lineWidth = 0.75;
majorGridLineStyle.lineColor = [[CPTColor whiteColor] colorWithAlphaComponent:0.1];
CPTMutableLineStyle *minorGridLineStyle = [CPTMutableLineStyle lineStyle];
minorGridLineStyle.lineWidth = 0.25;
minorGridLineStyle.lineColor = [[CPTColor whiteColor] colorWithAlphaComponent:0.1];
//Axes
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)graph.axisSet;
//X axis
CPTXYAxis *x = axisSet.xAxis;
x.orthogonalCoordinateDecimal = CPTDecimalFromInt(0);
x.majorIntervalLength = CPTDecimalFromInt(1);
x.minorTicksPerInterval = 0;
x.labelingPolicy = CPTAxisLabelingPolicyNone;
x.majorGridLineStyle = majorGridLineStyle;
x.axisConstraints = [CPTConstraints constraintWithLowerOffset:0.0];
//X labels
int labelLocations = 0;
NSMutableArray *customXLabels = [NSMutableArray array];
for (NSString *day in dates) {
CPTAxisLabel *newLabel = [[CPTAxisLabel alloc] initWithText:day textStyle:x.labelTextStyle];
newLabel.tickLocation = [[NSNumber numberWithInt:labelLocations] decimalValue];
newLabel.offset = x.labelOffset + x.majorTickLength;
newLabel.rotation = M_PI / 4;
[customXLabels addObject:newLabel];
labelLocations++;
[newLabel release];
}
x.axisLabels = [NSSet setWithArray:customXLabels];
//Y axis
CPTXYAxis *y = axisSet.yAxis;
y.title = #"Value";
y.titleOffset = 50.0f;
y.labelingPolicy = CPTAxisLabelingPolicyAutomatic;
y.majorGridLineStyle = majorGridLineStyle;
y.minorGridLineStyle = minorGridLineStyle;
y.axisConstraints = [CPTConstraints constraintWithLowerOffset:0.0];
//Create a bar line style
CPTMutableLineStyle *barLineStyle = [[[CPTMutableLineStyle alloc] init] autorelease];
barLineStyle.lineWidth = 1.0;
barLineStyle.lineColor = [CPTColor whiteColor];
CPTMutableTextStyle *whiteTextStyle = [CPTMutableTextStyle textStyle];
whiteTextStyle.color = [CPTColor whiteColor];
//Plot
BOOL firstPlot = YES;
for (NSString *set in [[sets allKeys] sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)]) {
CPTBarPlot *plot = [CPTBarPlot tubularBarPlotWithColor:[CPTColor blueColor] horizontalBars:NO];
plot.lineStyle = barLineStyle;
CGColorRef color = ((UIColor *)[sets objectForKey:set]).CGColor;
plot.fill = [CPTFill fillWithColor:[CPTColor colorWithCGColor:color]];
if (firstPlot) {
plot.barBasesVary = NO;
firstPlot = NO;
} else {
plot.barBasesVary = YES;
}
plot.barWidth = CPTDecimalFromFloat(0.8f);
plot.barsAreHorizontal = NO;
plot.dataSource = self;
plot.identifier = set;
[graph addPlot:plot toPlotSpace:plotSpace];
}
//Add legend
CPTLegend *theLegend = [CPTLegend legendWithGraph:graph];
theLegend.numberOfRows = sets.count;
theLegend.fill = [CPTFill fillWithColor:[CPTColor colorWithGenericGray:0.15]];
theLegend.borderLineStyle = barLineStyle;
theLegend.cornerRadius = 10.0;
theLegend.swatchSize = CGSizeMake(15.0, 15.0);
whiteTextStyle.fontSize = 13.0;
theLegend.textStyle = whiteTextStyle;
theLegend.rowMargin = 5.0;
theLegend.paddingLeft = 10.0;
theLegend.paddingTop = 10.0;
theLegend.paddingRight = 10.0;
theLegend.paddingBottom = 10.0;
graph.legend = theLegend;
graph.legendAnchor = CPTRectAnchorTopLeft;
graph.legendDisplacement = CGPointMake(80.0, -10.0);
}
- (void)createGraph
{
//Generate data
[self generateData];
//Generate layout
[self generateLayout];
}
- (void)dealloc
{
[data release];
[super dealloc];
}
#pragma mark - CPTPlotDataSource methods
- (NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{
return dates.count;
}
- (double)doubleForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
double num = NAN;
//X Value
if (fieldEnum == 0) {
num = index;
}
else {
double offset = 0;
if (((CPTBarPlot *)plot).barBasesVary) {
for (NSString *set in [[sets allKeys] sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)]) {
if ([plot.identifier isEqual:set]) {
break;
}
offset += [[[data objectForKey:[dates objectAtIndex:index]] objectForKey:set] doubleValue];
}
}
//Y Value
if (fieldEnum == 1) {
num = [[[data objectForKey:[dates objectAtIndex:index]] objectForKey:plot.identifier] doubleValue] + offset;
}
//Offset for stacked bar
else {
num = offset;
}
}
//NSLog(#"%# - %d - %d - %f", plot.identifier, index, fieldEnum, num);
return num;
}
#pragma mark - CPTBarPlotDelegate methods
-(void)barPlot:(CPTBarPlot *)plot barWasSelectedAtRecordIndex:(NSUInteger)index {
NSLog(#"barWasSelectedAtRecordIndex %d", index);
}
#end
to get scrolling you need to set the globalXRange on the plotspace to be the entire range, and set the xRange will be the visible area.
for example a globalXRange of 0-150, and a xRange of 0-50. then you could scroll up to view the 51-150 range.

Resources