iOS CorePlot x-axis DateTime interval proportional - ios

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.

Related

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

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

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.

iOS - Z order of plotted line in Core Plot

I have integrated Core Plot in my iOS App.I have few issues as mentioned below:
1) Need to show yellow line and red line behind y-axis.
2) Need to have the y-range as 5,10,15 only.Link For Graph Image
Below is my code:
-(void)configureHost {
self.hostView = [(CPTGraphHostingView *) [CPTGraphHostingView alloc] initWithFrame:CGRectMake(60, 80, 400, 200)];
}
-(void)configureGraph {
CPTGraph *graph = [[CPTXYGraph alloc] initWithFrame:CGRectMake(10, 100, 300, 200)];
self.hostView.hostedGraph = graph;
graph.plotAreaFrame.borderLineStyle = nil;
graph.plotAreaFrame.cornerRadius = 10.0f ;
graph.paddingLeft = 0.0;
graph.paddingRight = 0.0;
graph.paddingTop = 0.0;
graph.paddingBottom = 0.0;
[graph.plotAreaFrame setPaddingLeft:30.0f];
[graph.plotAreaFrame setPaddingRight:20.0f];
[graph.plotAreaFrame setPaddingTop:20.0f];
[graph.plotAreaFrame setPaddingBottom:40.0f];
}
-(void)configurePlots {
CPTGraph *lGraph = self.hostView.hostedGraph;
CPTXYPlotSpace *lPlotSpace = (CPTXYPlotSpace *) lGraph.defaultPlotSpace;
CPTScatterPlot *lDataLinePlot = [[CPTScatterPlot alloc] init];
lDataLinePlot.dataSource = self;
lDataLinePlot.identifier = CPDTickerSymbolBLUELINE;
lDataLinePlot.interpolation = CPTScatterPlotInterpolationCurved;
CPTColor *lDataLineColor = [CPTColor blueColor];
[lGraph addPlot:lDataLinePlot toPlotSpace:lPlotSpace];
[lGraph.defaultPlotSpace scaleToFitPlots:[lGraph allPlots]];
CPTScatterPlot *lDangerLinePlot = [[CPTScatterPlot alloc] init];
lDangerLinePlot.dataSource = self;
lDangerLinePlot.identifier = CPDTickerSymbolDANGERREDLINE;
lDangerLinePlot.interpolation = CPTScatterPlotInterpolationCurved;
CPTColor *lDangerLineColor = [CPTColor redColor];
[lGraph addPlot:lDangerLinePlot toPlotSpace:lPlotSpace];
CPTScatterPlot *lYellowLinePlot = [[CPTScatterPlot alloc] init];
lYellowLinePlot.dataSource = self;
lYellowLinePlot.identifier = CPDTickerSymbolYELLOWLINE;
lYellowLinePlot.interpolation = CPTScatterPlotInterpolationCurved;
CPTColor *lYellowLineColor = [CPTColor yellowColor];
[lGraph addPlot:lYellowLinePlot toPlotSpace:lPlotSpace];
[lPlotSpace scaleToFitPlots:[NSArray arrayWithObjects:lYellowLinePlot,lDangerLinePlot,lDataLinePlot, nil]];
min=0;
lPlotSpace.yRange = [CPTPlotRange
plotRangeWithLocation:CPTDecimalFromCGFloat(min)
length:CPTDecimalFromCGFloat((15))];
CPTMutablePlotRange *lRangeX = [lPlotSpace.xRange mutableCopy];
[lRangeX expandRangeByFactor:CPTDecimalFromCGFloat(1.005f)];
lPlotSpace.xRange = lRangeX;
CPTMutablePlotRange *lRangeY = [lPlotSpace.yRange mutableCopy];
[lRangeY expandRangeByFactor:CPTDecimalFromCGFloat(1.0f)];
lPlotSpace.yRange = lRangeY;
CPTColor *lAreaColor = [CPTColor colorWithComponentRed:255.0 green:255.0 blue:255.0 alpha:1.0];
CPTGradient *lAreaGradient =[CPTGradient gradientWithBeginningColor:lAreaColor endingColor:[CPTColor clearColor]];
lAreaGradient. angle = 90.0f ;
CPTMutableLineStyle *lDataLineStyle = [lDataLinePlot.dataLineStyle mutableCopy];
lDataLineStyle.lineWidth = 3;
lDataLineStyle.lineColor = lDataLineColor;
lDataLinePlot.dataLineStyle = lDataLineStyle;
CPTMutableLineStyle *lYellowLineStyle = [lDataLinePlot.dataLineStyle mutableCopy];
lYellowLineStyle.lineWidth = 1.5;
lYellowLineStyle.lineColor = lYellowLineColor;
lYellowLinePlot.dataLineStyle = lYellowLineStyle;
CPTMutableLineStyle *lDataLineStyleSymbol = [CPTMutableLineStyle lineStyle];
lDataLineStyleSymbol.lineColor = lDataLineColor;
CPTMutableLineStyle *lYellowLineStyleSymbol = [CPTMutableLineStyle lineStyle];
lYellowLineStyleSymbol.lineColor = lYellowLineColor;
CPTMutableLineStyle *lDangerLineStyle = [lDangerLinePlot.dataLineStyle mutableCopy];
lDangerLineStyle.lineWidth = 1.5;
lDangerLineStyle.lineColor = lDangerLineColor;
lDangerLinePlot.dataLineStyle = lDangerLineStyle;
CPTMutableLineStyle *lDangerLineStyleSumbol = [CPTMutableLineStyle lineStyle];
lDangerLineStyleSumbol.lineColor = lDangerLineColor;
CPTMutableLineStyle *lDataSymbolLineStyle = [CPTMutableLineStyle lineStyle];
lDataSymbolLineStyle.lineColor = lDataLineColor;
CPTMutableLineStyle *lYellowSymbolLineStyle = [CPTMutableLineStyle lineStyle];
lYellowSymbolLineStyle.lineColor = lYellowLineColor;
}
-(void)configureAxes {
CPTMutableTextStyle *axisTitleStyle = [CPTMutableTextStyle textStyle];
axisTitleStyle.color = [CPTColor blackColor];
axisTitleStyle.fontName = #"Helvetica";
axisTitleStyle.fontSize = 13.0f;
CPTMutableLineStyle *axisLineStyle = [CPTMutableLineStyle lineStyle];
axisLineStyle.lineWidth = 3.0f;
axisLineStyle.lineColor = [CPTColor blackColor];
CPTMutableTextStyle *axisTextStyle = [[CPTMutableTextStyle alloc] init];
axisTextStyle.color = [CPTColor blackColor];
axisTextStyle.fontName = #"Bold";
axisTextStyle.fontSize = 8.0f;
CPTMutableLineStyle *tickLineStyle = [CPTMutableLineStyle lineStyle];
tickLineStyle.lineColor = [CPTColor blackColor];
tickLineStyle.lineWidth = 1.0f;
CPTXYAxisSet *axisSet = (CPTXYAxisSet *) self.hostView.hostedGraph.axisSet;
/////X-AXIS DATE
DateArray=[[NSMutableArray alloc]init];
NSDateFormatter *format=[[NSDateFormatter alloc]init];
format.dateFormat=#"MM/dd/yy";
NSCalendar *calendar1 = [NSCalendar autoupdatingCurrentCalendar];
NSDateComponents *components1 = [calendar1 components:NSCalendarUnitYear
| NSCalendarUnitMonth | NSCalendarUnitDay
fromDate:[NSDate date]];
for (int i = 0; i < 60; ++i)
{
NSDate *date1 = [calendar1 dateFromComponents:components1];
NSString *getDate1=[format stringFromDate:date1];
NSString *lReplaced = [getDate1 substringToIndex:5];
lReplaced = [lReplaced stringByReplacingOccurrencesOfString:#"-"
withString:#"/"];
NSString *match = #"/";
NSMutableString *preTel;
NSString *postTel;
NSScanner *scanner = [NSScanner scannerWithString:lReplaced];
[scanner scanUpToString:match intoString:&preTel];
[scanner scanString:match intoString:nil];
postTel = [lReplaced substringFromIndex:scanner.scanLocation];
NSString *newStr1;
NSString *newStr2;
if ([preTel intValue] <10) {
newStr1 = [preTel substringFromIndex:1];
}else{
newStr1=preTel;
}
if ([postTel intValue] <10) {
newStr2 = [postTel substringFromIndex:1];
}else{
newStr2=postTel;
}
lReplaced =[NSString stringWithFormat:#"%#%#%#",newStr1,match,newStr2];
[DateArray addObject:lReplaced];
++components1.day;
}
NSOrderedSet *mySet = [[NSOrderedSet alloc] initWithArray:DateArray];
DateArray = [[NSMutableArray alloc] initWithArray:[mySet array]];
//////// configure x-Axes
CPTAxis *x = axisSet.xAxis;
x.titleTextStyle = axisTitleStyle;
x.axisLineStyle = axisLineStyle;
x.labelingPolicy = CPTAxisLabelingPolicyNone;
x.labelTextStyle = axisTextStyle;
x.majorTickLineStyle = axisLineStyle;
x.tickDirection = CPTSignPositive;
CGFloat dateCount = [dayArray count];
NSMutableSet *xLabels = [NSMutableSet setWithCapacity:dateCount];
NSMutableSet *xLocations = [NSMutableSet setWithCapacity:dateCount];
int lIndex = 1;
for (int i=0;i< [DateArray count];i++)
{
// NSLog(#"i VAL:%d",i);
NSString *date = [DateArray objectAtIndex:i];
// NSLog(#"date:%#",date);
CPTAxisLabel *label = [[CPTAxisLabel alloc] initWithText:date textStyle:x.labelTextStyle];
CGFloat location = i*3.40;
//NSLog(#"LOC:%f",location);
label.tickLocation = CPTDecimalFromCGFloat(location);
label.offset = -20.0f;
[xLabels addObject:label];
[xLocations addObject:[NSNumber numberWithFloat:location]];
lIndex++;
i = i+6;
}
x.axisLabels = xLabels;
x.majorTickLocations = xLocations;
//////// Configure Y-Axes
CPTAxis *y = axisSet.yAxis;
y.title = #"Hb";
y.titleTextStyle = axisTitleStyle;
y.titleOffset = -30.0f;
y.axisLineStyle = axisLineStyle;
y.labelingPolicy = CPTAxisLabelingPolicyNone;
// y.preferredNumberOfMajorTicks=5;
y.labelTextStyle = axisTextStyle;
y.labelOffset = -35.0f;
y.majorTickLineStyle = axisLineStyle;
y.tickDirection = CPTSignPositive;
NSInteger majorIncrement = 5;
NSInteger minorIncrement = 5;
CGFloat yMax =15.0f;
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:#"%li", (long)j] textStyle:y.labelTextStyle];
NSDecimal location = CPTDecimalFromInteger(j);
label.tickLocation = location;
label.offset = -20.0f;//-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;
}
Use the topDownLayerOrder to move the axis line in front of the plots.
CPTPlotArea *plotArea = graph.plotAreaFrame.plotArea;
plotArea.topDownLayerOrder = #[#(CPTGraphLayerTypeAxisLines)];
Set the yRange to start at 5.0 with length 10.0:
lPlotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(5.0)
length:CPTDecimalFromDouble(10.0)];

coreplot dynamic graph line not visible

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.

Consistently show a label at the origin using a date/time and Core Plot

I'm using core plot to display recent server metrics on an iPhone/iPad. I've got it plotting correctly, and looking about 95% how I want it to. My only gripe is that the Date and Time that are displayed as the x axis interval, and it doesn't appear that I have much control over what point that interval starts at.
For example, I currently have the major interval printing out the date/time every half hour. This means that I have times printing out on the x-axis as follows: 2/8 12:00pm 2/8 12:30pm 2/8 1:00pm
I would like to have the origin of the graph (the current time) be the start to this interval
(e.g. 2/8 11:37am 2/8 12:07pm 2/8 12:37pm). Is this possible? Is there some sort of interval start point I can define?
Here is the relevant code:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"M/d h:mm a"];
if([[NSTimeZone systemTimeZone] isDaylightSavingTime]) {
NSLog(#"DLS");
}
[NSTimeZone resetSystemTimeZone];
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
CPTTimeFormatter *timeFormatter = [[CPTTimeFormatter alloc] initWithDateFormatter:dateFormatter];
timeFormatter.referenceDate = [NSDate dateWithTimeIntervalSinceReferenceDate:0];
axisSet.xAxis.labelFormatter = timeFormatter;
CPTMutableLineStyle *lineStyle = [CPTMutableLineStyle lineStyle];
lineStyle.lineColor = [CPTColor whiteColor];
lineStyle.lineWidth = 2.0f;
axisSet.xAxis.majorIntervalLength = [[NSDecimalNumber decimalNumberWithString:#"50"] decimalValue];
axisSet.xAxis.minorTicksPerInterval = 4;
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;
axisSet.yAxis.majorIntervalLength = [[NSDecimalNumber decimalNumberWithString:#"50"] decimalValue];
axisSet.yAxis.minorTicksPerInterval = 4;
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;
CPTScatterPlot *PowerPlot = [[CPTScatterPlot alloc] initWithFrame:self.view.bounds];
PowerPlot.identifier = #"PowerPlot";
CPTMutableLineStyle *PowerLine = [[CPTMutableLineStyle alloc] init];
[PowerLine setLineColor:[CPTColor redColor]];
[PowerLine setLineWidth:1.0f];
[PowerPlot setDataLineStyle:PowerLine];
PowerPlot.dataSource = self;
[MainGraph addPlot:PowerPlot];
CPTPlotSymbol *greenCirclePlotSymbol = [CPTPlotSymbol ellipsePlotSymbol];
greenCirclePlotSymbol.fill = [CPTFill fillWithColor:[CPTColor greenColor]];
greenCirclePlotSymbol.size = CGSizeMake(2.0, 2.0);
PowerPlot.plotSymbol = greenCirclePlotSymbol;
(void)RefreshGraph {
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)MainGraph.defaultPlotSpace;
NSRange YRange = [self getActiveGraphYRange];
NSInteger YIncrement = YRange.length/10;
long TimeInterval = 0;
switch (CurrentPeriod) {
case PERIOD_HOUR:
TimeInterval = OneHour;
break;
case PERIOD_DAY:
TimeInterval = OneDay;
break;
case PERIOD_WEEK:
TimeInterval = OneWeek;
break;
case PERIOD_MONTH:
TimeInterval = OneMonth;
break;
default:
break;
}
long StartTime = [[NSDate date] timeIntervalSinceReferenceDate];
if([DataPoints count] > 0) {
StartTime = [[(DataPoint *)[DataPoints objectAtIndex:0] Timestamp] timeIntervalSinceReferenceDate];
}
NSInteger XIncrement = TimeInterval/10;
NSInteger XMajorIncrement = XIncrement*5;
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)MainGraph.axisSet;
axisSet.xAxis.majorIntervalLength = [[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:#"%d",XMajorIncrement]] decimalValue];
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(StartTime - XIncrement- (XIncrement/3)) length:CPTDecimalFromFloat(TimeInterval + (2*XIncrement))];
}
else{
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(StartTime - XIncrement) length:CPTDecimalFromFloat(TimeInterval + (2*XIncrement))];
}
axisSet.yAxis.orthogonalCoordinateDecimal = CPTDecimalFromFloat(StartTime - XIncrement/5);
//axisSet.yAxis.
if([TypeControl selectedSegmentIndex] == 0) { //Power
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(-40) length:CPTDecimalFromFloat(YRange.length+40)];
axisSet.yAxis.visibleRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0) length:CPTDecimalFromFloat(YRange.length+15)];
axisSet.yAxis.majorIntervalLength = [[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:#"%d",YIncrement]] decimalValue];
}
else{
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(-15) length:CPTDecimalFromFloat(YRange.length+15)];
axisSet.yAxis.visibleRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0) length:CPTDecimalFromFloat(YRange.length+15)];
axisSet.yAxis.majorIntervalLength = [[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:#"%d",YIncrement]] decimalValue];
}
axisSet.xAxis.orthogonalCoordinateDecimal = CPTDecimalFromFloat(0);
} else { //Temp
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
plotSpace.yRange =
[CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(-4) length:CPTDecimalFromFloat(35)];
axisSet.yAxis.visibleRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0) length:CPTDecimalFromFloat(35)];
axisSet.yAxis.majorIntervalLength = [[NSDecimalNumber decimalNumberWithString:#"4"] decimalValue];
}
else{
plotSpace.yRange =
[CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(-2) length:CPTDecimalFromFloat(35)];
axisSet.yAxis.visibleRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0) length:CPTDecimalFromFloat(35)];
axisSet.yAxis.majorIntervalLength = [[NSDecimalNumber decimalNumberWithString:#"1"] decimalValue];
}
axisSet.xAxis.orthogonalCoordinateDecimal = CPTDecimalFromFloat(0);
}
[MainGraph reloadData];
}
Since you're using the default labeling policy (CPTAxisLabelingPolicyFixedInterval), you can use the labelingOrigin property on the axis to control where labeling starts. Set it to the starting location of the plot range.

Resources