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

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.

Related

How to show Line label with two digits after dote?

i use a core plot in my Xcode project and have a problem with plot values.
How can i show number on the CPTScatterPlot?
My plot shows me only one digit after dot (36.6).
For example show me 36.665 or 36.001?
I add a screen preview.
INIT
-(void)initLinePlotTmp
{
//Initialize and display Graph (x and y axis lines)
self.graph = [[CPTXYGraph alloc] initWithFrame:self.graphView.bounds];
self.hostView = [[CPTGraphHostingView alloc] initWithFrame:self.graphView.bounds];
self.hostView.hostedGraph = self.graph;
[self.graphView addSubview:hostView];
//apply styling to Graph
[self.graph applyTheme:[CPTTheme themeNamed:kCPTPlainWhiteTheme]];
//set graph backgound area transparent
self.graph.backgroundColor = nil;
self.graph.fill = nil;
self.graph.plotAreaFrame.fill = nil;
self.graph.plotAreaFrame.plotArea.fill = nil;
//This removes top and right lines of graph
self.graph.plotAreaFrame.borderLineStyle = nil;
//This shows x and y axis labels from 0 to 1
self.graph.plotAreaFrame.masksToBorder = NO;
// set padding for graph from Left and Bottom
self.graph.paddingBottom = 10;
self.graph.paddingLeft = 50;
self.graph.paddingRight = 0;
self.graph.paddingTop = 10;
//Define x and y axis range
// x-axis from 0 to 100
// y-axis from 0 to 300
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;
plotSpace.allowsUserInteraction = YES;
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(plotXMinRange)
length:CPTDecimalFromInt(plotXMaxRange)];
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(plotYMinRange)
length:CPTDecimalFromInt(plotYMaxRange)];
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)self.graph.axisSet;
NSNumberFormatter *axisLabelFormatter = [[NSNumberFormatter alloc]init];
[axisLabelFormatter setGeneratesDecimalNumbers:NO];
[axisLabelFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
//Define x-axis properties
//x-axis intermediate interval 2
axisSet.xAxis.majorIntervalLength = CPTDecimalFromInt(plotXInterval);
axisSet.xAxis.minorTicksPerInterval = 1;
axisSet.xAxis.minorTickLength = 5;
axisSet.xAxis.majorTickLength = 7;
axisSet.xAxis.title = #"Time(Hours)";
axisSet.xAxis.titleOffset = 25;
axisSet.xAxis.labelFormatter = axisLabelFormatter;
//Define y-axis properties
//y-axis intermediate interval = 50;
axisSet.yAxis.majorIntervalLength = CPTDecimalFromInt(plotYInterval);
axisSet.yAxis.minorTicksPerInterval = 4;
axisSet.yAxis.minorTickLength = 5;
axisSet.yAxis.majorTickLength = 7;
axisSet.yAxis.title = #"Temperature";
axisSet.yAxis.titleOffset = 30;
axisSet.yAxis.labelFormatter = axisLabelFormatter;
//Define line plot and set line properties
self.linePlot = [[CPTScatterPlot alloc] init];
self.linePlot.dataSource = self;
[self.graph addPlot:self.linePlot toPlotSpace:plotSpace];
//set line plot style
CPTMutableLineStyle *lineStyle = [self.linePlot.dataLineStyle mutableCopy];
lineStyle.lineWidth = 2;
lineStyle.lineColor = [CPTColor blackColor];
self.linePlot.dataLineStyle = lineStyle;
CPTMutableLineStyle *symbolineStyle = [CPTMutableLineStyle lineStyle];
symbolineStyle.lineColor = [CPTColor blackColor];
CPTPlotSymbol *symbol = [CPTPlotSymbol ellipsePlotSymbol];
symbol.fill = [CPTFill fillWithColor:[CPTColor blackColor]];
symbol.lineStyle = symbolineStyle;
symbol.size = CGSizeMake(3.0f, 3.0f);
self.linePlot.plotSymbol = symbol;
//set graph grid lines
CPTMutableLineStyle *gridLineStyle = [[CPTMutableLineStyle alloc] init];
gridLineStyle.lineColor = [CPTColor grayColor];
gridLineStyle.lineWidth = 0.5;
axisSet.xAxis.majorGridLineStyle = gridLineStyle;
axisSet.yAxis.majorGridLineStyle = gridLineStyle;
}
this is my function for plot init.
Create a NSNumberFormatter and configure it to format the labels however you want. Set the labelFormatter on the plot to the new formatter.
NSLog(#"Digit with Three decimal Values = %.3f",999.123456789);
This Prints 999.123 // three values after decimal point
Assign text to that label accordingly.
You are add to:
leftAxis.valueFormatter = leftAxis.valueFormatter;
//remove decimal
NSNumberFormatter *vf = [[NSNumberFormatter alloc] init];
vf.generatesDecimalNumbers = NO;
data.valueFormatter = vf;

Scroll only horizontally with two y axis with differentes scales

I have a graph wtih scatter plot and barplot and I have two y axis. I wnt to be able to scroll horizontally without the y axes moves. When I have only one y axis my code works but when I add the second one. The second still moving up and down. Have you some idee?
Here is my code :
-(void) configureAxes:(CPTGraphHostingView *)layerHostingView withTheme:(CPTTheme *)theme{
[super configureAxes:layerHostingView withTheme:theme];
CPTXYAxisSet *axisSet = (CPTXYAxisSet *) layerHostingView.hostedGraph.axisSet;
CPTAxis *x = axisSet.xAxis;
CPTAxis *y = axisSet.yAxis;
y.labelingPolicy = CPTAxisLabelingPolicyAutomatic;
x.labelingPolicy= CPTAxisLabelingPolicyNone;
NSMutableSet *xLabels = [NSMutableSet setWithCapacity:self.selectedExplYear.exploitation.count];
NSMutableSet *xLocations = [NSMutableSet setWithCapacity:self.selectedExplYear.exploitation.count];
for (int i = 0; i<self.selectedExplYear.exploitation.count; i++) {
SCExploitation *tech = self.selectedExplYear.exploitation[i];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"MMMM"];
NSDate *dateExploitation = [NSDate dateWithTimeIntervalSince1970:tech.exploitationDate.doubleValue/1000];
NSString *mois = [df stringFromDate:dateExploitation];
CPTAxisLabel *label = [[CPTAxisLabel alloc]initWithText:[NSString stringWithFormat:#"%#", mois] textStyle:x.labelTextStyle];
CGFloat location = i;
label.tickLocation = CPTDecimalFromCGFloat(location);
label.offset = x.majorTickLength;
if (label) {
[xLabels addObject:label];
[xLocations addObject:[NSNumber numberWithFloat:location]];
}
}
NSNumberFormatter *Xformatter = [[NSNumberFormatter alloc] init];
[Xformatter setGeneratesDecimalNumbers:NO];
[Xformatter setNumberStyle:NSNumberFormatterDecimalStyle];
y.labelFormatter = Xformatter;
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *) layerHostingView.hostedGraph.defaultPlotSpace;
CPTMutableTextStyle *axisTitleStyle = [CPTMutableTextStyle textStyle];
axisTitleStyle.color = [CPTColor whiteColor];
axisTitleStyle.fontName = #"Helvetica-Bold";
axisTitleStyle.fontSize = 14.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 = 14.0f;
CPTMutableLineStyle *tickLineStyle = [CPTMutableLineStyle lineStyle];
tickLineStyle.lineColor = [CPTColor whiteColor];
tickLineStyle.lineWidth = 2.0f;
tickLineStyle.lineColor = [CPTColor blackColor];
tickLineStyle.lineWidth = 1.0f;
x.axisLabels=xLabels;
x.majorTickLocations = xLocations;
axisSet.yAxis.axisConstraints = [CPTConstraints constraintWithLowerOffset:5];
y.visibleRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(0.0) length:CPTDecimalFromDouble(250)];
CPTXYAxis *y2 = [[CPTXYAxis alloc] init];
y2.coordinate = CPTCoordinateY;
y2.plotSpace = self.scatterGraphPlotSpace;
y2.axisConstraints = [CPTConstraints constraintWithUpperOffset:0];
y2.labelingPolicy = CPTAxisLabelingPolicyFixedInterval;
y2.axisLineStyle = axisLineStyle;
y2.majorTickLineStyle = axisLineStyle;
y2.title = #"Km";
y2.majorIntervalLength = CPTDecimalFromFloat((80 - 0) / 5.0f);
y2.labelFormatter = Xformatter;
y2.titleTextStyle = axisTextStyle;
y2.labelTextStyle = axisTextStyle;
y2.tickDirection = CPTSignNone;
y2.tickLabelDirection = CPTSignPositive;
y2.orthogonalCoordinateDecimal = CPTDecimalFromFloat(5.0);
y2.titleOffset = 16.0 * CPTFloat(-2.1);
y2.visibleRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(0.0) length:CPTDecimalFromDouble(80)];
self.scatterGraphPlotSpace.xRange = plotSpace.xRange;
layerHostingView.hostedGraph.axisSet.axes = [NSArray arrayWithObjects:x, y, y2, nil];
}
-(void)configurePlots:(CPTGraphHostingView *)layerHostingView withTheme:(CPTTheme *)theme
{
CPTGraph *graph = layerHostingView.hostedGraph;
CPTBarPlot *barPlotTotalDetenteEau = [CPTBarPlot tubularBarPlotWithColor:[CPTColor blueColor] horizontalBars:NO];
barPlotTotalDetenteEau.identifier = DETENTEEAUIDENTIFIER;
CPTMutableLineStyle *lsEauPotable = [[CPTMutableLineStyle alloc]init];
lsEauPotable.lineColor = [CPTColor lightGrayColor];
lsEauPotable.lineWidth = 0.5;
barPlotTotalDetenteEau.lineStyle = lsEauPotable;
barPlotTotalDetenteEau.dataSource =self;
barPlotTotalDetenteEau.delegate = self;
barPlotTotalDetenteEau.zPosition = 90;
barPlotTotalDetenteEau.labelOffset = LABELOFFSET;
barPlotTotalDetenteEau.title = NSLocalizedString(#"exploitation_detente_eau", nil);
barPlotTotalDetenteEau.barWidth = CPTDecimalFromDouble(BARWIDTH);
barPlotTotalDetenteEau.barOffset = CPTDecimalFromDouble(0);
[graph addPlot:barPlotTotalDetenteEau toPlotSpace:graph.defaultPlotSpace];
CPTBarPlot *barPlotTotalControleGaz = [CPTBarPlot tubularBarPlotWithColor:[CPTColor yellowColor] horizontalBars:NO];
barPlotTotalControleGaz.identifier = CONTROLEGAZIDENTIFIER;
CPTMutableLineStyle *lsNouveau = [[CPTMutableLineStyle alloc]init];
lsNouveau.lineColor = [CPTColor lightGrayColor];
lsNouveau.lineWidth = 0.5;
barPlotTotalControleGaz.lineStyle = lsNouveau;
barPlotTotalControleGaz.dataSource =self;
barPlotTotalControleGaz.delegate = self;
barPlotTotalControleGaz.zPosition = 100;
barPlotTotalControleGaz.labelOffset = LABELOFFSET;
barPlotTotalControleGaz.title = NSLocalizedString(#"exploitation_controle_gaz", nil);
barPlotTotalControleGaz.barWidth = CPTDecimalFromDouble(BARWIDTH);
barPlotTotalControleGaz.barOffset = CPTDecimalFromDouble(BARWIDTH+0.01);
[graph addPlot:barPlotTotalControleGaz toPlotSpace:graph.defaultPlotSpace];
self.scatterGraphPlotSpace = [[CPTXYPlotSpace alloc] init];
self.scatterGraphPlotSpace.allowsUserInteraction =YES;
// self.scatterGraphPlotSpace.delegate =self;
CPTScatterPlot *controlerPlot = [[CPTScatterPlot alloc] init];
controlerPlot.dataSource = self;
controlerPlot.delegate = self;
controlerPlot.title = NSLocalizedString(#"km_fuite", nil);
controlerPlot.identifier = KMCONTROLERIDENTIFIER;
controlerPlot.plotSymbolMarginForHitDetection = 15.0f;
CPTColor *effectivePlotColor = [CPTColor redColor];
[graph addPlot:controlerPlot toPlotSpace:self.scatterGraphPlotSpace];
CPTBarPlot *barPlotTotalControleEau = [CPTBarPlot tubularBarPlotWithColor:[CPTColor greenColor] horizontalBars:NO];
barPlotTotalControleEau.identifier = CONTROLEEAUIDENTIFIER;
CPTMutableLineStyle *lsProvisoire = [[CPTMutableLineStyle alloc]init];
lsProvisoire.lineColor = [CPTColor lightGrayColor];
lsProvisoire.lineWidth = 0.5;
barPlotTotalControleEau.lineStyle = lsProvisoire;
barPlotTotalControleEau.dataSource = self;
barPlotTotalControleEau.delegate = self;
barPlotTotalControleEau.zPosition = 100;
barPlotTotalControleEau.labelOffset = LABELOFFSET;
barPlotTotalControleEau.title = NSLocalizedString(#"exploitation_controle_eau", nil);
barPlotTotalControleEau.barWidth = CPTDecimalFromDouble(BARWIDTH);
barPlotTotalControleEau.barOffset = CPTDecimalFromDouble(0);
[graph addPlot:barPlotTotalControleEau toPlotSpace:graph.defaultPlotSpace];
CPTBarPlot *barPlotTotalDetenteGaz = [CPTBarPlot tubularBarPlotWithColor:[CPTColor grayColor] horizontalBars:NO];
barPlotTotalDetenteGaz.identifier = DETENTEGAZIDENTIFIER;
CPTMutableLineStyle *lsAugmentation = [[CPTMutableLineStyle alloc]init];
lsAugmentation.lineColor = [CPTColor lightGrayColor];
lsAugmentation.lineWidth = 0.5;
barPlotTotalDetenteGaz.lineStyle = lsAugmentation;
barPlotTotalDetenteGaz.dataSource =self;
barPlotTotalDetenteGaz.delegate = self;
barPlotTotalDetenteGaz.zPosition = 70;
barPlotTotalDetenteGaz.labelOffset = LABELOFFSET;
barPlotTotalDetenteGaz.title = NSLocalizedString(#"exploitation_detente_gaz", nil);
barPlotTotalDetenteGaz.barWidth = CPTDecimalFromDouble(BARWIDTH);
barPlotTotalDetenteGaz.barOffset = CPTDecimalFromDouble(BARWIDTH+0.01);
[graph addPlot:barPlotTotalDetenteGaz toPlotSpace:graph.defaultPlotSpace];
NSArray *plots = #[barPlotTotalDetenteEau,barPlotTotalControleEau,barPlotTotalControleGaz,barPlotTotalDetenteGaz];
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *) graph.defaultPlotSpace;
[plotSpace scaleToFitPlots:plots];
CPTMutablePlotRange *xRange = [plotSpace.xRange mutableCopy];
[xRange expandRangeByFactor:CPTDecimalFromCGFloat(1.3f)];
xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(-0.5f) length:CPTDecimalFromFloat(4.0f)];
plotSpace.xRange = xRange;
CPTMutablePlotRange *yRange = [plotSpace.yRange mutableCopy];
[yRange expandRangeByFactor:CPTDecimalFromCGFloat(1.4f)];
plotSpace.yRange = yRange;
plotSpace.delegate = self;
self.scatterGraphPlotSpace.globalYRange = plotSpace.globalYRange;
CPTScatterPlot *visuelPlot = [[CPTScatterPlot alloc] init];
visuelPlot.dataSource = self;
visuelPlot.delegate = self;
visuelPlot.title = NSLocalizedString(#"km_visuel", nil);
visuelPlot.identifier = KMVISUELIDENTIFIER;
visuelPlot.plotSymbolMarginForHitDetection = 15.0f;
CPTColor *budgeteePlotColor = [CPTColor orangeColor];
CPTMutableLineStyle *budgeteelLineStyle = [CPTMutableLineStyle lineStyle]; // [budgeteePlot.dataLineStyle mutableCopy];
budgeteelLineStyle.lineWidth = 2.5;
budgeteelLineStyle.lineColor = budgeteePlotColor;
visuelPlot.dataLineStyle = budgeteelLineStyle;
CPTPlotSymbol *budgeteeSymbol = [CPTPlotSymbol ellipsePlotSymbol];
budgeteeSymbol.fill = [CPTFill fillWithColor:budgeteePlotColor];
budgeteeSymbol.lineStyle = budgeteelLineStyle;
budgeteeSymbol.size = CGSizeMake(6.0f, 6.0f);
visuelPlot.plotSymbol = budgeteeSymbol;
CPTMutableLineStyle *effectiveLineStyle = [CPTMutableLineStyle lineStyle];
effectiveLineStyle.lineWidth = 2.5;
effectiveLineStyle.lineColor = effectivePlotColor;
controlerPlot.dataLineStyle = effectiveLineStyle;
CPTPlotSymbol *effectiveSymbol = [CPTPlotSymbol ellipsePlotSymbol];
effectiveSymbol.fill = [CPTFill fillWithColor:effectivePlotColor];
effectiveSymbol.lineStyle = effectiveLineStyle;
effectiveSymbol.size = CGSizeMake(6.0f, 6.0f);
controlerPlot.plotSymbol = effectiveSymbol;
[self.scatterGraphPlotSpace scaleToFitPlots:[NSArray arrayWithObjects:controlerPlot, visuelPlot, nil]];
[graph addPlot:visuelPlot toPlotSpace:self.scatterGraphPlotSpace];
CPTPlotRange *globalYRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(0) length:CPTDecimalFromDouble(250)];
plotSpace.globalYRange = globalYRange;
self.scatterGraphPlotSpace.yRange =[CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0)
length:CPTDecimalFromFloat(80)];
CPTMutablePlotRange *y2Range = [self.scatterGraphPlotSpace.yRange mutableCopy];
[y2Range expandRangeByFactor:CPTDecimalFromCGFloat(1.4f)];
self.scatterGraphPlotSpace.yRange = y2Range;
[layerHostingView.hostedGraph addPlotSpace:self.scatterGraphPlotSpace];
}
-(void)configureGraph:(CPTGraphHostingView *)layerHostingView withTheme:(CPTTheme *)theme
{
CPTGraph *graph = [[CPTXYGraph alloc] initWithFrame:layerHostingView.bounds];
graph.plotAreaFrame.masksToBorder = NO;
layerHostingView.hostedGraph = graph;
if(self.selectedExplYear.exploitation.count> 3){
graph.defaultPlotSpace.allowsUserInteraction = YES;
}
[graph applyTheme:self.theme];
graph.paddingBottom = 60.0f;
graph.paddingLeft = 30.0f;
graph.paddingTop = 30.0f;
graph.paddingRight = 30.0f;
graph.title = nil;
}
-(CGPoint)plotSpace:(CPTPlotSpace *)space willDisplaceBy:(CGPoint)displacement
{
return CGPointMake(displacement.x, 0);
}
-(CPTPlotRange *)plotSpace:(CPTPlotSpace *)space willChangePlotRangeTo:(CPTPlotRange *)newRange forCoordinate:(CPTCoordinate)coordinate
{
if (space == self.scatterGraphPlotSpace) {
if (coordinate == CPTCoordinateY) {
newRange = self.scatterGraphPlotSpace.yRange;
}
}else{
if (coordinate == CPTCoordinateY) {
newRange = ((CPTXYPlotSpace*)space).yRange;
}
}
return newRange;
}
Thanks a lot
Set the delegate for self.scatterGraphPlotSpace. That line of code is commented out in the code you posted.

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.

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