I have created a simple implementation of the CorePlot framework. The chart shows up fine, but there is no line plotted. I have tried logging out my sample values and indeed do have data. Any and all input on why the line of plotted data does not show up would be appreciated!
Header File:
#import <UIKit/UIKit.h>
#import "PresentedViewControllerDelegate.h"
#import "CorePlot-CocoaTouch.h"
#define NUM_SAMPLES 30
#interface DeviceDetailModal : UIViewController <PresentedViewControllerDelegate, UIWebViewDelegate, UITableViewDataSource, UITableViewDelegate, CPTPlotDataSource>{
CPTXYGraph *graph;
NSMutableArray *samples;
double xxx[NUM_SAMPLES];
double yyy1[NUM_SAMPLES];
}
#property (weak, nonatomic) IBOutlet UITableView *tableView;
#property (nonatomic, weak) id <PresentedViewControllerDelegate> delegate;
#end
Main File
#import <Foundation/Foundation.h>
#import "DeviceDetailModal.h"
#import "DetailCell.h"
#import "CorePlot-CocoaTouch.h"
#define START_POINT 0 // Start at origin
#define END_POINT 15.0 // TODO time is 15 seconds
#define X_VAL #"X_VAL"
#define Y_VAL #"Y_VAL"
#implementation DeviceDetailModal
-(void)viewDidLoad{
UIBarButtonItem *closeButton = [[UIBarButtonItem alloc] initWithTitle:#"Close" style:UIBarButtonItemStylePlain target:self action:#selector(closeView)];
self.navigationItem.leftBarButtonItem = closeButton;
[[UIBarButtonItem appearance] setTintColor:[UIColor lightGrayColor]];
[[UINavigationBar appearance] setBarTintColor:[UIColor blackColor]];
self.tableView.layer.cornerRadius = 10.0;
self.tableView.layer.borderWidth = 0.7;
self.tableView.layer.borderColor = [UIColor whiteColor].CGColor;
[self generateDataSamples];
NSNumber *xAxisStart = [NSNumber numberWithDouble:START_POINT];
NSNumber *xAxisLength = [NSNumber numberWithDouble:END_POINT - START_POINT];
double maxY = [[samples valueForKeyPath:#"#max.Y_VAL"] doubleValue];
NSNumber *yAxisStart = [NSNumber numberWithDouble:-maxY];
NSNumber *yAxisLength = [NSNumber numberWithDouble:2 *maxY];
CGRect hostingRect = CGRectMake(20, 330, 335, 347);
CPTGraphHostingView *hostingView = [[CPTGraphHostingView alloc] initWithFrame:hostingRect];
[self.view addSubview:hostingView];
graph = [[CPTXYGraph alloc] initWithFrame:hostingView.bounds];
hostingView.hostedGraph = graph;
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)graph.defaultPlotSpace;
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:xAxisStart
length:xAxisLength];
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:yAxisStart
length:yAxisLength];
CPTScatterPlot *dataSourceLinePlot = [[CPTScatterPlot alloc] init];
dataSourceLinePlot.delegate = self;
// LINE STYLE
CPTMutableLineStyle *mainPlotLineStyle = [[dataSourceLinePlot dataLineStyle] mutableCopy];
[mainPlotLineStyle setLineWidth:2.0f];
[mainPlotLineStyle setLineColor:[CPTColor colorWithCGColor:[[UIColor whiteColor] CGColor]]];
[dataSourceLinePlot setDataLineStyle:mainPlotLineStyle];
// AXIS STYLE
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)[graph axisSet];
CPTXYAxis *xAxis = [axisSet xAxis];
CPTXYAxis *yAxis = [axisSet yAxis];
CPTMutableLineStyle *axisLineStyle = [CPTMutableLineStyle lineStyle];
[axisLineStyle setLineWidth:1];
[axisLineStyle setLineColor:[CPTColor colorWithCGColor:[[UIColor whiteColor] CGColor]]];
[xAxis setAxisLineStyle:axisLineStyle];
[xAxis setMajorTickLineStyle:axisLineStyle];
[yAxis setAxisLineStyle:axisLineStyle];
[yAxis setMajorTickLineStyle:axisLineStyle];
[graph addPlot:dataSourceLinePlot];
NSLog(#"PLOT: %#",dataSourceLinePlot);
[graph reloadData];
}
-(void)generateDataSamples{
double length = (END_POINT - START_POINT);
double delta = length / (NUM_SAMPLES -1);
samples = [[NSMutableArray alloc] initWithCapacity:NUM_SAMPLES];
for (int i = 0; i < NUM_SAMPLES; i++) {
double x = START_POINT + (delta * i);
//X^2
double y = x * x;
NSDictionary *sample = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithDouble:x],X_VAL,
[NSNumber numberWithDouble:y],Y_VAL,
nil];
NSLog(#"SAMPLE: %#", sample);
[samples addObject:sample];
}
[graph reloadData];
}
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot{
return NUM_SAMPLES;
}
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index{
NSDictionary *sample = [samples objectAtIndex:index];
if (fieldEnum == CPTScatterPlotFieldX) {
return [sample valueForKey:X_VAL];
}else{
return [sample valueForKey:Y_VAL];
}
}
Found the problem! The data source for the plot was not set, I had to do:
dataSourceLinePlot.dataSource = self;
I found this out when my numberOfRecordsPerPlot method was never being called.
The default background fill is white and it doesn't look like you've changed it. The plot line is drawn with a white color so it doesn't show up on the white background. Try using the default line style or this:
mainPlotLineStyle.lineColor = [CPTColor blackColor];
Related
I have an implementation of CorePlot in my project and though I have no relevant errors or warnings in Xcode, have been unsuccessful in getting the plot to show up in the graph. The axis and chart show up fine, but no bars in the graph.
Any help or advice would be appreciated!
Header File
#import <UIKit/UIKit.h>
#import "PresentedViewControllerDelegate.h"
#import <CorePlot/ios/CorePlot.h>
#interface DeviceDetailModal : UIViewController <PresentedViewControllerDelegate, UIWebViewDelegate, UITableViewDataSource, UITableViewDelegate, CPTPlotDataSource,CPTBarPlotDelegate>{
CPTGraph *graph;
}
#property (weak, nonatomic) IBOutlet UITableView *tableView;
#property (nonatomic, weak) id <PresentedViewControllerDelegate> delegate;
#property (strong,nonatomic) NSArray *dataSet;
#property (nonatomic, strong) CPTBarPlot *aaplPlot;
#property (nonatomic, strong) CPTPlotSpaceAnnotation *priceAnnotation;
#end
Main File
#import <Foundation/Foundation.h>
#import "DeviceDetailModal.h"
#import "DetailCell.h"
#import <CorePlot/ios/CorePlot.h>
#import "Constants.h"
#implementation DeviceDetailModal
NSString * const CPDTickerSymbolAAPL = #"AAPL";
CGFloat const CPDBarWidth = 0.25f;
CGFloat const CPDBarInitialX = 0.25f;
#synthesize aaplPlot = aaplPlot_;
-(void)viewDidLoad{
[super viewDidLoad];
[self.view setBackgroundColor:[UIColor colorWithRed:0.03 green:0.06 blue:0.10 alpha:1.0]];
UIBarButtonItem *closeButton = [[UIBarButtonItem alloc] initWithTitle:#"Close" style:UIBarButtonItemStylePlain target:self action:#selector(closeView)];
self.navigationItem.leftBarButtonItem = closeButton;
[[UIBarButtonItem appearance] setTintColor:[UIColor lightGrayColor]];
[[UINavigationBar appearance] setBarTintColor:[UIColor blackColor]];
self.tableView.layer.cornerRadius = 10.0;
self.tableView.layer.borderWidth = 0.7;
self.tableView.layer.borderColor = [UIColor whiteColor].CGColor;
self.tableView.opaque = NO;
self.tableView.backgroundColor = [UIColor clearColor];
self.tableView.backgroundView = nil;
self.dataSet = [[NSArray alloc] init];
self.dataSet = [NSArray arrayWithObjects:
[NSDecimalNumber numberWithFloat:571.70],
[NSDecimalNumber numberWithFloat:560.28],
[NSDecimalNumber numberWithFloat:610.00],
[NSDecimalNumber numberWithFloat:607.70],
[NSDecimalNumber numberWithFloat:603.00],
nil];
[self configureGraph];
[graph reloadData];
}
-(void)configureGraph {
CGRect hostingRect = CGRectMake(20, 350, 335, 310);
CPTGraphHostingView *hostingView = [[CPTGraphHostingView alloc] initWithFrame:hostingRect];
[self.view addSubview:hostingView];
[hostingView setBackgroundColor:[UIColor colorWithRed:0.03 green:0.06 blue:0.10 alpha:1.0]];
hostingView.layer.cornerRadius = 10.0;
hostingView.layer.borderWidth = 0.7;
hostingView.layer.borderColor = [UIColor whiteColor].CGColor;
graph = [[CPTXYGraph alloc] initWithFrame:hostingView.bounds];
hostingView.hostedGraph = graph;
[[graph defaultPlotSpace] setAllowsUserInteraction:TRUE];
// 1 - Create the graph
graph.plotAreaFrame.masksToBorder = NO;
// 2 - Configure the graph
//[graph applyTheme:[CPTTheme themeNamed:kCPTPlainBlackTheme]];
graph.paddingBottom = 30.0f;
graph.paddingLeft = 30.0f;
graph.paddingTop = -1.0f;
graph.paddingRight = -5.0f;
// 3 - Set up styles
CPTMutableTextStyle *titleStyle = [CPTMutableTextStyle textStyle];
titleStyle.color = [CPTColor whiteColor];
titleStyle.fontName = #"Helvetica-Bold";
titleStyle.fontSize = 16.0f;
// 4 - Set up title
NSString *title = #"Portfolio Prices: April 23 - 27, 2012";
graph.title = title;
graph.titleTextStyle = titleStyle;
graph.titlePlotAreaFrameAnchor = CPTRectAnchorTop;
graph.titleDisplacement = CGPointMake(0.0f, -16.0f);
// 5 - Set up plot space
CGFloat xMin = 0.0f;
CGFloat xMax = 7;
CGFloat yMin = 0.0f;
CGFloat yMax = 800.0f; // should determine dynamically based on max price
NSNumber *xAxisStart = [NSNumber numberWithFloat:xMin];
NSNumber *xAxisLength = [NSNumber numberWithDouble:xMax];
NSNumber *yAxisStart = [NSNumber numberWithFloat:yMin];
NSNumber *yAxisLength = [NSNumber numberWithDouble:yMax];
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *) graph.defaultPlotSpace;
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:xAxisStart length:xAxisLength];
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:yAxisStart length:yAxisLength];
// 1 - Set up the three plots
self.aaplPlot = [CPTBarPlot tubularBarPlotWithColor:[CPTColor redColor] horizontalBars:NO];
self.aaplPlot.identifier = CPDTickerSymbolAAPL;
// 2 - Set up line style
CPTMutableLineStyle *barLineStyle = [[CPTMutableLineStyle alloc] init];
barLineStyle.lineColor = [CPTColor lightGrayColor];
barLineStyle.lineWidth = 0.5;
// 3 - Add plots to graph
graph = hostingView.hostedGraph;
CGFloat barX = CPDBarInitialX;
NSArray *plots = [NSArray arrayWithObjects:self.aaplPlot, nil];
for (CPTBarPlot *plot in plots) {
plot.dataSource = self;
plot.delegate = self;
plot.barWidth = [NSNumber numberWithFloat:CPDBarWidth];
plot.barOffset = [NSNumber numberWithFloat:barX];
plot.lineStyle = barLineStyle;
[graph addPlot:plot toPlotSpace:graph.defaultPlotSpace];
barX += CPDBarWidth;
}
// 1 - Configure 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] colorWithAlphaComponent:1];
// 2 - Get the graph's axis set
CPTXYAxisSet *axisSet = (CPTXYAxisSet *) hostingView.hostedGraph.axisSet;
// 3 - Configure the x-axis
axisSet.xAxis.labelingPolicy = CPTAxisLabelingPolicyNone;
axisSet.xAxis.title = #"Days of Week (Mon - Fri)";
axisSet.xAxis.titleTextStyle = axisTitleStyle;
axisSet.xAxis.titleOffset = 10.0f;
axisSet.xAxis.axisLineStyle = axisLineStyle;
// 4 - Configure the y-axis
axisSet.yAxis.labelingPolicy = CPTAxisLabelingPolicyNone;
axisSet.yAxis.title = #"Price";
axisSet.yAxis.titleTextStyle = axisTitleStyle;
axisSet.yAxis.titleOffset = 5.0f;
axisSet.yAxis.axisLineStyle = axisLineStyle;
}
#pragma mark - CPTPlotDataSource methods
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot {
return [self.dataSet count];
}
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index {
NSLog(#"DATA: %#",[self.dataSet objectAtIndex:index]);
return [self.dataSet objectAtIndex:index];
}
#pragma mark - CPTBarPlotDelegate methods
-(void)barPlot:(CPTBarPlot *)plot barWasSelectedAtRecordIndex:(NSUInteger)index {
// 1 - Is the plot hidden?
if (plot.isHidden == YES) {
return;
}
// 2 - Create style, if necessary
static CPTMutableTextStyle *style = nil;
if (!style) {
style = [CPTMutableTextStyle textStyle];
style.color= [CPTColor yellowColor];
style.fontSize = 16.0f;
style.fontName = #"Helvetica-Bold";
}
// 3 - Create annotation, if necessary
NSNumber *price = [self numberForPlot:plot field:CPTBarPlotFieldBarTip recordIndex:index];
if (!self.priceAnnotation) {
NSNumber *x = [NSNumber numberWithInt:0];
NSNumber *y = [NSNumber numberWithInt:0];
NSArray *anchorPoint = [NSArray arrayWithObjects:x, y, nil];
self.priceAnnotation = [[CPTPlotSpaceAnnotation alloc] initWithPlotSpace:plot.plotSpace anchorPlotPoint:anchorPoint];
}
// 4 - Create number formatter, if needed
static NSNumberFormatter *formatter = nil;
if (!formatter) {
formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:2];
}
// 5 - Create text layer for annotation
NSString *priceValue = [formatter stringFromNumber:price];
CPTTextLayer *textLayer = [[CPTTextLayer alloc] initWithText:priceValue style:style];
self.priceAnnotation.contentLayer = textLayer;
// 6 - Get plot index based on identifier
NSInteger plotIndex = 0;
if ([plot.identifier isEqual:CPDTickerSymbolAAPL] == YES) {
plotIndex = 0;
}
// 7 - Get the anchor point for annotation
CGFloat x = index + CPDBarInitialX + (plotIndex * CPDBarWidth);
NSNumber *anchorX = [NSNumber numberWithFloat:x];
CGFloat y = [price floatValue] + 40.0f;
NSNumber *anchorY = [NSNumber numberWithFloat:y];
self.priceAnnotation.anchorPlotPoint = [NSArray arrayWithObjects:anchorX, anchorY, nil];
// 8 - Add the annotation
[plot.graph.plotAreaFrame.plotArea addAnnotation:self.priceAnnotation];
}
#end
Plot ranges are given as a starting location and length. In your case, make the starting location the min value and the length max - min. Right now it's ok since the min is zero, but the length will be wrong if you ever change the min values.
The -numberForPlot:field:recordIndex: datasource method must check the field parameter and return the correct value for the field. Return the index parameter value for the CPTBarPlotFieldBarLocation field. Return the value from the dataSet array for the CPTBarPlotFieldBarTip field.
I would like to be able to add a legend to a graph slice. How can I do this?
I tried to implement the following two methods but I don't think is right;
- (NSString *) legendTitleForPieChart:(CPTPieChart *)pieChart
recordIndex:(NSUInteger)idx{
return #"Legend";
}
- (NSAttributedString *) attributedLegendTitleForPieChart: (CPTPieChart *) pieChart
recordIndex: (NSUInteger) idxv{
return [[NSAttributedString alloc] initWithString:#"Attributed"];
}
Here is the official CorePlot protocol documentation:
https://core-plot.googlecode.com/hg/documentation/html/iOS/protocol_c_p_t_pie_chart_data_source-p.html#a6a85e1a9e613eb65267abfb8a884434a
EDIT: my code
// .h
#interface MyViewController : UIViewController<CPTPlotSpaceDelegate,CPTPieChartDelegate,CPTLegendDelegate,CPTPlotDataSource>
- (void) initializeAll;
- (id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil data:(NSMutableArray*)dataPoints;
// .m
#import “MyViewController.h"
#import <QuartzCore/QuartzCore.h>
#interface MyViewController ()
#property (weak, nonatomic) IBOutlet CPTGraphHostingView * pieChartgraphHostView;
#property (strong, nonatomic) CPTGraph* pieChartGraph;
#property (strong, nonatomic) CPTPieChart* pieChart;
#end
#implementation MyViewController
#synthesize data;
#synthesize pieChart, pieChartGraph;
- (id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil data:(NSMutableArray*)dataPoints{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.data = dataPoints;
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
[self initializeGraph];
[self updateViewData];
[self configureChart];
}
- (void) initializeGraph{
if (self.data == nil) {
NSLog(#"Error, should not use this without assigning data");
}
// Create a CPTGraph object and add to hostView
self.graph = [[CPTXYGraph alloc] initWithFrame:self.graphHostView.bounds];
self.graphHostView.hostedGraph = self.graph;
////////////////////
CPTMutableTextStyle *titleStyle = [CPTMutableTextStyle textStyle];
titleStyle.color = [CPTColor blackColor];
titleStyle.fontName = #"Helvetica";
titleStyle.fontSize = 12.0f;
// Axes
// Label x axis with a fixed interval policy
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)self.graph.axisSet;
CPTXYAxis *x = axisSet.xAxis;
x.separateLayers = NO;
x.title = #"X Axis";
x.titleTextStyle = titleStyle;
x.delegate = self;
CPTXYAxis *y = axisSet.yAxis;
y.labelingPolicy = CPTAxisLabelingPolicyAutomatic;
y.separateLayers = YES;
y.majorTickLocations = [NSSet setWithObjects:
[NSDecimalNumber numberWithDouble:0],
[NSDecimalNumber numberWithDouble:300],
nil];
y.title = #"Y Axis";
y.titleTextStyle = titleStyle;
y.delegate = self;
CPTFill *whitebandFill = [CPTFill fillWithColor:[[CPTColor whiteColor] colorWithAlphaComponent:0.5]];
CPTFill *greenbandFill = [CPTFill fillWithColor:[[CPTColor greenColor] colorWithAlphaComponent:0.5]];
CPTFill *redbandFill = [CPTFill fillWithColor:[[CPTColor redColor] colorWithAlphaComponent:0.75]];
[y addBackgroundLimitBand:[CPTLimitBand limitBandWithRange:[CPTPlotRange plotRangeWithLocationDecimal:CPTDecimalFromDouble(0.0) lengthDecimal:CPTDecimalFromDouble(500.0)] fill:whitebandFill]];
[y addBackgroundLimitBand:[CPTLimitBand limitBandWithRange:[CPTPlotRange plotRangeWithLocationDecimal:CPTDecimalFromDouble(500.0) lengthDecimal:CPTDecimalFromDouble(750.0)] fill:greenbandFill]];
[y addBackgroundLimitBand:[CPTLimitBand limitBandWithRange:[CPTPlotRange plotRangeWithLocationDecimal:CPTDecimalFromDouble(750.0) lengthDecimal:CPTDecimalFromDouble(1024.0)] fill:redbandFill]];
// Add the y2 axis to the axis set
self.graph.axisSet.axes = #[x, y];
/////////////////////
// Get the (default) plotspace from the graph so we can set its x/y ranges
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *) self.graph.defaultPlotSpace;
// Note that these CPTPlotRange are defined by START and LENGTH (not START and END) !!
[plotSpace setYRange: [CPTPlotRange plotRangeWithLocation:[NSNumber numberWithInt:0] length:[NSNumber numberWithInt:1024]]];
NSLog(#"creating x range for %lu data points", (unsigned long)[self.data count]);
[plotSpace setXRange: [CPTPlotRange plotRangeWithLocation:[NSNumber numberWithInt:0] length:[NSNumber numberWithInt:[self.data count]]]];
// Create the plot (we do not define actual x/y values yet, these will be supplied by the datasource...)
self.plot = [[CPTScatterPlot alloc] initWithFrame:CGRectZero];
// Let's keep it simple and let this class act as datasource (therefore we implemtn <CPTPlotDataSource>)
self.plot.dataSource = self;
self.plot.delegate = self;
// Finally, add the created plot to the default plot space of the CPTGraph object we created before
[self.graph addPlot:self.plot toPlotSpace:self.graph.defaultPlotSpace];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)configureChart {
// 1 - Get reference to graph
pieChartGraph = [[CPTXYGraph alloc] initWithFrame:self.pieChartgraphHostView.bounds];
self.pieChartgraphHostView.hostedGraph = pieChartGraph;
pieChartGraph.plotAreaFrame.masksToBorder = NO;
pieChartGraph.axisSet = nil;
pieChart.title = #"My pie chart";
// 2 - Create chart
pieChart = [[CPTPieChart alloc] init];
pieChart.dataSource = self;
pieChart.delegate = self;
pieChart.pieRadius = (self.pieChartgraphHostView.bounds.size.height * 0.9) / 2;
pieChartGraph.delegate = self;
pieChart.identifier = pieChartGraph.title;
pieChart.startAngle = CPTFloat(M_PI_4);
pieChart.sliceDirection = CPTPieDirectionClockwise;
pieChart.borderLineStyle = [CPTLineStyle lineStyle];
// 3 - Create gradient
CPTGradient *overlayGradient = [[CPTGradient alloc] init];
overlayGradient.gradientType = CPTGradientTypeRadial;
overlayGradient = [overlayGradient addColorStop:[[CPTColor blackColor] colorWithAlphaComponent:0.0] atPosition:0.9];
overlayGradient = [overlayGradient addColorStop:[[CPTColor blackColor] colorWithAlphaComponent:0.4] atPosition:1.0];
pieChart.overlayFill = [CPTFill fillWithGradient:overlayGradient];
// 4 - Add chart to graph
pieChart.pieRadius = pieChart.pieRadius / 2.3;
[pieChartGraph addPlot:pieChart];
self.dataForChart = [#[#20.0, #30.0, #25.0, #25.0] mutableCopy];
}
-(void)setRoundedView:(UIView *)roundedView toDiameter:(float)newSize;
{
CGPoint saveCenter = roundedView.center;
CGRect newFrame = CGRectMake(roundedView.frame.origin.x, roundedView.frame.origin.y, newSize, newSize);
roundedView.frame = newFrame;
roundedView.layer.cornerRadius = newSize / 2.0;
roundedView.center = saveCenter;
}
-(void)configureLegend {
// 1 - Get graph instance
CPTGraph *graph = self.graphHostView.hostedGraph;
// 2 - Create legend
CPTLegend *theLegend = [CPTLegend legendWithGraph:graph];
// 3 - Configure legen
theLegend.numberOfColumns = 1;
theLegend.fill = [CPTFill fillWithColor:[CPTColor whiteColor]];
theLegend.borderLineStyle = [CPTLineStyle lineStyle];
theLegend.cornerRadius = 5.0;
// 4 - Add legend to graph
graph.legend = theLegend;
graph.legendAnchor = CPTRectAnchorRight;
CGFloat legendPadding = -(self.view.bounds.size.width / 8);
graph.legendDisplacement = CGPointMake(legendPadding, 0.0);
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
#pragma mark -
#pragma mark Plot Data Source Methods
- (NSString *) legendTitleForPieChart:(CPTPieChart *)pieChart
recordIndex:(NSUInteger)idx{
return #"Legend";
}
/**
- (NSAttributedString *) attributedLegendTitleForPieChart: (CPTPieChart *) pieChart
recordIndex: (NSUInteger) idxv{
return [[NSAttributedString alloc] initWithString:#"Attributed"];
}**/
-(NSAttributedString *)attributedLegendTitleForPieChart:(CPTPieChart *)pieChart recordIndex:(NSUInteger)index
{
#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
UIColor *sliceColor = [CPTPieChart defaultPieSliceColorForIndex:index].uiColor;
UIFont *labelFont = [UIFont fontWithName:#"Helvetica" size:12.0 * CPTFloat(0.5)];
#else
NSColor *sliceColor = [CPTPieChart defaultPieSliceColorForIndex:index].nsColor;
NSFont *labelFont = [NSFont fontWithName:#"Helvetica" size:12.0 * CPTFloat(0.5)];
#endif
NSMutableAttributedString *title = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:#"Pie Slice %lu", (unsigned long)index]];
[title addAttribute:NSForegroundColorAttributeName
value:sliceColor
range:NSMakeRange(4, 5)];
[title addAttribute:NSFontAttributeName
value:labelFont
range:NSMakeRange(0, title.length)];
return title;
}
#end
Title, legend and labels won't show.
You only need one of those methods. Use the attributed title if you need styled text like in the example image, otherwise either method will work. These methods should be implemented in the plot's datasource.
This core plot is created from : http://codejunkster.wordpress.com/2011/11/23/core-plot-2-bar-plot/#comment-85 . I have created 2 app with the same code, one for iPhone and another for iPad.The iphone app works perfectly but the ipad app displays x-coordinates and y-coordinated along with the title not the columns I don’t have any idea how to fix it.Please help me.It would be a great help.Using Xcode 4.5.2 ios6 .Thanks in Advance.
BarPlotViewController.h
#import <UIKit/UIKit.h>
#import "CorePlot-CocoaTouch.h"
#interface BarPlotViewController : UIViewController
<CPTBarPlotDataSource, CPTBarPlotDelegate>
#property (nonatomic, retain) NSMutableArray *data;
#property (nonatomic, retain) CPTGraphHostingView *hostingView;
#property (nonatomic, retain) CPTXYGraph *graph;
- (void) generateBarPlot;
#end
BarPlotViewController.m
#import "BarPlotViewController.h"
#interface BarPlotViewController ()
#end
#implementation BarPlotViewController
#define BAR_POSITION #"POSITION"
#define BAR_HEIGHT #"HEIGHT"
#define COLOR #"COLOR"
#define CATEGORY #"CATEGORY"
#define AXIS_START 0
#define AXIS_END 50
#synthesize data;
#synthesize graph;
#synthesize hostingView;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.data = [NSMutableArray array];
int bar_heights[] = {20,30,10,40};
UIColor *colors[] = {
[UIColor redColor],
[UIColor blueColor],
[UIColor orangeColor],
[UIColor purpleColor]};
NSString *categories[] = {#"Plain Milk", #"Milk + Caramel", #"White", #"Dark"};
for (int i = 0; i < 4 ; i++){
double position = i*10; //Bars will be 10 pts away from each other
double height = bar_heights[i];
NSDictionary *bar = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithDouble:position],BAR_POSITION,
[NSNumber numberWithDouble:height],BAR_HEIGHT,
colors[i],COLOR,
categories[i],CATEGORY,
nil];
[self.data addObject:bar];
}
[self generateBarPlot];
}
return self;
}
- (void)generateBarPlot
{
//Create host view
self.hostingView = [[CPTGraphHostingView alloc]
initWithFrame:[[UIScreen mainScreen]bounds]];
[self.view addSubview:self.hostingView];
//Create graph and set it as host view's graph
self.graph = [[CPTXYGraph alloc] initWithFrame:self.hostingView.bounds];
[self.hostingView setHostedGraph:self.graph];
//set graph padding and theme
self.graph.plotAreaFrame.paddingTop = 20.0f;
self.graph.plotAreaFrame.paddingRight = 20.0f;
self.graph.plotAreaFrame.paddingBottom = 70.0f;
self.graph.plotAreaFrame.paddingLeft = 70.0f;
[self.graph applyTheme:[CPTTheme themeNamed:kCPTDarkGradientTheme]];
//set axes ranges
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:
CPTDecimalFromFloat(AXIS_START)
length:CPTDecimalFromFloat((AXIS_END - AXIS_START)+5)];
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:
CPTDecimalFromFloat(AXIS_START)
length:CPTDecimalFromFloat((AXIS_END - AXIS_START)+5)];
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)self.graph.axisSet;
//set axes' title, labels and their text styles
CPTMutableTextStyle *textStyle = [CPTMutableTextStyle textStyle];
textStyle.fontName = #"Helvetica";
textStyle.fontSize = 14;
textStyle.color = [CPTColor whiteColor];
axisSet.xAxis.title = #"CHOCOLATE";
axisSet.yAxis.title = #"AWESOMENESS";
axisSet.xAxis.titleTextStyle = textStyle;
axisSet.yAxis.titleTextStyle = textStyle;
axisSet.xAxis.titleOffset = 30.0f;
axisSet.yAxis.titleOffset = 40.0f;
axisSet.xAxis.labelTextStyle = textStyle;
axisSet.xAxis.labelOffset = 3.0f;
axisSet.yAxis.labelTextStyle = textStyle;
axisSet.yAxis.labelOffset = 3.0f;
//set axes' line styles and interval ticks
CPTMutableLineStyle *lineStyle = [CPTMutableLineStyle lineStyle];
lineStyle.lineColor = [CPTColor whiteColor];
lineStyle.lineWidth = 3.0f;
axisSet.xAxis.axisLineStyle = lineStyle;
axisSet.yAxis.axisLineStyle = lineStyle;
axisSet.xAxis.majorTickLineStyle = lineStyle;
axisSet.yAxis.majorTickLineStyle = lineStyle;
axisSet.xAxis.majorIntervalLength = CPTDecimalFromFloat(5.0f);
axisSet.yAxis.majorIntervalLength = CPTDecimalFromFloat(5.0f);
axisSet.xAxis.majorTickLength = 7.0f;
axisSet.yAxis.majorTickLength = 7.0f;
axisSet.xAxis.minorTickLineStyle = lineStyle;
axisSet.yAxis.minorTickLineStyle = lineStyle;
axisSet.xAxis.minorTicksPerInterval = 1;
axisSet.yAxis.minorTicksPerInterval = 1;
axisSet.xAxis.minorTickLength = 5.0f;
axisSet.yAxis.minorTickLength = 5.0f;
// Create bar plot and add it to the graph
CPTBarPlot *plot = [[CPTBarPlot alloc] init] ;
plot.dataSource = self;
plot.delegate = self;
plot.barWidth = [[NSDecimalNumber decimalNumberWithString:#"5.0"]
decimalValue];
plot.barOffset = [[NSDecimalNumber decimalNumberWithString:#"10.0"]
decimalValue];
plot.barCornerRadius = 5.0;
// Remove bar outlines
CPTMutableLineStyle *borderLineStyle = [CPTMutableLineStyle lineStyle];
borderLineStyle.lineColor = [CPTColor clearColor];
plot.lineStyle = borderLineStyle;
// Identifiers are handy if you want multiple plots in one graph
plot.identifier = #"chocoplot";
[self.graph addPlot:plot];
}
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{
if ( [plot.identifier isEqual:#"chocoplot"] )
return [self.data count];
return 0;
}
-(CPTLayer *)dataLabelForPlot:(CPTPlot *)plot recordIndex:(NSUInteger)index
{
if ( [plot.identifier isEqual: #"chocoplot"] )
{
CPTMutableTextStyle *textStyle = [CPTMutableTextStyle textStyle];
textStyle.fontName = #"Helvetica";
textStyle.fontSize = 14;
textStyle.color = [CPTColor whiteColor];
NSDictionary *bar = [self.data objectAtIndex:index];
CPTTextLayer *label = [[CPTTextLayer alloc] initWithText:[NSString stringWithFormat:#"%#", [bar valueForKey:#"CATEGORY"]]];
label.textStyle =textStyle;
return label;
}
CPTTextLayer *defaultLabel = [[CPTTextLayer alloc] initWithText:#"Label"];
return defaultLabel;
}
-(CPTFill *)barFillForBarPlot:(CPTBarPlot *)barPlot
recordIndex:(NSUInteger)index
{
if ( [barPlot.identifier isEqual:#"chocoplot"] )
{
NSDictionary *bar = [self.data objectAtIndex:index];
CPTGradient *gradient = [CPTGradient gradientWithBeginningColor:[CPTColor whiteColor]
endingColor:[bar valueForKey:#"COLOR"]
beginningPosition:0.0 endingPosition:0.3 ];
[gradient setGradientType:CPTGradientTypeAxial];
[gradient setAngle:320.0];
CPTFill *fill = [CPTFill fillWithGradient:gradient];
return fill;
}
return [CPTFill fillWithColor:[CPTColor colorWithComponentRed:1.0 green:1.0 blue:1.0 alpha:1.0]];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
AppDelegate.h
#import <UIKit/UIKit.h>
#import "BarPlotViewController.h"
#interface AppDelegate : UIResponder <UIApplicationDelegate>
#property (strong, nonatomic) UIWindow *window;
#property (strong, nonatomic) BarPlotViewController *barPlotViewController;
#end
AppDelegate.m
#import "AppDelegate.h"
#implementation AppDelegate
#synthesize window = _window;
#synthesize barPlotViewController;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
barPlotViewController = [[BarPlotViewController alloc] init];
[self.window setRootViewController:barPlotViewController];
[self.window makeKeyAndVisible];
return YES;
}
#end
Image of the Simulator on Ipad:
This is how it looks on iphone same code :
Your datasource needs to implement one of the following methods:
-(NSArray *)numbersForPlot:(CPTPlot *)plot
field:(NSUInteger)fieldEnum
recordIndexRange:(NSRange)indexRange;
-(NSNumber *)numberForPlot:(CPTPlot *)plot
field:(NSUInteger)fieldEnum
recordIndex:(NSUInteger)idx;
-(double *)doublesForPlot:(CPTPlot *)plot
field:(NSUInteger)fieldEnum
recordIndexRange:(NSRange)indexRange;
-(double)doubleForPlot:(CPTPlot *)plot
field:(NSUInteger)fieldEnum
recordIndex:(NSUInteger)idx;
-(CPTNumericData *)dataForPlot:(CPTPlot *)plot
field:(NSUInteger)fieldEnum
recordIndexRange:(NSRange)indexRange;
-(CPTNumericData *)dataForPlot:(CPTPlot *)plot
recordIndexRange:(NSRange)indexRange;
I have changed all the settings to iPad except the targets --> Device --> iPad .And then it started to work.This has been the worst mistake ever and an awful waste of Time.
I have attached the entire code which I am using but the x-axis label is not being generated .I have no clue where it is going wrong .I am a noob in core plot .PLease Help me out .Thanks in Advance and Happy New Year.
#import "BarPlotViewController.h"
#interface BarPlotViewController ()
#end
#implementation BarPlotViewController
#define BAR_POSITION #"POSITION"
#define BAR_HEIGHT #"HEIGHT"
#define COLOR #"COLOR"
#define CATEGORY #"CATEGORY"
#define AXIS_START 0
#define AXIS_END 50
//
#synthesize data;
#synthesize graph;
#synthesize hostingView;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.data = [NSMutableArray array];
int bar_heights[] = {20,30,10,40};
UIColor *colors[] = {
[UIColor redColor],
[UIColor blueColor],
[UIColor orangeColor],
[UIColor purpleColor]};
NSString *categories[] = {#"Plain Milk", #"Milk + Caramel", #"White", #"Dark"};
for (int i = 0; i < 4 ; i++){
double position = i*10; //Bars will be 10 pts away from each other
double height = bar_heights[i];
NSDictionary *bar = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithDouble:position],BAR_POSITION,
[NSNumber numberWithDouble:height],BAR_HEIGHT,
colors[i],COLOR,
categories[i],CATEGORY,
nil];
[self.data addObject:bar];
}
[self generateBarPlot];
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)generateBarPlot
{
//Create host view
self.hostingView = [[CPTGraphHostingView alloc]
initWithFrame:[[UIScreen mainScreen]bounds]];
[self.view addSubview:self.hostingView];
//Create graph and set it as host view's graph
self.graph = [[CPTXYGraph alloc] initWithFrame:self.hostingView.bounds];
[self.hostingView setHostedGraph:self.graph];
//set graph padding and theme
self.graph.plotAreaFrame.paddingTop = 20.0f;
self.graph.plotAreaFrame.paddingRight = 20.0f;
self.graph.plotAreaFrame.paddingBottom = 70.0f;
self.graph.plotAreaFrame.paddingLeft = 70.0f;
[self.graph applyTheme:[CPTTheme themeNamed:kCPTDarkGradientTheme]];
//set axes ranges
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;
// plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(AXIS_START) length:CPTDecimalFromFloat((AXIS_END - AXIS_START)+5)];
// plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(-1) length:CPTDecimalFromInt(8)];
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)self.graph.axisSet;
//X labels
int labelLocations = 0;
NSMutableArray *customXLabels = [NSMutableArray array];
NSArray *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];
for (NSString *day in dates) {
CPTAxisLabel *newLabel = [[CPTAxisLabel alloc] initWithText:day textStyle:axisSet.xAxis.labelTextStyle];
newLabel.tickLocation = [[NSNumber numberWithInt:labelLocations] decimalValue];
newLabel.offset = axisSet.xAxis.labelOffset + axisSet.xAxis.majorTickLength;
// newLabel.rotation = M_PI / 4;
[customXLabels addObject:newLabel];
labelLocations++;
}
axisSet.xAxis.axisLabels = [NSSet setWithArray:customXLabels];
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:
CPTDecimalFromFloat(AXIS_START)
length:CPTDecimalFromFloat((AXIS_END - AXIS_START)+5)];
//set axes' title, labels and their text styles
CPTMutableTextStyle *textStyle = [CPTMutableTextStyle textStyle];
textStyle.fontName = #"Helvetica";
textStyle.fontSize = 14;
textStyle.color = [CPTColor whiteColor];
axisSet.xAxis.title = #"Years";
axisSet.yAxis.title = #"Expenses";
axisSet.xAxis.titleTextStyle = textStyle;
axisSet.yAxis.titleTextStyle = textStyle;
axisSet.xAxis.titleOffset = 30.0f;
axisSet.yAxis.titleOffset = 40.0f;
axisSet.xAxis.labelTextStyle = textStyle;
axisSet.xAxis.labelOffset = 3.0f;
axisSet.yAxis.labelTextStyle = textStyle;
axisSet.yAxis.labelOffset = 3.0f;
//set axes' line styles and interval ticks
CPTMutableLineStyle *lineStyle = [CPTMutableLineStyle lineStyle];
lineStyle.lineColor = [CPTColor whiteColor];
lineStyle.lineWidth = 3.0f;
axisSet.xAxis.axisLineStyle = lineStyle;
axisSet.yAxis.axisLineStyle = lineStyle;
axisSet.xAxis.majorTickLineStyle = lineStyle;
axisSet.yAxis.majorTickLineStyle = lineStyle;
axisSet.xAxis.majorIntervalLength = CPTDecimalFromFloat(5.0f);
axisSet.yAxis.majorIntervalLength = CPTDecimalFromFloat(5.0f);
axisSet.xAxis.majorTickLength = 7.0f;
axisSet.yAxis.majorTickLength = 7.0f;
axisSet.xAxis.minorTickLineStyle = lineStyle;
axisSet.yAxis.minorTickLineStyle = lineStyle;
axisSet.xAxis.minorTicksPerInterval = 1;
axisSet.yAxis.minorTicksPerInterval = 1;
axisSet.xAxis.minorTickLength = 5.0f;
axisSet.yAxis.minorTickLength = 5.0f;
// Create bar plot and add it to the graph
CPTBarPlot *plot = [[CPTBarPlot alloc] init] ;
plot.dataSource = self;
plot.delegate = self;
plot.barWidth = [[NSDecimalNumber decimalNumberWithString:#"5.0"]
decimalValue];
plot.barOffset = [[NSDecimalNumber decimalNumberWithString:#"10.0"]
decimalValue];
plot.barCornerRadius = 5.0;
// Remove bar outlines
CPTMutableLineStyle *borderLineStyle = [CPTMutableLineStyle lineStyle];
borderLineStyle.lineColor = [CPTColor clearColor];
plot.lineStyle = borderLineStyle;
// Identifiers are handy if you want multiple plots in one graph
plot.identifier = #"chocoplot";
[self.graph addPlot:plot];
}
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{
if ( [plot.identifier isEqual:#"chocoplot"] )
return [self.data count];
return 0;
}
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
if ( [plot.identifier isEqual:#"chocoplot"] )
{
NSDictionary *bar = [self.data objectAtIndex:index];
if(fieldEnum == CPTBarPlotFieldBarLocation)
return [bar valueForKey:BAR_POSITION];
else if(fieldEnum ==CPTBarPlotFieldBarTip)
return [bar valueForKey:BAR_HEIGHT];
}
return [NSNumber numberWithFloat:0];
}
-(CPTLayer *)dataLabelForPlot:(CPTPlot *)plot recordIndex:(NSUInteger)index
{
if ( [plot.identifier isEqual: #"chocoplot"] )
{
CPTMutableTextStyle *textStyle = [CPTMutableTextStyle textStyle];
textStyle.fontName = #"Helvetica";
textStyle.fontSize = 14;
textStyle.color = [CPTColor whiteColor];
NSDictionary *bar = [self.data objectAtIndex:index];
// CPTTextLayer *label = [[CPTTextLayer alloc] initWithText:[NSString stringWithFormat:#"%#", [bar valueForKey:#"CATEGORY"]]];
CPTTextLayer *label = [[CPTTextLayer alloc] initWithText:[NSString stringWithFormat:#"%#", [bar valueForKey:#"HEIGHT"]]];
label.textStyle =textStyle;
return label;
}
CPTTextLayer *defaultLabel = [[CPTTextLayer alloc] initWithText:#"Label"];
return defaultLabel;
}
-(void)barPlot:(CPTBarPlot *)plot barWasSelectedAtRecordIndex:(NSUInteger)index
{
NSLog(#"barWasSelectedAtRecordIndex %d", index);
}
-(CPTFill *)barFillForBarPlot:(CPTBarPlot *)barPlot
recordIndex:(NSUInteger)index
{
if ( [barPlot.identifier isEqual:#"chocoplot"] )
{
NSDictionary *bar = [self.data objectAtIndex:index];
CPTGradient *gradient = [CPTGradient gradientWithBeginningColor:[CPTColor whiteColor]
endingColor:[bar valueForKey:#"COLOR"]
beginningPosition:0.0 endingPosition:0.3 ];
[gradient setGradientType:CPTGradientTypeAxial];
[gradient setAngle:320.0];
CPTFill *fill = [CPTFill fillWithGradient:gradient];
return fill;
}
return [CPTFill fillWithColor:[CPTColor colorWithComponentRed:1.0 green:1.0 blue:1.0 alpha:1.0]];
}
#end
Main Code for plotting x-axis labels :
This is the code for x-axis labels:
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)self.graph.axisSet;
//X labels
int labelLocations = 0;
NSMutableArray *customXLabels = [NSMutableArray array];
NSArray *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];
for (NSString *day in dates) {
CPTAxisLabel *newLabel = [[CPTAxisLabel alloc] initWithText:day textStyle:axisSet.xAxis.labelTextStyle];
newLabel.tickLocation = [[NSNumber numberWithInt:labelLocations] decimalValue];
newLabel.offset = axisSet.xAxis.labelOffset + axisSet.xAxis.majorTickLength;
// newLabel.rotation = M_PI / 4;
[customXLabels addObject:newLabel];
labelLocations++;
}
axisSet.xAxis.axisLabels = [NSSet setWithArray:customXLabels];
Have you tried this? You have to handle the padding correctly.
graph.plotAreaFrame.paddingBottom=40;
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?