coreplot dynamic graph line not visible - core-plot

I am working to have live graph displayed using coreplot. I am fetching the data every 2 seconds and passing that to the coreplot datasource but i dont see the line. i notice the x-axis (time axis) is updating correctly. Any advise please
//listen to notification center and update the plot
- (id) init
{
self = [super init];
if (!self) return nil;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(receiveDownloadDataNotification:)
name:#"Data"
object:nil];
NSLog(#" downalodData notification listening");
return self;
}
-(void)constructGraph1
{
// Create graph from a theme
graph1 = [[CPTXYGraph alloc] initWithFrame:CGRectZero];
CPTTheme *theme = [ CPTTheme themeNamed:kCPTPlainWhiteTheme];
[graph1 applyTheme:theme];
CPTGraphHostingView *hostingView = (CPTGraphHostingView *)self.view;
hostingView.hostedGraph = graph1;
graph1.plotAreaFrame.masksToBorder = NO;
//create x-axis time format
NSTimeInterval refTimeInterval = [[NSDate date]
timeIntervalSinceReferenceDate];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HH:mm:ss a"];
CPTTimeFormatter *timeFormatter = [[CPTTimeFormatter alloc] initWithDateFormatter:dateFormatter];
timeFormatter.referenceDate = [NSDate dateWithTimeIntervalSinceReferenceDate:0];
// Setup plot space
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)graph1.defaultPlotSpace;
plotSpace.allowsUserInteraction = NO;
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(refTimeInterval-(5*oneMin)) length:CPTDecimalFromFloat(2*oneMin)];
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0) length:CPTDecimalFromFloat(100.0)];
plotSpace.globalYRange=[CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0) length:CPTDecimalFromFloat(100.0f)];
//Line Styles
CPTScatterPlot *boundLinePlot = [[CPTScatterPlot alloc] init];
CPTMutableLineStyle *lineStyle = [boundLinePlot.dataLineStyle mutableCopy];
lineStyle.lineWidth = 1.0f;
lineStyle.lineColor = [CPTColor blueColor];
boundLinePlot.dataLineStyle = lineStyle;
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];
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)graph1.axisSet;
// X-Axes formatting
CPTXYAxis *x = axisSet.xAxis;
x.majorIntervalLength = CPTDecimalFromInteger(30);
x.orthogonalCoordinateDecimal = CPTDecimalFromString(#"0");
x.minorTicksPerInterval = 0;
x.labelOffset=0;
x.labelFormatter = timeFormatter;
x.majorGridLineStyle = majorGridLineStyle;
x.minorGridLineStyle = minorGridLineStyle;
x.title=#"Time Axis";
x.labelFormatter = timeFormatter;
//Y-Axes formatting
CPTXYAxis *y = axisSet.yAxis;
y.majorIntervalLength = CPTDecimalFromInteger(10);
y.orthogonalCoordinateDecimal = CPTDecimalFromFloat(refTimeInterval-oneMin);
y.minorTicksPerInterval = 5;
y.labelOffset = 0;
y.majorGridLineStyle = majorGridLineStyle;
y.minorGridLineStyle = minorGridLineStyle;
y.preferredNumberOfMajorTicks = 10;
y.minorTickLineStyle = nil;
y.visibleRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInteger(0) length:CPTDecimalFromInteger(100)];
y.axisConstraints = [CPTConstraints constraintWithLowerOffset:0.0];
y.title=#"Mbps";
// Create a plot that uses the data source method
CPTScatterPlot *dataSourceLinePlot = [[CPTScatterPlot alloc] init] ;
dataSourceLinePlot.identifier = #"graph Plot";
dataSourceLinePlot.dataLineStyle = lineStyle;
dataSourceLinePlot.dataSource = self;
[graph1 addPlot:dataSourceLinePlot];
graphDatatoPlot = [[NSMutableArray alloc]init];
}
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{
return graphDatatoPlot.count;
}
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
if ( [plot.identifier isEqual:#"graph Plot"] ){
NSDecimalNumber *num = [[graphDatatoPlot objectAtIndex:index] objectForKey:[NSNumber numberWithInt:fieldEnum]];
return num;
}
return 0;
}
- (void) receiveDownloadDataNotification:(NSNotification *) notification
{
if ([[notification name] isEqualToString:#"Data"])
{
NSLog(#"received item %#",[notification object]);
[graphDatatoPlot addObject:[notification object]];
[graph1 reloadData];
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)graph1.defaultPlotSpace;
NSTimeInterval aTimeInterval = [[NSDate date]timeIntervalSinceReferenceDate];
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(aTimeInterval-(5*oneMin)) length:CPTDecimalFromInt(2*oneMin)];
NSLog(#"plot count %i",graphDatatoPlot.count);
}
}
just to test i am sending a constant value of 20 to the Notification center. Time is fired OK, x-axis is updated but i dont see the actual line at 20 mark.
-(void)testTimer:(NSTimer *)Timer {
NSTimeInterval timeNow= [NSDate timeIntervalSinceReferenceDate];
NSMutableDictionary *newData= [NSMutableDictionary dictionaryWithObjectsAndKeys:
[NSDecimalNumber numberWithInt:timeNow], [NSNumber numberWithInt:CPTScatterPlotFieldX],
[NSDecimalNumber numberWithInt:20], [NSNumber numberWithInt:CPTScatterPlotFieldX],nil
] ;
[[NSNotificationCenter defaultCenter] postNotificationName:#"Data" object:newData];
NSLog(#"newdata is %# %f",newData,timeNow);
}

The data points are outside the xRange. Each data point is given a x-value of the current time, but the xRange is set to a range starting five minutes before the current time with a length of two minutes, meaning it ends three minutes before the current time.

Related

[CPTPlotRange objCType]: unrecognized selector sent to instance

I'm trying to implement the real-time plot example from core-plot into my ios project, I keep getting [CPTPlotRange objCType]: unrecognized selector sent to instance which seems to be stopping the CPTAnimation for moving the graph to the newest values.
This is pretty much all of my code, and I cannot figure out why this issue occurs
-(id)initWithGraphView:(CPTGraphHostingView *) gView name:(NSString *)label {
self = [super init];
if(self) {
_graphView = gView;
CGRect bounds = _graphView.bounds;
_graph = [[CPTXYGraph alloc] initWithFrame:bounds];
_graphView.hostedGraph = _graph;
_currentIndex = 0;
_plotData = [[NSMutableArray alloc] initWithCapacity:kMaxDataPoints];
[_plotData removeAllObjects];
CPTMutableLineStyle *majorGridLineStyle = [CPTMutableLineStyle lineStyle];
majorGridLineStyle.lineWidth = 0.75;
majorGridLineStyle.lineColor = [[CPTColor colorWithGenericGray:CPTFloat(0.2)] colorWithAlphaComponent:CPTFloat(0.75)];
CPTMutableLineStyle *minorGridLineStyle = [CPTMutableLineStyle lineStyle];
minorGridLineStyle.lineWidth = 0.25;
minorGridLineStyle.lineColor = [[CPTColor whiteColor] colorWithAlphaComponent:CPTFloat(0.1)];
// Axes
// X axis
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)_graph.axisSet;
CPTXYAxis *x = axisSet.xAxis;
x.labelingPolicy = CPTAxisLabelingPolicyAutomatic;
x.orthogonalPosition = #0.0;
x.majorGridLineStyle = majorGridLineStyle;
x.minorGridLineStyle = minorGridLineStyle;
x.minorTicksPerInterval = 9;
x.title = #"X Axis";
NSNumberFormatter *labelFormatter = [[NSNumberFormatter alloc] init];
labelFormatter.numberStyle = NSNumberFormatterNoStyle;
x.labelFormatter = labelFormatter;
// Y axis
CPTXYAxis *y = axisSet.yAxis;
y.labelingPolicy = CPTAxisLabelingPolicyAutomatic;
y.orthogonalPosition = #0.0;
y.majorGridLineStyle = majorGridLineStyle;
y.minorGridLineStyle = minorGridLineStyle;
y.minorTicksPerInterval = 3;
y.title = #"Y Axis";
y.axisConstraints = [CPTConstraints constraintWithLowerOffset:0.0];
// Rotate the labels by 45 degrees, just to show it can be done.
x.labelRotation = CPTFloat(M_PI_4);
// Create the plot
CPTScatterPlot *dataSourceLinePlot = [[CPTScatterPlot alloc] init];
dataSourceLinePlot.identifier = kPlotIdentifier;
dataSourceLinePlot.cachePrecision = CPTPlotCachePrecisionDouble;
dataSourceLinePlot.interpolation = CPTScatterPlotInterpolationCurved;
CPTMutableLineStyle *lineStyle = [dataSourceLinePlot.dataLineStyle mutableCopy];
lineStyle.lineWidth = 3.0;
lineStyle.lineColor = [CPTColor greenColor];
dataSourceLinePlot.dataLineStyle = lineStyle;
dataSourceLinePlot.dataSource = self;
[_graph addPlot:dataSourceLinePlot];
// Plot space
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)_graph.defaultPlotSpace;
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:#0.0 length:#(kMaxDataPoints - 2)];
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:#0.0 length:#1000000.0];
}
return self;
}
-(void)newData:(int)value
{
NSLog(#"adding, %i", value);
CPTGraph *theGraph = _graph;
CPTPlot *thePlot = [theGraph plotWithIdentifier:kPlotIdentifier];
if ( thePlot ) {
if ( self.plotData.count >= kMaxDataPoints ) {
[self.plotData removeObjectAtIndex:0];
[thePlot deleteDataInIndexRange:NSMakeRange(0, 1)];
}
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)_graph.defaultPlotSpace;
NSUInteger location = (self.currentIndex >= kMaxDataPoints ? self.currentIndex - kMaxDataPoints + 2 : 0);
CPTPlotRange *oldRange = [CPTPlotRange plotRangeWithLocation:#( (location > 0) ? (location - 1) : 0 )
length:#(kMaxDataPoints - 2)];
CPTPlotRange *newRange = [CPTPlotRange plotRangeWithLocation:#(location)
length:#(kMaxDataPoints - 2)];
[CPTAnimation animate:plotSpace
property:#"xRange"
fromPlotRange:oldRange
toPlotRange:newRange
duration:CPTFloat(1.0 / kFrameRate)];
self.currentIndex++;
[self.plotData addObject:#(value)];
[thePlot insertDataAtIndex:self.plotData.count - 1 numberOfRecords:1];
}
}
-(NSUInteger)numberOfRecordsForPlot:(nonnull CPTPlot *)plot
{
return _plotData.count;
}
-(nullable id)numberForPlot:(nonnull CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
NSNumber *num = nil;
switch ( fieldEnum ) {
case CPTScatterPlotFieldX:
num = #(index + _currentIndex - _plotData.count);
break;
case CPTScatterPlotFieldY:
num = _plotData[index];
break;
default:
break;
}
return num;
}
There was a bug in Core Plot 2.1 that caused this error when animating plot ranges. It's fixed on the master branch and will be in the next release.
In the meantime, you can pull the latest code from GitHub or point Cocoapods to the latest code on master rather than to a release package (pod 'CorePlot', :git => 'https://github.com/core-plot/core-plot.git').

how to display Custom objects on x-axis in CPTScatterPlot graph

I have implemented custom objects(coming from webservices) on y-axis starting at y orthogonal 40 at interval of 20 in y-axis and its working correct.
At present we are showing time interval of 1 day in x-axis. But now i want to display custom objects(i.e dates but there are chances of occurring 2 different time of same date) (coming from webservices)at interval of 20 as done in y-axis.
I tried similar to y-axis but it didn’t work. All values are displaying in single position but not in interval of 20.
Sample server response is as shown below only for x-axis.
For example:-
{
date : “2015-12-25 6:30:00”,
date : “2015-12-30 14:00:00”,
date : “2016-01-25 5:30:00”,
date : “2016-01-25 7:00:00”,
date : “2016-01-10 10:00:00”,
date : “2016-01-10 12:30:00”,
date : “2016-01-11 11:00:00”,
date : “2016-01-12 16:30:00”
}
This is my code:
-(void)reloadData
{
if ( !self.graph ) {
CPTXYGraph *newGraph = [[CPTXYGraph alloc] initWithFrame:CGRectZero];
self.graph = newGraph;
newGraph.paddingTop = 0.0;
newGraph.paddingBottom = 0.0;
newGraph.paddingLeft = 0.0;
newGraph.paddingRight = 0.0;
self.graph.plotAreaFrame.paddingTop = 2.0f;
self.graph.plotAreaFrame.paddingRight = 8.0f;
self.graph.plotAreaFrame.paddingBottom = 30.0f;
self.graph.plotAreaFrame.paddingLeft = 42.0f;
//self.graph.backgroundColor = [[UIColor greenColor] CGColor];
self.graph.paddingTop = 2.0f;
self.graph.paddingRight = 2.0f;
self.graph.paddingBottom = 2.0f;
self.graph.paddingLeft = 2.0f;
CPTScatterPlot *dataSourceLinePlot = [[CPTScatterPlot alloc] initWithFrame:newGraph.bounds];
dataSourceLinePlot.identifier = #"Systolic";
dataSourceLinePlot.dataSource = self;
dataSourceLinePlot.delegate = self;
CPTColor *areaColor = [CPTColor colorWithComponentRed:249.0/255.0 green:183.0/255.0 blue:183.0/255.0 alpha:.7];
CPTFill *areaGradientFill = [CPTFill fillWithColor:areaColor];
[dataSourceLinePlot setAreaFill:areaGradientFill];
[dataSourceLinePlot setAreaBaseValue:[NSDecimalNumber decimalNumberWithDecimal:CPTDecimalFromInt(60)]];//[NSNumber numberWithInt:CPTDecimalFromInt(0)]];
CPTMutableLineStyle *lineStyle = [dataSourceLinePlot.dataLineStyle mutableCopy];
CPTColor *aaplColor = [CPTColor redColor];
lineStyle.lineColor = aaplColor;
CPTXYAxisSet axisSet = (CPTXYAxisSet ) newGraph.axisSet;
/*
// 3 - Configure x-axis
CPTAxis *x = axisSet.xAxis;
*/
// set the majorGridLinestyleProperty by this line as.
CPTMutableLineStyle *gridLineStyle = [CPTMutableLineStyle lineStyle];
gridLineStyle.lineColor = [CPTColor grayColor];
gridLineStyle.lineWidth = 1.0f;
gridLineStyle.dashPattern = [NSArray arrayWithObjects:[NSDecimalNumber numberWithInt:1], [NSDecimalNumber numberWithInt:2], nil];
gridLineStyle.patternPhase=0.0f;
dataSourceLinePlot.dataLineStyle = lineStyle;
axisSet.yAxis.majorGridLineStyle = gridLineStyle;
// axisSet.yAxis.axisLineStyle = axisLineStyle;
axisSet.xAxis.majorGridLineStyle = gridLineStyle;
// axisSet.xAxis.axisLineStyle = axisLineStyle;
dataSourceLinePlot.dataSource = self;
[newGraph addPlot:dataSourceLinePlot];
//-------------------------------------------------------------------------------------
CPTScatterPlot *dataSourceLinePlot2 = [[CPTScatterPlot alloc] initWithFrame:newGraph.bounds];
dataSourceLinePlot2.identifier = #"Diastolic";
dataSourceLinePlot2.dataSource = self;
dataSourceLinePlot2.delegate = self;
CPTColor *areaColor1 = [CPTColor colorWithComponentRed:229.0/255.0 green:87.0/255.0 blue:87.0/255.0 alpha:.7];
CPTFill *areaGradientFill1 = [CPTFill fillWithColor:areaColor1];
[dataSourceLinePlot2 setAreaFill:areaGradientFill1];
[dataSourceLinePlot2 setAreaBaseValue:[NSDecimalNumber decimalNumberWithDecimal:CPTDecimalFromInt(60)]];
CPTMutableLineStyle *lineStyle1 = [dataSourceLinePlot.dataLineStyle mutableCopy];
CPTColor *aaplColor1 = [CPTColor redColor];
lineStyle1.lineColor = aaplColor1;
dataSourceLinePlot2.dataLineStyle = lineStyle1;
dataSourceLinePlot2.dataSource = self;
[newGraph addPlot:dataSourceLinePlot2];
}
CPTXYGraph *theGraph = self.graph;
self.graphHost.hostedGraph = theGraph;
CPTXYPlotSpace plotSpace = (CPTXYPlotSpace )theGraph.defaultPlotSpace;
plotSpace.allowsUserInteraction = YES;
plotSpace.delegate = self;
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setGeneratesDecimalNumbers:NO];
NSTimeInterval oneDay = 24 60 60;
NSTimeInterval xLow = 0.0f;
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:[NSDecimalNumber decimalNumberWithDecimal:CPTDecimalFromFloat(xLow)]
length:[NSDecimalNumber decimalNumberWithDecimal:CPTDecimalFromFloat(oneDay*5.0f)]];
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:#50.0 length:#(120)];
// Axes
CPTXYAxisSet axisSet = (CPTXYAxisSet )theGraph.axisSet;
NSDate refDate = [NSDate dateWithTimeIntervalSinceReferenceDate:31556926 10];
// added for date
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd/MM"];
// dateFormatter.dateStyle = kCFDateFormatterShortStyle;
CPTTimeFormatter *timeFormatter = [[CPTTimeFormatter alloc] initWithDateFormatter:dateFormatter];
NSLog(#"Ref date: %#", refDate);
timeFormatter.referenceDate = refDate;
axisSet.xAxis.labelFormatter = timeFormatter;
CPTXYAxis *x = axisSet.xAxis;
x.majorIntervalLength = [NSDecimalNumber decimalNumberWithDecimal:CPTDecimalFromFloat(oneDay)];
x.orthogonalPosition = #60.0;
x.minorTicksPerInterval = 1;
CPTXYAxis *y = axisSet.yAxis;
y.majorIntervalLength = #20;
y.majorTickLineStyle = nil;
y.minorTicksPerInterval = 4;
y.minorTickLineStyle = nil;
y.orthogonalPosition = #60.0;
y.tickDirection = CPTSignPositive;
[theGraph reloadData];
}
Please let me know how to achieve this.
Thanks in advance.
You can use -[NSDateFormatter dateFromString:] to convert the date strings received from the server into NSDate objects. It looks the graph is already set up to display the dates.

CorePlot ScatterPlot labelingPolicy

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.

iOS CorePlot x-axis DateTime interval proportional

I have code which display me graph with two plots. What I want and didn't find how to do is that: On x-axis where is DateTime I need correct proportional intervals between Dates, not the same.
Here is my code:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
DateTime = #[#"2013-10-05 08:47:52",#"2013-10-06 08:47:52",#"2013-10-07 08:47:52",#"2013-10-08 08:47:52",#"2013-10-09 08:47:52",#"2013-10-12 08:47:52",#"2013-10-13 08:47:52"];
temp1 = #[#"17.1",#"20",#"19",#"16",#"15",#"15",#"17"];
temp2 = #[#"13",#"11",#"13",#"10",#"11",#"12",#"13"];
[self initPlot];
}
-(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:kCPTSlateTheme]];
self.hostView.hostedGraph = graph;
// 2 - Set graph title
NSString *title = #"Testovací graf";
graph.title = title;
// 3 - Create and set text style
CPTMutableTextStyle *titleStyle = [CPTMutableTextStyle textStyle];
titleStyle.color = [CPTColor blackColor];
titleStyle.fontName = #"Helvetica-Bold";
titleStyle.fontSize = 12.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:100.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 plots
CPTScatterPlot *probe1Plot = [[CPTScatterPlot alloc] init];
probe1Plot.dataSource = self;
probe1Plot.identifier = #"Temp1";
CPTColor *probe1Color = [CPTColor redColor];
[graph addPlot:probe1Plot toPlotSpace:plotSpace];
CPTScatterPlot *probe2Plot = [[CPTScatterPlot alloc] init];
probe2Plot.dataSource = self;
probe2Plot.identifier = #"Temp2";
CPTColor *probe2Color = [CPTColor blueColor];
[graph addPlot:probe2Plot toPlotSpace:plotSpace];
// 3 - Set up plot space
[plotSpace scaleToFitPlots:[NSArray arrayWithObjects:probe1Plot, probe2Plot, nil]];
CPTMutablePlotRange *xRange = [plotSpace.xRange mutableCopy];
[xRange expandRangeByFactor:CPTDecimalFromCGFloat(1.48f)];
plotSpace.xRange = xRange;
CPTMutablePlotRange *yRange = [plotSpace.yRange mutableCopy];
[yRange expandRangeByFactor:CPTDecimalFromCGFloat(3.0f)];
plotSpace.yRange = yRange;
// 4 - Create styles and symbols
CPTMutableLineStyle *probe1LineStyle = [probe1Plot.dataLineStyle mutableCopy];
probe1LineStyle.lineWidth = 1.0 ;
probe1LineStyle.lineColor = probe1Color;
probe1Plot.dataLineStyle = probe1LineStyle;
CPTMutableLineStyle *probe1SymbolLineStyle = [CPTMutableLineStyle lineStyle];
probe1SymbolLineStyle.lineColor = probe1Color;
CPTPlotSymbol *probe1Symbol = [CPTPlotSymbol ellipsePlotSymbol];
probe1Symbol.fill = [CPTFill fillWithColor:probe1Color];
probe1Symbol.lineStyle = probe1SymbolLineStyle;
probe1Symbol.size = CGSizeMake(3.0f, 3.0f);
probe1Plot.plotSymbol = probe1Symbol;
CPTMutableLineStyle *probe2LineStyle = [probe2Plot.dataLineStyle mutableCopy];
probe2LineStyle.lineWidth = 1.0;
probe2LineStyle.lineColor = probe2Color;
probe2Plot.dataLineStyle = probe2LineStyle;
CPTMutableLineStyle *probe2SymbolLineStyle = [CPTMutableLineStyle lineStyle];
probe2SymbolLineStyle.lineColor = probe2Color;
CPTPlotSymbol *probe2Symbol = [CPTPlotSymbol diamondPlotSymbol];
probe2Symbol.fill = [CPTFill fillWithColor:probe2Color];
probe2Symbol.lineStyle = probe2SymbolLineStyle;
probe2Symbol.size = CGSizeMake(3.0f, 3.0f);
probe2Plot.plotSymbol = probe2Symbol;
}
-(void)configureAxes
{
// 1 - Create styles
CPTMutableTextStyle *axisTitleStyle = [CPTMutableTextStyle textStyle];
axisTitleStyle.color = [CPTColor blackColor];
axisTitleStyle.fontName = #"Helvetica-Bold";
axisTitleStyle.fontSize = 10.0f;
CPTMutableLineStyle *axisLineStyle = [CPTMutableLineStyle lineStyle];
axisLineStyle.lineWidth = 1.5f;
axisLineStyle.lineColor = [CPTColor blackColor];
CPTMutableTextStyle *axisTextStyle = [[CPTMutableTextStyle alloc] init];
axisTextStyle.color = [CPTColor blackColor];
axisTextStyle.fontName = #"Helvetica-Bold";
axisTextStyle.fontSize = 11.0f;
CPTMutableLineStyle *tickLineStyle = [CPTMutableLineStyle lineStyle];
tickLineStyle.lineColor = [CPTColor blackColor];
tickLineStyle.lineWidth = 2.0f;
CPTMutableLineStyle *gridLineStyle = [CPTMutableLineStyle lineStyle];
gridLineStyle.lineColor = [CPTColor grayColor];
gridLineStyle.lineWidth = 0.5f;
// 2 - Get axis set
CPTXYAxisSet *axisSet = (CPTXYAxisSet *) self.hostView.hostedGraph.axisSet;
// 3 - Configure x-axis
CPTAxis *x = axisSet.xAxis;
x.title = #"DateTime";
x.titleTextStyle = axisTitleStyle;
x.titleOffset = 85.0f;
x.axisLineStyle = axisLineStyle;
x.labelingPolicy = CPTAxisLabelingPolicyNone;
x.labelTextStyle = axisTextStyle;
x.majorTickLineStyle = axisLineStyle;
x.majorTickLength = 4.0f;
x.tickLabelDirection = CPTSignNegative;
CGFloat dateCount = [DateTime count];
NSMutableSet *xLabels = [NSMutableSet setWithCapacity:dateCount];
NSMutableSet *xLocations = [NSMutableSet setWithCapacity:dateCount];
NSInteger i = 0;
for (NSString *date in DateTime)
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
NSString *str = [self localTime:date];
CPTAxisLabel *label = [[CPTAxisLabel alloc] initWithText:str 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;
x.labelRotation = M_PI / 4;
// 4 - Configure y-axis
CPTAxis *y = axisSet.yAxis;
y.title = #"Temperature";
y.titleTextStyle = axisTitleStyle;
y.titleOffset = 30.0f;
y.axisLineStyle = axisLineStyle;
y.majorGridLineStyle = gridLineStyle;
y.labelingPolicy = CPTAxisLabelingPolicyNone;
y.labelTextStyle = axisTextStyle;
y.labelOffset = -16.0f;
y.majorTickLineStyle = axisLineStyle;
y.majorTickLength = 2.0f;
y.minorTickLength = 2.0f;
NSInteger majorIncrement = 10;
NSInteger minorIncrement = 1;
CGFloat yMax = 40.0f; // should determine dynamically based on max temp
NSMutableSet *yLabels = [NSMutableSet set];
NSMutableSet *yMajorLocations = [NSMutableSet set];
NSMutableSet *yMinorLocations = [NSMutableSet set];
for (NSInteger j = minorIncrement; j <= yMax; j+= minorIncrement)
{
NSInteger mod = j % majorIncrement;
if (mod == 0)
{
CPTAxisLabel *label = [[CPTAxisLabel alloc] initWithText:[NSString stringWithFormat:#"%li", (long)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;
CPTGraph *graph = self.hostView.hostedGraph;
graph.legend = [CPTLegend legendWithGraph:graph];
CPTMutableLineStyle *legendBorderlineStyle = [CPTMutableLineStyle lineStyle];
legendBorderlineStyle.lineColor = [CPTColor blackColor];
legendBorderlineStyle.lineWidth = 1.0f;
legendBorderlineStyle.lineColor = [CPTColor blackColor];
graph.legend.borderLineStyle = legendBorderlineStyle;
graph.legend.fill = [CPTFill fillWithColor:[CPTColor lightGrayColor]];
graph.legend.cornerRadius = 5.0;
graph.legend.swatchSize = CGSizeMake(10, 20);
graph.legendAnchor = CPTRectAnchorBottom;
graph.legend.textStyle = axisTextStyle;
graph.legendDisplacement = CGPointMake(150.40, 250.0);
}
- (NSString *) localTime:(NSString *)time //this is for recount TimeZone ofset
{
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
//Special Locale for fixed dateStrings
NSLocale *locale = [[NSLocale alloc]initWithLocaleIdentifier:#"en_US_POSIX"];
[formatter setLocale:locale];
//Assuming the dateString is in GMT+00:00
//formatter by default would be set to local timezone
NSTimeZone *timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
[formatter setTimeZone:timeZone];
[formatter setDateFormat:#"YYYY-MM-dd HH:mm:ss"];
NSDate *date =[formatter dateFromString:time];
//After forming the date set local time zone to formatter
NSTimeZone *localTimeZone = [NSTimeZone localTimeZone];
[formatter setTimeZone:localTimeZone];
NSString *newTimeZoneDateString = [formatter stringFromDate:date];
return newTimeZoneDateString;
}
#pragma mark - CPTPlotDataSource methods
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{
// return [DateTime count];
if ([(NSString *)plot.identifier isEqualToString:#"Temp1"])
{
return temp1.count;
}
else if ([(NSString *)plot.identifier isEqualToString:#"Temp2"])
{
return temp2.count;
}
return 0;
}
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)idx
{
NSNumber *num = nil;
switch (fieldEnum) {
case CPTScatterPlotFieldX:
num = [NSNumber numberWithUnsignedInteger:idx];
break;
case CPTScatterPlotFieldY:
if ([(NSString *)plot.identifier isEqualToString:#"Temp1"])
{
num = [temp1 objectAtIndex:idx];
}
else if ([(NSString *)plot.identifier isEqualToString:#"Temp2"])
{
num = [temp2 objectAtIndex:idx];
}
break;
}
return num;
}
I wantproportional gaps between DateTime items on X-axis. If someone helps me, I'll be very lucky. Thanks. :)
Eric is an expert, and his answer is good enough. But I want to contribute with more details, which are necessary for beginners like me, having a lot of troubles putting things into proper places.
First, you need to set proper range (I did learn a great deal from Eric on that).
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HH:mm"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:25200]];
NSTimeInterval xLow = [[dateFormatter dateFromString:#"8:30"] timeIntervalSince1970];
NSTimeInterval xHigh = [[dateFormatter dateFromString:#"12:00"] timeIntervalSince1970];
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(xLow)
length:CPTDecimalFromDouble(xHigh-xLow)];
Next, for fixed intervals (e.g. half an hour), use the following:
x.labelingPolicy = CPTAxisLabelingPolicyFixedInterval;
NSTimeInterval x1 = [[dateFormatter dateFromString:#"8:30"] timeIntervalSince1970];
NSTimeInterval x2 = [[dateFormatter dateFromString:#"9:30"] timeIntervalSince1970];
x.majorIntervalLength = CPTDecimalFromDouble(x2-x1);
//Label time Format:
CPTTimeFormatter *timeFormatter = [[CPTTimeFormatter alloc] initWithDateFormatter:dateFormatter];
x.labelFormatter = timeFormatter;
For custom labelling, replace the above two sections with the following:
x.labelingPolicy = CPTAxisLabelingPolicyNone;
NSMutableSet *xLabels = [NSMutableSet setWithCapacity:[self.arrXValues count]];
NSMutableSet *xLocations = [NSMutableSet setWithCapacity:[self.arrXValues count]];
for (NSString *string in self.arrXValues) {
CPTAxisLabel *label = [[CPTAxisLabel alloc] initWithText:string textStyle:axisTextStyle];
NSDate *time = [dateFormatter dateFromString:string];
NSTimeInterval interval = [time timeIntervalSince1970];
label.tickLocation = CPTDecimalFromDouble(interval);
label.rotation = M_PI * 1/4;
label.offset = 0.0f;
if (label) {
[xLabels addObject:label];
[xLocations addObject:[NSString stringWithFormat:#"%f", interval]];
}
}
x.axisLabels = xLabels;
x.majorTickLocations = xLocations;
And finally, core plot delegate method,
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)indexPath
{
if(fieldEnum == CPTScatterPlotFieldX)
{
//return [NSNumber numberWithFloat:[[self.arrXValues objectAtIndex:indexPath] floatValue]];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HH:mm"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:25200]];
NSDate *time = [dateFormatter dateFromString:[self.arrXValues objectAtIndex:indexPath]];
NSTimeInterval interval = [time timeIntervalSince1970];
return [NSNumber numberWithDouble:interval];
}
else if(fieldEnum == CPTScatterPlotFieldY) {
return [NSNumber numberWithFloat:[[self.arrYValues objectAtIndex:indexPath] floatValue]];
}
return nil;
}
There are several example apps included with Core Plot that demonstrate working with dates. See, for example, the "Date Plot" demo in the Plot Gallery app.
You need to convert the date value to numeric values and use those for the x-values instead of the data index. Be sure to set the plot space xRange accordingly.

Using core plot for iPhone, drawing date on x axis

I have available an array of dictionary that contains NSDate and NSNumber values. I wanted to plot date on X axis.
For plotting I need to supply xRanges to plot with some decimal values. I don't understand how can I supply NSDate values to xRange (low and length).
And what should be there in this method:
-(NSNumber *)numberForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
I mean how my date value will be returned as NSNumber? I think I should use some interval over there, but what should be the exact conversion?
Can any one explain me what are the exact requirement to plot the date on xAxis?
I am plotting my plot in half of the view.
Here you go, DatePlot working on iOS. Don't forget to check it as correct.
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
// If you make sure your dates are calculated at noon, you shouldn't have to
// worry about daylight savings. If you use midnight, you will have to adjust
// for daylight savings time.
NSDate *refDate = [NSDate dateWithTimeIntervalSinceReferenceDate:31556926 * 10];
NSTimeInterval oneDay = 24 * 60 * 60;
// Invert graph view to compensate for iOS coordinates
CGAffineTransform verticalFlip = CGAffineTransformMakeScale(1,-1);
self.view.transform = verticalFlip;
// allocate the graph within the current view bounds
graph = [[CPTXYGraph alloc] initWithFrame: self.view.bounds];
// assign theme to graph
CPTTheme *theme = [CPTTheme themeNamed:kCPTDarkGradientTheme];
[graph applyTheme:theme];
// Setting the graph as our hosting layer
CPTGraphHostingView *hostingView = [[CPTGraphHostingView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:hostingView];
hostingView.hostedGraph = graph;
graph.paddingLeft = 20.0;
graph.paddingTop = 20.0;
graph.paddingRight = 20.0;
graph.paddingBottom = 150.0;
// setup a plot space for the plot to live in
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)graph.defaultPlotSpace;
NSTimeInterval xLow = 0.0f;
// sets the range of x values
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(xLow)
length:CPTDecimalFromFloat(oneDay*5.0f)];
// sets the range of y values
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0)
length:CPTDecimalFromFloat(5)];
// plotting style is set to line plots
CPTMutableLineStyle *lineStyle = [CPTMutableLineStyle lineStyle];
lineStyle.lineColor = [CPTColor blackColor];
lineStyle.lineWidth = 2.0f;
// X-axis parameters setting
CPTXYAxisSet *axisSet = (id)graph.axisSet;
axisSet.xAxis.majorIntervalLength = CPTDecimalFromFloat(oneDay);
axisSet.xAxis.minorTicksPerInterval = 0;
axisSet.xAxis.orthogonalCoordinateDecimal = CPTDecimalFromString(#"1"); //added for date, adjust x line
axisSet.xAxis.majorTickLineStyle = lineStyle;
axisSet.xAxis.minorTickLineStyle = lineStyle;
axisSet.xAxis.axisLineStyle = lineStyle;
axisSet.xAxis.minorTickLength = 5.0f;
axisSet.xAxis.majorTickLength = 7.0f;
axisSet.xAxis.labelOffset = 3.0f;
// added for date
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
dateFormatter.dateStyle = kCFDateFormatterShortStyle;
CPTTimeFormatter *timeFormatter = [[[CPTTimeFormatter alloc] initWithDateFormatter:dateFormatter] autorelease];
timeFormatter.referenceDate = refDate;
axisSet.xAxis.labelFormatter = timeFormatter;
// Y-axis parameters setting
axisSet.yAxis.majorIntervalLength = CPTDecimalFromString(#"0.5");
axisSet.yAxis.minorTicksPerInterval = 2;
axisSet.yAxis.orthogonalCoordinateDecimal = CPTDecimalFromFloat(oneDay); // added for date, adjusts y line
axisSet.yAxis.majorTickLineStyle = lineStyle;
axisSet.yAxis.minorTickLineStyle = lineStyle;
axisSet.yAxis.axisLineStyle = lineStyle;
axisSet.yAxis.minorTickLength = 5.0f;
axisSet.yAxis.majorTickLength = 7.0f;
axisSet.yAxis.labelOffset = 3.0f;
// This actually performs the plotting
CPTScatterPlot *xSquaredPlot = [[[CPTScatterPlot alloc] init] autorelease];
CPTMutableLineStyle *dataLineStyle = [CPTMutableLineStyle lineStyle];
//xSquaredPlot.identifier = #"X Squared Plot";
xSquaredPlot.identifier = #"Date Plot";
dataLineStyle.lineWidth = 1.0f;
dataLineStyle.lineColor = [CPTColor redColor];
xSquaredPlot.dataLineStyle = dataLineStyle;
xSquaredPlot.dataSource = self;
CPTPlotSymbol *greenCirclePlotSymbol = [CPTPlotSymbol ellipsePlotSymbol];
greenCirclePlotSymbol.fill = [CPTFill fillWithColor:[CPTColor greenColor]];
greenCirclePlotSymbol.size = CGSizeMake(2.0, 2.0);
xSquaredPlot.plotSymbol = greenCirclePlotSymbol;
// add plot to graph
[graph addPlot:xSquaredPlot];
// Add some data
NSMutableArray *newData = [NSMutableArray array];
NSUInteger i;
for ( i = 0; i < 5; i++ ) {
NSTimeInterval x = oneDay*i;
id y = [NSDecimalNumber numberWithFloat:1.2*rand()/(float)RAND_MAX + 1.2];
[newData addObject:
[NSDictionary dictionaryWithObjectsAndKeys:
[NSDecimalNumber numberWithFloat:x], [NSNumber numberWithInt:CPTScatterPlotFieldX],
y, [NSNumber numberWithInt:CPTScatterPlotFieldY],
nil]];
NSLog(#"%#",newData);
}
plotData = [newData retain];
}
#pragma mark - Plot Data Source Methods
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{
return plotData.count;
}
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
NSDecimalNumber *num = [[plotData objectAtIndex:index] objectForKey:[NSNumber numberWithInt:fieldEnum]];
return num;
}
Take a look at the DatePlot program in the examples folder. It shows how to format axis labels as dates.

Resources