The axis lines and tick marks for my graph don't appear when I set hostingView.collapsesLayers = NO. When I set hostingView.collapsesLayers = YES, they do appear. Any idea what might be causing this situation?
I've tried changing up the chart layer order, but no order (that I've tried) seems to make the axis lines appear. The issue also doesn't seem to be related to the background color of the hosting view or fill color of the graph, which I've tried setting to be clear for both.
The axis labels are appearing and in the correct locations.
EDIT: Grid lines and annotations are also all appearing. Everything is appearing as it should except the axis lines and tick marks.
EDIT2: Graph setup code, called in viewDidAppear
//create graph and hosting view
_graph = [[CPTXYGraph alloc] initWithFrame:_graphHostingView.frame];
_graphHostingView.hostedGraph = _graph;
_graphHostingView.collapsesLayers = NO;
//format graph
CGFloat graphPadding = 0.0f;
_graph.paddingBottom = graphPadding;
_graph.paddingLeft = graphPadding;
_graph.paddingRight = graphPadding;
_graph.paddingTop = graphPadding;
_graph.fill = [CPTFill fillWithColor:[CPTColor whiteColor]];
CGFloat plotPadding = 20.0f;
_graph.plotAreaFrame.paddingBottom = plotPadding;
_graph.plotAreaFrame.paddingLeft = plotPadding;
_graph.plotAreaFrame.paddingRight = plotPadding;
_graph.plotAreaFrame.paddingTop = plotPadding;
//configure plot spaces
_rightAxisPlotSpace = [[CPTXYPlotSpace alloc] init];
[_graph addPlotSpace:_rightAxisPlotSpace];
//init axes
_xAxis = [[CPTXYAxis alloc] init];
_xAxis.coordinate = CPTCoordinateX;
_xAxis.plotSpace = _graph.defaultPlotSpace;
_yAxisLeft = [[CPTXYAxis alloc] init];
_yAxisLeft.coordinate = CPTCoordinateY;
_yAxisLeft.plotSpace = _graph.defaultPlotSpace;
_yAxisRight = [[CPTXYAxis alloc] init];
_yAxisRight.coordinate = CPTCoordinateY;
_yAxisRight.plotSpace = _rightAxisPlotSpace;
_xAxis.axisConstraints = [CPTConstraints constraintWithLowerOffset:0.0f];
_yAxisLeft.axisConstraints = [CPTConstraints constraintWithLowerOffset:0.0f];
_yAxisRight.axisConstraints = [CPTConstraints constraintWithUpperOffset:0.0f];
_xAxis.tickDirection = CPTSignNegative;
_yAxisLeft.tickDirection = CPTSignNegative;
_yAxisRight.tickDirection = CPTSignPositive;
CPTAxisSet* axisSet = [[CPTAxisSet alloc] init];
axisSet.axes = [NSArray arrayWithObjects:_xAxis, _yAxisLeft, _yAxisRight, nil];
_graph.axisSet = axisSet;
//format axes
CPTMutableLineStyle* axisStyle = [CPTMutableLineStyle lineStyle];
axisStyle.lineWidth = 0.75f;
axisStyle.lineColor = [CPTColor colorWithCGColor:DARK_GRAY.CGColor];
CPTMutableLineStyle* axisTickStyle = [CPTMutableLineStyle lineStyle];
axisTickStyle.lineWidth = 0.5f;
axisTickStyle.lineColor = axisStyle.lineColor;
CPTMutableLineStyle* gridStyle = [CPTMutableLineStyle lineStyle];
gridStyle.lineWidth = 0.25f;
gridStyle.lineColor = [CPTColor colorWithCGColor:LIGHT_GRAY.CGColor];
CPTMutableTextStyle* labelTextStyle = [CPTMutableTextStyle textStyle];
labelTextStyle.fontName = FONT_REGULAR;
labelTextStyle.fontSize = 8.0f;
labelTextStyle.color = [CPTColor colorWithCGColor:DARK_GRAY.CGColor];
CPTMutableTextStyle* leftAxisTitleStyle = [CPTMutableTextStyle textStyle];
leftAxisTitleStyle.fontName = FONT_HEAVY;
leftAxisTitleStyle.fontSize = 10.0f;
leftAxisTitleStyle.color = [CPTColor colorWithCGColor:BLUE.CGColor];
CPTMutableTextStyle* rightAxisTitleStyle = [CPTMutableTextStyle textStyle];
rightAxisTitleStyle.fontName = FONT_HEAVY;
rightAxisTitleStyle.fontSize = 10.0f;
rightAxisTitleStyle.color = [CPTColor colorWithCGColor:YELLOW.CGColor];
CPTTimeFormatter* calendarFormatter = [[CPTTimeFormatter alloc] initWithDateFormatter:_dateFormatter];
_xAxis.majorGridLineStyle = gridStyle;
_xAxis.labelFormatter = calendarFormatter;
NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setMinimumFractionDigits:0];
[numberFormatter setMaximumFractionDigits:2];
_yAxisLeft.majorGridLineStyle = gridStyle;
_yAxisLeft.minorGridLineStyle = gridStyle;
_yAxisLeft.titleTextStyle = leftAxisTitleStyle;
_yAxisLeft.titleOffset = 20.0f;
_yAxisLeft.labelFormatter = numberFormatter;
_yAxisRight.majorGridLineStyle = nil;
_yAxisRight.minorGridLineStyle = nil;
_yAxisRight.titleTextStyle = rightAxisTitleStyle;
_yAxisRight.titleOffset = 20.0f;
_yAxisRight.titleRotation = 3.0f*M_PI/2.0f;
_yAxisRight.labelFormatter = numberFormatter;
for(CPTXYAxis* axis in _graph.axisSet.axes)
{
axis.labelingPolicy = CPTAxisLabelingPolicyAutomatic;
axis.preferredNumberOfMajorTicks = 7;
axis.minorTicksPerInterval = 0;
axis.majorTickLineStyle = axisTickStyle;
axis.minorTickLineStyle = axisTickStyle;
axis.axisLineStyle = axisStyle;
axis.labelTextStyle = labelTextStyle;
axis.majorTickLength = 3.0f;
axis.minorTickLength = 1.5f;
axis.labelOffset = 0.0f;
}
//set chart layer order
NSArray* chartLayers = [NSArray arrayWithObjects:[NSNumber numberWithInteger:CPTGraphLayerTypeAxisLines],
[NSNumber numberWithInteger:CPTGraphLayerTypeAxisLabels],
[NSNumber numberWithInteger:CPTGraphLayerTypePlots],
[NSNumber numberWithInteger:CPTGraphLayerTypeMajorGridLines],
[NSNumber numberWithInteger:CPTGraphLayerTypeMinorGridLines],
[NSNumber numberWithInteger:CPTGraphLayerTypeAxisTitles], nil];
_graph.topDownLayerOrder = chartLayers;
Instead of replacing the default axis set, just set your new axes array to it:
_graph.axisSet.axes = #[_xAxis, _yAxisLeft, _yAxisRight];
You are replacing a CPTXYAxisSet with a CPTAxisSet that doesn't know how to lay out and draw the x-y axes.
Related
I am using CorePlot to plot a simple Line Graph in my macOS app.
CPTXYGraph *newGraph = [[CPTXYGraph alloc] initWithFrame:CGRectZero];
CPTTheme *theme = [CPTTheme themeNamed:kCPTDarkGradientTheme];
[newGraph applyTheme:theme];
self.graph = newGraph;
self.hostView.hostedGraph = newGraph;
newGraph.plotAreaFrame.paddingTop = 10.0;
newGraph.plotAreaFrame.paddingBottom = 30.0;
newGraph.plotAreaFrame.paddingLeft = 40.0;
newGraph.plotAreaFrame.paddingRight = 10.0;
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)newGraph.defaultPlotSpace;
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:#(1.0) length:[NSNumber numberWithUnsignedInteger:[dataArray count]-1]];
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:#0.0 length:#102.0];
plotSpace.allowsUserInteraction = YES;
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)newGraph.axisSet;
CPTXYAxis *x = axisSet.xAxis;
//x.majorIntervalLength = #1;
x.majorIntervalLength = [NSNumber numberWithInt:numberOfIntervalsX];
x.orthogonalPosition = #(0);
x.minorTicksPerInterval = 0;
x.labelOffset = 0;
CPTXYAxis *y = axisSet.yAxis;
y.majorIntervalLength = #5;
y.minorTicksPerInterval = 0;
y.orthogonalPosition = #(1.0);
y.labelOffset = 0.0;
CPTScatterPlot *dataSourceLinePlot = [[CPTScatterPlot alloc] init];
CPTMutableLineStyle *lineStyle = [dataSourceLinePlot.dataLineStyle mutableCopy];
lineStyle.lineWidth = 2.;
lineStyle.lineColor = [CPTColor greenColor];
dataSourceLinePlot.dataLineStyle = lineStyle;
dataSourceLinePlot.dataSource = self;
[newGraph addPlot:dataSourceLinePlot];
I was expecting that the hover/ click to see values would be a default behavior but looks it is not. I have tried searching the forums but no luck. I am assuming it would be really straight forward. Not sure if I am missing something.
As far as i know, you're impression is correct, there is no built in data value overlay. However, you can make it yourself. CorePlot has the function indexOfVisiblePointClosestToPlotAreaPoint: that should give you the references needed to add a label w/ point value to your chart.
(NSUInteger) indexOfVisiblePointClosestToPlotAreaPoint:
Returns the index of the closest point, or NSNotFound if there is no visible point.
Then you can subclass your graph hostingview, implement a mouse movement event to capture mouse coordinates, and from there to do whatever logic you want to chose how to display the points.
I wouldn't say it's particularly easy to implement, but at least its straight foward. I hope it helps!
References:
http://core-plot.github.io/MacOS/interface_c_p_t_scatter_plot.html#a57eacc8261a4d4a1399f1196be786cff
https://stackoverflow.com/a/21819342/357288
I have two plot spaces
//First Plot Space
self.plotSpace1 =(CPTXYPlotSpace *) self.hostingView.hostedGraph.defaultPlotSpace;
[self.plotSpace1 setYRange: [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0) length:CPTDecimalFromFloat(100)]];
[self.plotSpace1 setXRange: [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(([startNumber floatValue]/1000000) ) length:CPTDecimalFromFloat( ([endLength floatValue]/1000000))]];
//Second Plot Space
self.plotSpace2 =(CPTXYPlotSpace *) [self.hostingView.hostedGraph newPlotSpace];
[self.plotSpace2 setGraph:self.hostingView.hostedGraph];
[self.plotSpace2 setYRange: [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0) length:CPTDecimalFromFloat(1)]];
[self.plotSpace2 setXRange: [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat( ([startNumber floatValue]/1000000) ) length:CPTDecimalFromFloat( ([endLength floatValue]/1000000) )]];
[self.plotSpace2 setIdentifier:#"PLOT2"];
[self.plotSpace2 setAllowsUserInteraction:YES];
[self.hostingView.hostedGraph addPlotSpace:self.plotSpace2];
When I add a plot to the second plot space like so
CPTScatterPlot* plot = [[CPTScatterPlot alloc] initWithFrame:CGRectZero];
plot.title = plotTitle;
plot.dataSource = self;
[plot setPlotSpace:self.plotSpace2];
[self.hostingView.hostedGraph addPlot:plot toPlotSpace:self.plotSpace2];
I add a second y axis like so - the second y axis is displayed
CPTXYAxis *rightY = [(CPTXYAxis *)[CPTXYAxis alloc] initWithFrame:CGRectZero];
rightY.axisConstraints = [CPTConstraints constraintWithUpperOffset:0.0];
rightY.coordinate = CPTCoordinateY;
rightY.plotSpace = self.plotSpace2;
//Labeling and intervals
rightY.labelingPolicy = CPTAxisLabelingPolicyFixedInterval;
rightY.majorIntervalLength = CPTDecimalFromCGFloat(0.1f);
rightY.minorTicksPerInterval = 5;
rightY.orthogonalCoordinateDecimal = CPTDecimalFromDouble(self.plotSpace2.xRange.locationDouble + self.plotSpace2.xRange.lengthDouble);
rightY.title = nil;
//Format and position
rightY.titleTextStyle = axisTitleStyle;
rightY.titleOffset = 20.0f;
rightY.axisLineStyle = axisLineStyle;
rightY.labelTextStyle = axisTextStyle;
rightY.labelOffset = 2.0f;
rightY.majorTickLineStyle = axisLineStyle;
rightY.majorTickLength = 4.0f;
rightY.minorTickLength = 2.0f;
rightY.tickDirection = CPTSignPositive;
axisSet.axes = [NSArray arrayWithObjects:x, y, rightY, nil];
The line is not plotted. However, if I add it to plotSpace1 (the default plot space) it is plotted.
I have been stuck on this for a while now. I have searched and searched like crazy for an answer. Any help is appreciated.
The first plot space has a yRange from 0 to 100 while the second yRange extends between 0 and 1. The plot data is probably outside the visible plot range.
You should only add the plot to the graph once:
CPTScatterPlot* plot = [[CPTScatterPlot alloc] initWithFrame:CGRectZero];
plot.title = plotTitle;
plot.dataSource = self;
[self.hostingView.hostedGraph addPlot:plot toPlotSpace:self.plotSpace2];
I am trying to set up two charts similar to the AAPlot sample provided with Core Plot.
It basically consists of a stock chart, which is shown almost correctly and a second chart (volume chart), which should be placed directly below the stock chart. Both charts should share the same x axis.
Unfortunately the volume chart's data is not being plotted in my app.
Even though I intensely compared the sample source code with mine, I do not find the source of my error.
Could you please point me to right direction?
This is my code:
- (void)configureChart
{
self.graph = [[CPTXYGraph alloc] initWithFrame:self.hostView.bounds];
self.hostView.hostedGraph = self.graph;
self.graph.paddingLeft = 0.0f;
self.graph.paddingTop = 0.0f;
self.graph.paddingRight = 0.0f;
self.graph.paddingBottom = 0.0f;
self.graph.axisSet = nil;
// 2 - Set up text style
CPTMutableTextStyle *textStyle = [CPTMutableTextStyle textStyle];
textStyle.color = [CPTColor grayColor];
textStyle.fontName = #"Helvetica-Bold";
textStyle.fontSize = 16.0f;
// 3 - Configure title
NSString *title = self.issue.company.companyName;
_graph.title = title;
_graph.titleTextStyle = textStyle;
_graph.titlePlotAreaFrameAnchor = CPTRectAnchorTop;
_graph.titleDisplacement = CGPointMake(0.0f, -12.0f);
// 4 - Set theme
[self.graph applyTheme:[CPTTheme themeNamed:kCPTStocksTheme]];
_graph.plotAreaFrame.cornerRadius = 0.0f;
CPTMutableLineStyle *borderLineStyle = [CPTMutableLineStyle lineStyle];
borderLineStyle.lineColor = [CPTColor whiteColor];
borderLineStyle.lineWidth = 2.0f;
_graph.plotAreaFrame.borderLineStyle = borderLineStyle;
// Axes
CPTXYAxisSet *xyAxisSet = (id)self.graph.axisSet;
CPTXYAxis *xAxis = xyAxisSet.xAxis;
CPTMutableLineStyle *lineStyle = [xAxis.axisLineStyle mutableCopy];
lineStyle.lineCap = kCGLineCapButt;
xAxis.axisLineStyle = lineStyle;
xAxis.labelingPolicy = CPTAxisLabelingPolicyNone;
CPTXYAxis *yAxis = xyAxisSet.yAxis;
yAxis.axisLineStyle = nil;
// OHLC plot
CPTMutableLineStyle *whiteLineStyle = [CPTMutableLineStyle lineStyle];
whiteLineStyle.lineColor = [CPTColor whiteColor];
whiteLineStyle.lineWidth = 1.0f;
CPTTradingRangePlot *ohlcPlot = [[CPTTradingRangePlot alloc] initWithFrame:self.graph.bounds];
ohlcPlot.identifier = #"OHLC";
ohlcPlot.lineStyle = whiteLineStyle;
CPTMutableTextStyle *whiteTextStyle = [CPTMutableTextStyle textStyle];
whiteTextStyle.color = [CPTColor whiteColor];
whiteTextStyle.fontSize = 8.0;
ohlcPlot.labelTextStyle = whiteTextStyle;
ohlcPlot.labelOffset = 5.0;
ohlcPlot.stickLength = 2.0f;
ohlcPlot.dataSource = self;
ohlcPlot.plotStyle = CPTTradingRangePlotStyleOHLC;
[self.graph addPlot:ohlcPlot];
// Add volume plot space
CPTXYPlotSpace *volumePlotSpace = [[CPTXYPlotSpace alloc] init];
volumePlotSpace.identifier = #"Volume";
[_graph addPlotSpace:volumePlotSpace];
CPTBarPlot *volumePlot = [CPTBarPlot tubularBarPlotWithColor:[CPTColor whiteColor] horizontalBars:NO];
volumePlot.dataSource = self;
lineStyle = [volumePlot.lineStyle mutableCopy];
lineStyle.lineColor = [CPTColor whiteColor];
volumePlot.lineStyle = lineStyle;
volumePlot.fill = nil;
volumePlot.barWidth = CPTDecimalFromFloat(1.0f);
volumePlot.identifier = #"Volume Plot";
[_graph addPlot:volumePlot toPlotSpace:volumePlotSpace];
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *) self.graph.defaultPlotSpace;
[plotSpace scaleToFitPlots:[self.graph allPlots]];
}
What happens when you just do [_graph addPlot:volumePlot] instead of [_graph addPlot toPlotSpace:volumePlotSpace]?
I'm thinking that you may have added some extra restraints using all of those various plot spaces and that is keeping both of your plots from showing up.
I'm not entirely sure though to be honest, I've just been learning Core Plot as well, most solutions I've come up are a result of lots of playing around and googling. I'll edit this post if I think of something else.
You never set the plot space ranges for the volume plot space. It still has the default x and y ranges of [0, 1].
Hi All
Can someone help me with this problem I have encountered
Can I plot a bargraph in coreplote with unequal bar width meaning Say my X-axis interval is 1 unit and I have set the bar graph width as same 1 unit. But there are certain points where x-axis value changes at 0.5units and i want the bar width to be equal to the width where change has occurred. And the data is dynamically changing. Is there any other solution that I can use and still looks like a bar graph. The only reason for using bar is I need to fill the plot space.
CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)barChart.defaultPlotSpace;
plotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromInt(0)
length:CPDecimalFromInt(rangeY)];
plotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(-0.5f)
length:CPDecimalFromFloat(rangeX)];
CPXYAxisSet *axisSet = (CPXYAxisSet *)barChart.axisSet;
CPXYAxis *x = axisSet.xAxis;
x.axisLineStyle = nil;
x.majorTickLineStyle = nil;
x.minorTickLineStyle = nil;
x.majorIntervalLength = CPDecimalFromString(#"1");
x.orthogonalCoordinateDecimal = CPDecimalFromString(#"0");
x.title = [[[tempCol colName] componentsSeparatedByString:#"*#"] objectAtIndex:0];
x.titleLocation = CPDecimalFromFloat((rangeX-1)/2);
x.titleOffset = 25.0f;
// Define some custom labels for the data elements
x.labelRotation = 0;
x.labelingPolicy = CPAxisLabelingPolicyNone;
NSMutableArray *customTickLocations = [[NSMutableArray alloc] init];
NSMutableArray *xAxisLabels = [[NSMutableArray alloc] init];
for (int i = 0; i < [tempGraph.d2pArray count]; i++) {
tempD2P = [tempGraph.d2pArray objectAtIndex:i];
[customTickLocations addObject:[NSNumber numberWithInt:i]];
[xAxisLabels addObject:[tempD2P d2pName]];
}
NSUInteger labelLocation = 0;
NSMutableArray *customLabels = [NSMutableArray arrayWithCapacity:[xAxisLabels count]];
for (NSNumber *tickLocation in customTickLocations) {
CPAxisLabel *newLabel = [[CPAxisLabel alloc]
initWithText:[xAxisLabels objectAtIndex:labelLocation++]
textStyle:x.labelTextStyle];
newLabel.tickLocation = [tickLocation decimalValue];
newLabel.offset = 0;
newLabel.rotation = 0;
newLabel.alignment = CPAlignmentCenter;
[customLabels addObject:newLabel];
[newLabel release];
newLabel = nil;
}
[xAxisLabels release];
xAxisLabels = nil;
[customTickLocations release];
customTickLocations = nil;
x.axisLabels = [NSSet setWithArray:customLabels];
CPXYAxis *y = axisSet.yAxis;
CPLineStyle *majorGridLineStyle = [CPLineStyle lineStyle];
majorGridLineStyle.lineWidth = 0.75;
majorGridLineStyle.lineColor = [CPColor colorWithCGColor:[[UIColor grayColor] CGColor]];
y.axisLineStyle = nil;
y.majorTickLineStyle = nil;
y.majorGridLineStyle = majorGridLineStyle;
y.minorTickLineStyle = nil;
y.majorIntervalLength = CPDecimalFromInt(rangeY/8);
y.orthogonalCoordinateDecimal = CPDecimalFromString(#"-0.5");
y.title = [[[tempCol colName] componentsSeparatedByString:#"*#"] objectAtIndex:1];
y.titleOffset = 30 + 5*log10(mult);
y.titleLocation = CPDecimalFromInt(rangeY/2);
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:0];
y.labelFormatter = formatter;
[formatter release];
formatter = nil;
char firstChar = 'F';
CPBarPlot *barPlot;
// First bar plot
for (int i = 0; i < noOfBarCharts; i++) {
static CPTextStyle *whiteText = nil;
if ( !whiteText ) {
whiteText = [[CPTextStyle alloc] init];
whiteText.color = [CPColor whiteColor];
whiteText.fontSize = 14;
}
barPlot = [CPBarPlot tubularBarPlotWithColor:[CPColor colorWithComponentRed:[[[rgbArray objectAtIndex:0] objectAtIndex:i] floatValue]/255.0
green:[[[rgbArray objectAtIndex:1] objectAtIndex:i] floatValue]/255.0
blue:[[[rgbArray objectAtIndex:2] objectAtIndex:i] floatValue]/255.0
alpha:1.0]
horizontalBars:NO];
barPlot.baseValue = CPDecimalFromString(#"0");
barPlot.dataSource = self;
barPlot.barOffset = ([tempGraph.graType rangeOfString:#"GROUPED"].location != NSNotFound)?(i+0.5)-(noOfBarCharts/2):0;
barPlot.labelOffset = 0;
barPlot.barWidth = 20;
barPlot.identifier = [NSString stringWithFormat:#"%d%c", [tempGraph.graID intValue], (firstChar - noOfBarCharts +1 + i)];
barPlot.delegate = self;
[barChart addPlot:barPlot
toPlotSpace:plotSpace];
I figured it out myself instead of using a bar chart i used a scatter plot with step graph That did the trick :
Plot.interpolation = CPTScatterPlotInterpolationStepped;
and filled the plot with:
Plot.areaFill = [CPTFill fillWithColor:[CPTColor blueColor]];
Plot.areaBaseValue = CPTDecimalFromInteger(0);
If you're not putting a border line on the bars, you could make the bar width half the distance between bars and double-up the wide ones.
I have been playing with Core Plot and trying to create a dynamic date x-axis. From the date plot example I have managed to create a static date axis, but would like to create a two-minute window at any time and update the xRange values. I am not sure on how to pass dates as the xRange min and length values and display time on the x-axis.
I have looked at examples, but I haven't been able to utilize NSTimeInterval (if this is how to do it...).
Below is the picture (if it helps)
Below is my attempt so far; can someone please advise me on how to achieve this?
- (void)loadView {
// Alloc & Init Main View and since the display resolution is 1024x768 take 20 off for labels later
UIView *tmpView = [ [ UIView alloc ] initWithFrame:CGRectMake(0, 0, 1024.0,768.0) ];
[ tmpView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight ];
[ tmpView setBackgroundColor:[ UIColor redColor ] ];
// Alloc Graph View
graphView = [ [ CPGraphHostingView alloc ] initWithFrame:CGRectMake(0, 0, 1024.0,768.0) ];
[ tmpView addSubview:[ graphView autorelease ] ];
// Set MainView
[ self setView:[ tmpView autorelease ] ];
}
-(void)viewDidLoad{
[super viewDidLoad];
NSDate *refDate = [NSDate date];
// NSTimeInterval oneDay = 24 * 60 * 60;
NSTimeInterval oneHour = 60 * 60;
NSTimeInterval fivemin= 5 * 60;
// Create graph from theme
graph = [(CPXYGraph *) [CPXYGraph alloc] initWithFrame:self.view.bounds];
CPTheme *theme = [CPTheme themeNamed:kCPDarkGradientTheme];
[graph applyTheme:theme];
graphView.hostedGraph = graph;
//padding
graph.paddingLeft = 20.0;
graph.paddingTop = 20.0;
graph.paddingRight = 20.0;
graph.paddingBottom = 20.0;
graph.plotAreaFrame.paddingTop=10.0;
graph.plotAreaFrame.paddingLeft=50.0;
graph.plotAreaFrame.paddingRight=35.0;
graph.plotAreaFrame.paddingBottom=50.0;
// Setup scatter plot space
CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)graph.defaultPlotSpace;
NSTimeInterval xLow = 0.0f;
plotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(xLow) length:CPDecimalFromFloat(oneHour)];
plotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0.0f) length:CPDecimalFromFloat(100.0f)];
//Line Styles
CPLineStyle *lineStyle = [CPLineStyle lineStyle];
lineStyle.lineColor = [CPColor redColor];
lineStyle.lineWidth = 2.0f;
CPLineStyle *majorGridLineStyle = [CPLineStyle lineStyle];
majorGridLineStyle.lineWidth = 0.75;
majorGridLineStyle.lineColor = [[CPColor colorWithGenericGray:0.2] colorWithAlphaComponent:0.75];
CPLineStyle *minorGridLineStyle = [CPLineStyle lineStyle];
minorGridLineStyle.lineWidth = 0.25;
minorGridLineStyle.lineColor = [[CPColor whiteColor] colorWithAlphaComponent:0.1];
CPXYAxisSet *axisSet = (CPXYAxisSet *)graph.axisSet;
// X-Axes formatting
CPXYAxis *x = axisSet.xAxis;
x.majorIntervalLength = CPDecimalFromFloat(oneHour);
x.orthogonalCoordinateDecimal = CPDecimalFromString(#"0");
x.minorTicksPerInterval = 0;
x.labelOffset=0;
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
dateFormatter.dateStyle = kCFDateFormatterShortStyle;
CPTimeFormatter *timeFormatter = [[[CPTimeFormatter alloc] initWithDateFormatter:dateFormatter] autorelease];
timeFormatter.referenceDate = refDate;
x.labelFormatter = timeFormatter;
x.majorGridLineStyle = majorGridLineStyle;
x.minorGridLineStyle = minorGridLineStyle;
x.title=#"Time Axis";
//Y-Axes formatting
CPXYAxis *y = axisSet.yAxis;
y.majorIntervalLength = [ [ NSDecimalNumber decimalNumberWithString:#"10.0" ] decimalValue ];
y.orthogonalCoordinateDecimal = CPDecimalFromString(#"0");
y.minorTicksPerInterval = 5;
y.labelOffset = 0.0;
y.majorGridLineStyle = majorGridLineStyle;
y.minorGridLineStyle = minorGridLineStyle;
y.preferredNumberOfMajorTicks = 10;
y.minorTickLineStyle = nil;
y.labelTextStyle = nil;
y.visibleRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0.0f) length:CPDecimalFromFloat(100.0f)];
CPConstraints yConstraints = {CPConstraintFixed, CPConstraintFixed};
y.isFloatingAxis=YES;
y.constraints=yConstraints;
// Create a plot that uses the data source method
CPScatterPlot *dataSourceLinePlot = [[[CPScatterPlot alloc] init] autorelease];
dataSourceLinePlot.identifier = #"Date Plot";
dataSourceLinePlot.dataLineStyle = lineStyle;
dataSourceLinePlot.dataSource = self;
[graph addPlot:dataSourceLinePlot];
mydata = [[NSMutableArray alloc]initWithObjects:
[NSDecimalNumber numberWithInt:0],
nil ];
//a timer to re-load the graph every 2 seconds and re-draw x-axis
Timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:#selector(testingTimer:) userInfo:nil repeats:YES];
}
-(NSUInteger)numberOfRecordsForPlot:(CPPlot *)plot
{
return mydata.count;
}
-(NSNumber *)numberForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
switch ( fieldEnum ) {
case CPScatterPlotFieldX:
return (NSDecimalNumber *)[NSDecimalNumber numberWithUnsignedInteger:index];
case CPScatterPlotFieldY:
return [mydata objectAtIndex:index];
}
return nil;
}
-(void) testingTimer: (NSTimer *) Timer{
//generating random number and add to mydata array
testdata=arc4random() % 100;
[mydata addObject:[NSNumber numberWithInt:testdata]];
[graph reloadData];
count++;
CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)graph.defaultPlotSpace;
plotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(count) length:CPDecimalFromFloat(5*30.0f)];
}
the location for the xRange is where you want the plot to start, for example if you had 5 minutes(assuming 1 entry per second) of data loaded for the plot and you wanted to start at minute 3 your location would be 3*60. your length would always be 2*60 if you only want to show 2 minutes of data.
you probably want to change x.majorIntervalLength as well, that value controls how often a major tick is placed along the x axis. your major tick usually has a label associated with it, so you'd want to lower that value to something more appropriate for only 2 minutes of data