I have the app compiling, but I see no graph.
RaceDetailView.h
#import <UIKit/UIKit.h>
#import "CorePlot-CocoaTouch.h"
#interface RaceDetailView : UIView <CPTPlotDataSource, CPTPlotSpaceDelegate>
#property (nonatomic, retain) NSArray *plotData;
#property (nonatomic, retain) NSString *title;
#property (nonatomic, retain) CPTGraphHostingView *layerHostingView;
#property CGFloat labelRotation;
- (void)setTitleDefaultsForGraph:(CPTGraph *)graph withBounds:(CGRect)bounds;
- (void)setPaddingDefaultsForGraph:(CPTGraph *)graph withBounds:(CGRect)bounds;
-(NSUInteger)numberOfRecords;
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index;
#end
RaceDetailView.m
#import "RaceDetailView.h"
#implementation RaceDetailView
#synthesize layerHostingView;
#synthesize labelRotation;
#synthesize title;
#synthesize plotData;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
title = #"my race chart";
plotData = [[NSMutableArray alloc] initWithObjects:
[NSNumber numberWithDouble:20.0],
[NSNumber numberWithDouble:30.0],
[NSNumber numberWithDouble:60.0],
nil];
CPTGraph *graph = [[[CPTXYGraph alloc] initWithFrame:frame] autorelease];
//[self addGraph:graph toHostingView:layerHostingView];
layerHostingView.hostedGraph = graph;
//[self applyTheme:theme toGraph:graph withDefault:[CPTTheme themeNamed:kCPTDarkGradientTheme]];
[graph applyTheme:[CPTTheme themeNamed:kCPTDarkGradientTheme]];
[self setTitleDefaultsForGraph:graph withBounds:frame];
[self setPaddingDefaultsForGraph:graph withBounds:frame];
// Setup scatter plot space
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)graph.defaultPlotSpace;
plotSpace.allowsUserInteraction = YES;
plotSpace.delegate = self;
// Grid line styles
CPTMutableLineStyle *majorGridLineStyle = [CPTMutableLineStyle lineStyle];
majorGridLineStyle.lineWidth = 0.75;
majorGridLineStyle.lineColor = [[CPTColor colorWithGenericGray:0.2] colorWithAlphaComponent:0.75];
CPTMutableLineStyle *minorGridLineStyle = [CPTMutableLineStyle lineStyle];
minorGridLineStyle.lineWidth = 0.25;
minorGridLineStyle.lineColor = [[CPTColor whiteColor] colorWithAlphaComponent:0.1];
CPTMutableLineStyle *redLineStyle = [CPTMutableLineStyle lineStyle];
redLineStyle.lineWidth = 10.0;
redLineStyle.lineColor = [[CPTColor redColor] colorWithAlphaComponent:0.5];
// Axes
// Label x axis with a fixed interval policy
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)graph.axisSet;
CPTXYAxis *x = axisSet.xAxis;
x.majorIntervalLength = CPTDecimalFromString(#"0.5");
x.orthogonalCoordinateDecimal = CPTDecimalFromString(#"1.0");
x.minorTicksPerInterval = 2;
x.majorGridLineStyle = majorGridLineStyle;
x.minorGridLineStyle = minorGridLineStyle;
x.title = #"X Axis";
x.titleOffset = 30.0;
x.titleLocation = CPTDecimalFromString(#"1.25");
// Label y with an automatic label policy.
CPTXYAxis *y = axisSet.yAxis;
y.labelingPolicy = CPTAxisLabelingPolicyAutomatic;
y.orthogonalCoordinateDecimal = CPTDecimalFromString(#"1.0");
y.minorTicksPerInterval = 2;
y.preferredNumberOfMajorTicks = 8;
y.majorGridLineStyle = majorGridLineStyle;
y.minorGridLineStyle = minorGridLineStyle;
y.labelOffset = 10.0;
y.title = #"Y Axis";
y.titleOffset = 30.0;
y.titleLocation = CPTDecimalFromString(#"1.0");
// Rotate the labels by 45 degrees, just to show it can be done.
labelRotation = M_PI * 0.25;
// Set axes
//graph.axisSet.axes = [NSArray arrayWithObjects:x, y, y2, nil];
graph.axisSet.axes = [NSArray arrayWithObjects:x, y, nil];
// Create a plot that uses the data source method
CPTScatterPlot *dataSourceLinePlot = [[[CPTScatterPlot alloc] init] autorelease];
dataSourceLinePlot.identifier = #"Data Source Plot";
CPTMutableLineStyle *lineStyle = [[dataSourceLinePlot.dataLineStyle mutableCopy] autorelease];
lineStyle.lineWidth = 3.0;
lineStyle.lineColor = [CPTColor greenColor];
dataSourceLinePlot.dataLineStyle = lineStyle;
dataSourceLinePlot.dataSource = self;
[graph addPlot:dataSourceLinePlot];
// Auto scale the plot space to fit the plot data
// Extend the y range by 10% for neatness
[plotSpace scaleToFitPlots:[NSArray arrayWithObjects:dataSourceLinePlot, nil]];
CPTPlotRange *xRange = plotSpace.xRange;
CPTPlotRange *yRange = plotSpace.yRange;
[xRange expandRangeByFactor:CPTDecimalFromDouble(1.3)];
[yRange expandRangeByFactor:CPTDecimalFromDouble(1.3)];
plotSpace.yRange = yRange;
// Restrict y range to a global range
CPTPlotRange *globalYRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0f)
length:CPTDecimalFromFloat(2.0f)];
plotSpace.globalYRange = globalYRange;
// set the x and y shift to match the new ranges
CGFloat length = xRange.lengthDouble;
//xShift = length - 3.0;
length = yRange.lengthDouble;
//yShift = length - 2.0;
// Add plot symbols
CPTMutableLineStyle *symbolLineStyle = [CPTMutableLineStyle lineStyle];
symbolLineStyle.lineColor = [CPTColor blackColor];
CPTPlotSymbol *plotSymbol = [CPTPlotSymbol ellipsePlotSymbol];
plotSymbol.fill = [CPTFill fillWithColor:[CPTColor blueColor]];
plotSymbol.lineStyle = symbolLineStyle;
plotSymbol.size = CGSizeMake(10.0, 10.0);
dataSourceLinePlot.plotSymbol = plotSymbol;
// Set plot delegate, to know when symbols have been touched
// We will display an annotation when a symbol is touched
dataSourceLinePlot.delegate = self;
dataSourceLinePlot.plotSymbolMarginForHitDetection = 5.0f;
// Add legend
graph.legend = [CPTLegend legendWithGraph:graph];
graph.legend.textStyle = x.titleTextStyle;
graph.legend.fill = [CPTFill fillWithColor:[CPTColor darkGrayColor]];
graph.legend.borderLineStyle = x.axisLineStyle;
graph.legend.cornerRadius = 5.0;
graph.legend.swatchSize = CGSizeMake(25.0, 25.0);
graph.legendAnchor = CPTRectAnchorBottom;
graph.legendDisplacement = CGPointMake(0.0, 12.0);
}
return self;
}
- (void)setTitleDefaultsForGraph:(CPTGraph *)graph withBounds:(CGRect)bounds
{
graph.title = title;
CPTMutableTextStyle *textStyle = [CPTMutableTextStyle textStyle];
textStyle.color = [CPTColor grayColor];
textStyle.fontName = #"Helvetica-Bold";
textStyle.fontSize = round(bounds.size.height / 20.0f);
graph.titleTextStyle = textStyle;
graph.titleDisplacement = CGPointMake(0.0f, round(bounds.size.height / 18.0f)); // Ensure that title displacement falls on an integral pixel
graph.titlePlotAreaFrameAnchor = CPTRectAnchorTop;
}
- (void)setPaddingDefaultsForGraph:(CPTGraph *)graph withBounds:(CGRect)bounds
{
float boundsPadding = round(bounds.size.width / 20.0f); // Ensure that padding falls on an integral pixel
graph.paddingLeft = boundsPadding;
if (graph.titleDisplacement.y > 0.0) {
graph.paddingTop = graph.titleDisplacement.y * 2;
}
else {
graph.paddingTop = boundsPadding;
}
graph.paddingRight = boundsPadding;
graph.paddingBottom = boundsPadding;
}
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{
return [plotData count];
}
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
NSNumber *num;
if (fieldEnum == CPTPieChartFieldSliceWidth) {
num = [plotData objectAtIndex:index];
}
else {
return [NSNumber numberWithInt:index];
}
return num;
}
#end
Edit: You may note that this is from the CorePlot example SimpleScatterPlot.
Why is this code in a UIView? This code normally resides in a view controller (UIViewController). The Plot Gallery app that you pulled the example from is a little more complicated because it uses the plots in multiple places--in the main view area and also to make the thumbnail images for the list or browser view.
Do you ever set the layerHostingView? Is it in the view hierarchy and visible?
Check your datasource as #danielbeard suggested. The correct field names for scatter plots are CPTScatterPlotFieldX and CPTScatterPlotFieldY.
You are setting up a scatter plot, then in the numberForPlot method you are asking for the CPTPieChartFieldSliceWidth, is this intended? Can you see grid lines at all, or is the whole graph area just blank?
Related
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];
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.
I've been trying to make a horizontal bar chart using CorePlot in iOS.
I'm trying to find documentation but I cant seem to find anything good for this area. What else do I need to change if I make the bars horizontal? Is it simply a display things, or do I need to change data too?
These would be
xRange, yRange
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index implementation
Here's what I have so far...
#pragma mark -
#pragma mark - Chart behavior
-(void)initPlot {
[self configureGraph];
[self configurePlots];
[self configureAxes];
}
-(void)configureGraph {
CPTGraph *countryGraph = [[CPTXYGraph alloc] initWithFrame:self.countryGraph.bounds];
CPTGraph *timeZoneGraph = [[CPTXYGraph alloc] initWithFrame:self.timeZoneGraph.bounds];
countryGraph.plotAreaFrame.masksToBorder = NO;
timeZoneGraph.plotAreaFrame.masksToBorder = NO;
self.countryGraph.hostedGraph = countryGraph;
self.timeZoneGraph.hostedGraph = timeZoneGraph;
CPTXYPlotSpace *countryPlotSpace = (CPTXYPlotSpace *) countryGraph.defaultPlotSpace;
countryPlotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0) length:CPTDecimalFromFloat([self.countryData[0] count])];
countryPlotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0) length:CPTDecimalFromFloat([self.countryData count]*50)];
CPTXYPlotSpace *timeZonePlotSpace = (CPTXYPlotSpace *) timeZoneGraph.defaultPlotSpace;
timeZonePlotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0) length:CPTDecimalFromFloat([self.timeZoneData[0] count])];
timeZonePlotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0) length:CPTDecimalFromFloat([self.timeZoneData count]*50)];
}
-(void)configurePlots {
CPTBarPlot *countryPlot = [CPTBarPlot tubularBarPlotWithColor:[CPTColor colorWithComponentRed:19/255.0 green:221/255.0 blue:187/255.0 alpha:1] horizontalBars:YES];
countryPlot.identifier = #"CountryPlot";
CPTBarPlot *timeZonePlot = [CPTBarPlot tubularBarPlotWithColor:[CPTColor colorWithComponentRed:30/255.0 green:33/255.0 blue:36/255.0 alpha:1] horizontalBars:YES];
timeZonePlot.identifier = #"TimeZonePlot";
CPTMutableLineStyle *barLineStyle = [[CPTMutableLineStyle alloc] init];
barLineStyle.lineColor = [CPTColor whiteColor];
barLineStyle.lineWidth = 1.0;
CPTGraph *countryGraph = self.countryGraph.hostedGraph;
CPTGraph *timeZoneGraph = self.timeZoneGraph.hostedGraph;
countryPlot.dataSource = self;
countryPlot.delegate = self;
countryPlot.barWidth = CPTDecimalFromDouble(20);
countryPlot.baseValue = CPTDecimalFromString(#"0");
countryPlot.lineStyle = barLineStyle;
countryPlot.barOffset = CPTDecimalFromFloat(0.25f);
[countryGraph addPlot:countryPlot toPlotSpace:countryGraph.defaultPlotSpace];
timeZonePlot.dataSource = self;
timeZonePlot.delegate = self;
timeZonePlot.baseValue = CPTDecimalFromString(#"0");
timeZonePlot.barWidth = CPTDecimalFromDouble(20);
timeZonePlot.lineStyle = barLineStyle;
timeZonePlot.barOffset = CPTDecimalFromFloat(0.25f);
[timeZoneGraph addPlot:timeZonePlot toPlotSpace:timeZoneGraph.defaultPlotSpace];
}
-(void)configureAxes {
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] colorWithAlphaComponent:1];
CPTXYAxisSet *countryAxisSet = (CPTXYAxisSet *) self.countryGraph.hostedGraph.axisSet;
CPTXYAxis *x = countryAxisSet.xAxis;
x.labelingPolicy = CPTAxisLabelingPolicyNone;
x.axisLineStyle = axisLineStyle;
x.majorIntervalLength = CPTDecimalFromString(#"20");
CPTXYAxis *y = countryAxisSet.yAxis;
y.labelingPolicy = CPTAxisLabelingPolicyNone;
y.axisLineStyle = axisLineStyle;
y.majorIntervalLength = CPTDecimalFromString(#"50");
CPTXYAxisSet *timeZoneAxisSet = (CPTXYAxisSet *) self.timeZoneGraph.hostedGraph.axisSet;
CPTXYAxis *x2 = timeZoneAxisSet.xAxis;
x2.labelingPolicy = CPTAxisLabelingPolicyNone;
x2.axisLineStyle = axisLineStyle;
x2.majorIntervalLength = CPTDecimalFromString(#"20");
CPTXYAxis *y2 = timeZoneAxisSet.yAxis;
y2.labelingPolicy = CPTAxisLabelingPolicyNone;
y2.axisLineStyle = axisLineStyle;
y2.majorIntervalLength = CPTDecimalFromString(#"50");
}
#pragma mark - CPTPlotDataSource methods
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot {
NSUInteger num = 0;
if ([plot.identifier isEqual:#"CountryPlot"]) {
num = self.countryData.count;
} else {
num = self.timeZoneData.count;
}
return num;
}
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index {
NSNumber *num = #0;
switch (fieldEnum) {
case CPTBarPlotFieldBarTip:
if ([plot.identifier isEqual:#"CountryPlot"]) {
num = [NSNumber numberWithInteger:[self.countryData[index] count]];
} else {
num = [NSNumber numberWithInteger:[self.timeZoneData[index] count]];
}
break;
default:
num = [NSNumber numberWithInteger:index];
break;
}
return num;
}
Here's what it makes
And I'd prefer that the bars would be stacked up on top of each other with a small separation.... so what have I missed?
Set barsAreHorizontal to YES on the bar plot to make horizontal bars. Everything else is the same except the bar locations are now on the y-axis and the bar tip and base values are on the x-axis.
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 *)];
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.