Enable x-Axis (Horizontal) scroll in coreplot - ios

I am using code from this link . And currently If I have 50 bar columns or 150 bar columns then the labels below is compressed and I would like to have horizontal scroll on x-Axis instead of having compressed x-Axis.
I have tried this:
plotSpace.xRange = CPTPlotRangeplotRangeWithLocation:CPTDecimalFromInt(-1)length:CPTDecimalFromInt(50)];
Attaching code from the file :
#import "GraphView.h"
#implementation GraphView
- (void)generateData
{
NSMutableDictionary *dataTemp = [[NSMutableDictionary alloc] init];
//Array containing all the dates that will be displayed on the X axis
dates = [NSArray arrayWithObjects:#"2012-05-01", #"2012-05-02", #"2012-05-03",
#"2012-05-04", #"2012-05-05", #"2012-05-06", #"2012-05-07", nil];
//Dictionary containing the name of the two sets and their associated color
//used for the demo
sets = [NSDictionary dictionaryWithObjectsAndKeys:[UIColor blueColor], #"Plot 1",
[UIColor redColor], #"Plot 2",
[UIColor greenColor], #"Plot 3", nil];
//Generate random data for each set of data that will be displayed for each day
//Numbers between 1 and 10
for (NSString *date in dates) {
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for (NSString *set in sets) {
NSNumber *num = [NSNumber numberWithInt:arc4random_uniform(10)+1];
[dict setObject:num forKey:set];
}
[dataTemp setObject:dict forKey:date];
}
data = [dataTemp copy];
[dataTemp release];
NSLog(#"%#", data);
}
- (void)generateLayout
{
//Create graph from theme
graph = [[CPTXYGraph alloc] initWithFrame:CGRectZero];
[graph applyTheme:[CPTTheme themeNamed:kCPTStocksTheme]];
self.hostedGraph = graph;
graph.plotAreaFrame.masksToBorder = NO;
graph.paddingLeft = 0.0f;
graph.paddingTop = 0.0f;
graph.paddingRight = 0.0f;
graph.paddingBottom = 0.0f;
CPTMutableLineStyle *borderLineStyle = [CPTMutableLineStyle lineStyle];
borderLineStyle.lineColor = [CPTColor whiteColor];
borderLineStyle.lineWidth = 2.0f;
graph.plotAreaFrame.borderLineStyle = borderLineStyle;
graph.plotAreaFrame.paddingTop = 10.0;
graph.plotAreaFrame.paddingRight = 10.0;
graph.plotAreaFrame.paddingBottom = 80.0;
graph.plotAreaFrame.paddingLeft = 70.0;
//Add plot space
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)graph.defaultPlotSpace;
plotSpace.delegate = self;
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(0)
length:CPTDecimalFromInt(10 * sets.count)];
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(-1)
length:CPTDecimalFromInt(8)];
//Grid line styles
CPTMutableLineStyle *majorGridLineStyle = [CPTMutableLineStyle lineStyle];
majorGridLineStyle.lineWidth = 0.75;
majorGridLineStyle.lineColor = [[CPTColor whiteColor] colorWithAlphaComponent:0.1];
CPTMutableLineStyle *minorGridLineStyle = [CPTMutableLineStyle lineStyle];
minorGridLineStyle.lineWidth = 0.25;
minorGridLineStyle.lineColor = [[CPTColor whiteColor] colorWithAlphaComponent:0.1];
//Axes
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)graph.axisSet;
//X axis
CPTXYAxis *x = axisSet.xAxis;
x.orthogonalCoordinateDecimal = CPTDecimalFromInt(0);
x.majorIntervalLength = CPTDecimalFromInt(1);
x.minorTicksPerInterval = 0;
x.labelingPolicy = CPTAxisLabelingPolicyNone;
x.majorGridLineStyle = majorGridLineStyle;
x.axisConstraints = [CPTConstraints constraintWithLowerOffset:0.0];
//X labels
int labelLocations = 0;
NSMutableArray *customXLabels = [NSMutableArray array];
for (NSString *day in dates) {
CPTAxisLabel *newLabel = [[CPTAxisLabel alloc] initWithText:day textStyle:x.labelTextStyle];
newLabel.tickLocation = [[NSNumber numberWithInt:labelLocations] decimalValue];
newLabel.offset = x.labelOffset + x.majorTickLength;
newLabel.rotation = M_PI / 4;
[customXLabels addObject:newLabel];
labelLocations++;
[newLabel release];
}
x.axisLabels = [NSSet setWithArray:customXLabels];
//Y axis
CPTXYAxis *y = axisSet.yAxis;
y.title = #"Value";
y.titleOffset = 50.0f;
y.labelingPolicy = CPTAxisLabelingPolicyAutomatic;
y.majorGridLineStyle = majorGridLineStyle;
y.minorGridLineStyle = minorGridLineStyle;
y.axisConstraints = [CPTConstraints constraintWithLowerOffset:0.0];
//Create a bar line style
CPTMutableLineStyle *barLineStyle = [[[CPTMutableLineStyle alloc] init] autorelease];
barLineStyle.lineWidth = 1.0;
barLineStyle.lineColor = [CPTColor whiteColor];
CPTMutableTextStyle *whiteTextStyle = [CPTMutableTextStyle textStyle];
whiteTextStyle.color = [CPTColor whiteColor];
//Plot
BOOL firstPlot = YES;
for (NSString *set in [[sets allKeys] sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)]) {
CPTBarPlot *plot = [CPTBarPlot tubularBarPlotWithColor:[CPTColor blueColor] horizontalBars:NO];
plot.lineStyle = barLineStyle;
CGColorRef color = ((UIColor *)[sets objectForKey:set]).CGColor;
plot.fill = [CPTFill fillWithColor:[CPTColor colorWithCGColor:color]];
if (firstPlot) {
plot.barBasesVary = NO;
firstPlot = NO;
} else {
plot.barBasesVary = YES;
}
plot.barWidth = CPTDecimalFromFloat(0.8f);
plot.barsAreHorizontal = NO;
plot.dataSource = self;
plot.identifier = set;
[graph addPlot:plot toPlotSpace:plotSpace];
}
//Add legend
CPTLegend *theLegend = [CPTLegend legendWithGraph:graph];
theLegend.numberOfRows = sets.count;
theLegend.fill = [CPTFill fillWithColor:[CPTColor colorWithGenericGray:0.15]];
theLegend.borderLineStyle = barLineStyle;
theLegend.cornerRadius = 10.0;
theLegend.swatchSize = CGSizeMake(15.0, 15.0);
whiteTextStyle.fontSize = 13.0;
theLegend.textStyle = whiteTextStyle;
theLegend.rowMargin = 5.0;
theLegend.paddingLeft = 10.0;
theLegend.paddingTop = 10.0;
theLegend.paddingRight = 10.0;
theLegend.paddingBottom = 10.0;
graph.legend = theLegend;
graph.legendAnchor = CPTRectAnchorTopLeft;
graph.legendDisplacement = CGPointMake(80.0, -10.0);
}
- (void)createGraph
{
//Generate data
[self generateData];
//Generate layout
[self generateLayout];
}
- (void)dealloc
{
[data release];
[super dealloc];
}
#pragma mark - CPTPlotDataSource methods
- (NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{
return dates.count;
}
- (double)doubleForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
double num = NAN;
//X Value
if (fieldEnum == 0) {
num = index;
}
else {
double offset = 0;
if (((CPTBarPlot *)plot).barBasesVary) {
for (NSString *set in [[sets allKeys] sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)]) {
if ([plot.identifier isEqual:set]) {
break;
}
offset += [[[data objectForKey:[dates objectAtIndex:index]] objectForKey:set] doubleValue];
}
}
//Y Value
if (fieldEnum == 1) {
num = [[[data objectForKey:[dates objectAtIndex:index]] objectForKey:plot.identifier] doubleValue] + offset;
}
//Offset for stacked bar
else {
num = offset;
}
}
//NSLog(#"%# - %d - %d - %f", plot.identifier, index, fieldEnum, num);
return num;
}
#pragma mark - CPTBarPlotDelegate methods
-(void)barPlot:(CPTBarPlot *)plot barWasSelectedAtRecordIndex:(NSUInteger)index {
NSLog(#"barWasSelectedAtRecordIndex %d", index);
}
#end

to get scrolling you need to set the globalXRange on the plotspace to be the entire range, and set the xRange will be the visible area.
for example a globalXRange of 0-150, and a xRange of 0-50. then you could scroll up to view the 51-150 range.

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];

Core-Plot multiple y axis alignment issues - possibly related to scaling

My Issues is as follows:
I'm trying to graph two data sets (One is in Feet and one is in degrees) in such a way that they can be compared (they do share a common x-axis value).
As you can see my data seems to be interlaced correctly but I'm having trouble getting the yAxises to behave as I'd like. I would like the X-Axis Max/Min to actually line up with both Y-Axises. My code is as follows:
- (void)initPlot {
[self loadCoreData];
[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:kCPTDarkGradientTheme]];
self.hostView.hostedGraph = graph;
// 2 - Set graph title
NSString *title = [NSString stringWithFormat:#"Altitude Plot [%# to %#]", self.flightRecording.originAirport, self.flightRecording.destinationAirport];
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, -20.0f);
// 4 - Set padding for plot area
float padding = 10.0f;
[graph.plotAreaFrame setPaddingLeft:padding];
[graph.plotAreaFrame setPaddingBottom:50.0f];
[graph.plotAreaFrame setPaddingRight:padding];
[graph.plotAreaFrame setPaddingTop:padding];
// 5 - Enable user interactions for plot space
altSpace= (CPTXYPlotSpace *) graph.defaultPlotSpace;
altSpace.allowsUserInteraction = NO;
rollSpace = [[CPTXYPlotSpace alloc] init];
rollSpace.allowsUserInteraction = NO;
[self.hostView.hostedGraph addPlotSpace:rollSpace];
//
// pitchSpace = [[CPTXYPlotSpace alloc] init];
// pitchSpace.allowsUserInteraction = NO;
// [self.hostView.hostedGraph addPlotSpace:pitchSpace];
//
//
// slipSpace = [[CPTXYPlotSpace alloc] init];
// slipSpace.allowsUserInteraction = NO;
// [self.hostView.hostedGraph addPlotSpace:slipSpace];
//
//
// gSpace = [[CPTXYPlotSpace alloc] init];
// gSpace.allowsUserInteraction = NO;
// [self.hostView.hostedGraph addPlotSpace:gSpace];
}
- (void)configurePlots {
// 1 - Get graph and plot space
CPTGraph *graph = self.hostView.hostedGraph;
// 2 - Create the three plots
// Custom AHRS Plot
CPTScatterPlot *ahrsAltPlot = [[CPTScatterPlot alloc] init];
ahrsAltPlot.dataSource = self;
ahrsAltPlot.identifier = #"AHRSALT";
CPTColor *ahrsAltColor = [CPTColor yellowColor];
[graph addPlot:ahrsAltPlot toPlotSpace:altSpace];
CPTScatterPlot *rollPlot = [[CPTScatterPlot alloc] init];
rollPlot.dataSource = self;
rollPlot.identifier = #"ROLL";
CPTColor *rollColor = [CPTColor greenColor];
[graph addPlot:rollPlot toPlotSpace:rollSpace];
// 3 - Set up plot space
CPTMutablePlotRange *xRange = [altSpace.xRange mutableCopy];
xRange=[CPTMutablePlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0f ) length:CPTDecimalFromFloat(maxEpoch + 300.0f )];
// [xRange expandRangeByFactor:CPTDecimalFromCGFloat(1.1f)];
altSpace.xRange = xRange;
CPTMutablePlotRange *yRange = [altSpace.yRange mutableCopy];
yRange = [CPTMutablePlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0f) length:CPTDecimalFromFloat(maxAlt)];
[yRange expandRangeByFactor:CPTDecimalFromCGFloat(1.2f)];
altSpace.yRange = yRange;
rollSpace.xRange = xRange;
CPTMutablePlotRange *yRangeRoll =[CPTMutablePlotRange plotRangeWithLocation:CPTDecimalFromFloat(0 ) length:CPTDecimalFromFloat(40 )];
[yRangeRoll expandRangeByFactor:CPTDecimalFromCGFloat(1.2f)];
rollSpace.yRange = yRangeRoll;
[altSpace scaleToFitPlots:[NSArray arrayWithObjects:ahrsAltPlot, nil] ];
[rollSpace scaleToFitPlots:[NSArray arrayWithObjects:rollPlot, nil] ];
[rollSpace setYRange:yRangeRoll];
// 4 - Create styles and symbols
// AHRS Style
CPTMutableLineStyle *ahrsLineStyle = [ahrsAltPlot.dataLineStyle mutableCopy];
ahrsLineStyle.lineWidth = 2.5;
ahrsLineStyle.lineColor = [CPTColor blueColor];
ahrsAltPlot.dataLineStyle = ahrsLineStyle;
}
- (void)configureAxes {
// 1 - Create styles
CPTMutableTextStyle *axisTitleStyle = [CPTMutableTextStyle textStyle];
axisTitleStyle.color = [CPTColor whiteColor];
axisTitleStyle.fontName = #"Helvetica-Bold";
axisTitleStyle.fontSize = 12.0f;
CPTMutableLineStyle *axisLineStyle = [CPTMutableLineStyle lineStyle];
axisLineStyle.lineWidth = 2.0f;
axisLineStyle.lineColor = [CPTColor whiteColor];
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 *) self.hostView.hostedGraph.axisSet;
// 3 - Configure x-axis
CPTAxis *x = axisSet.xAxis;
x.title = #"Flight Time";
x.titleTextStyle = axisTitleStyle;
x.titleOffset = 15.0f;
x.axisLineStyle = axisLineStyle;
x.labelingPolicy = CPTAxisLabelingPolicyNone;
x.labelTextStyle = axisTextStyle;
x.majorTickLineStyle = axisLineStyle;
x.majorTickLength = 4.0f;
x.tickDirection = CPTSignNegative;
NSMutableSet *xLabels = [NSMutableSet new];
NSMutableSet *xLocations = [NSMutableSet new];
NSInteger i = 0;
for (i; i < maxEpoch; i += 600) {
int hour = i / (68 * 60);
int min = i / 60;
CPTAxisLabel *label = [[CPTAxisLabel alloc] initWithText:[NSString stringWithFormat:#"%02d:%02d", hour, min] textStyle:x.labelTextStyle];
CGFloat location = i++;
label.tickLocation = CPTDecimalFromCGFloat(location);
label.offset = x.majorTickLength;
if (label) {
[xLabels addObject:label];
[xLocations addObject:[NSNumber numberWithInteger:i]];
}
}
x.axisLabels = xLabels;
x.majorTickLocations = xLocations;
// 4 - Configure y-axis
CPTAxis *y = axisSet.yAxis;
y.title = #"Altitude in Feet";
y.titleTextStyle = axisTitleStyle;
y.titleOffset = 20.0f;
y.axisLineStyle = axisLineStyle;
y.majorGridLineStyle = gridLineStyle;
y.labelingPolicy = CPTAxisLabelingPolicyNone;
y.labelTextStyle = axisTextStyle;
y.labelOffset = 21.0f;
y.majorTickLineStyle = axisLineStyle;
y.majorTickLength = 20.0f;
y.minorTickLength = 10.0f;
y.tickDirection = CPTSignNegative;
// Axis #2
CPTXYAxis *yRoll = [[CPTXYAxis alloc] init];
yRoll.title = #"Degrees";
// Styling
yRoll.titleTextStyle = axisTitleStyle;
yRoll.labelTextStyle = axisTextStyle;
yRoll.axisLineStyle = axisLineStyle;
yRoll.majorTickLineStyle = axisLineStyle;
yRoll.plotSpace = rollSpace;
yRoll.delegate = self;
yRoll.labelingPolicy = CPTAxisLabelingPolicyNone;
yRoll.coordinate = CPTCoordinateY;
yRoll.tickDirection = CPTSignNone;
yRoll.separateLayers = NO;
yRoll.tickDirection = CPTSignNegative;
yRoll.labelOffset = 21.0f;
yRoll.axisConstraints = [CPTConstraints constraintWithLowerOffset:40.0];
yRoll.orthogonalCoordinateDecimal = CPTDecimalFromFloat(0.0f);
NSMutableSet *rollLabels = [NSMutableSet new];
NSMutableSet *rollLocations = [NSMutableSet new];
for (int i =0; i <= 40; i+= 5) {
CPTAxisLabel *label = [[CPTAxisLabel alloc] initWithText:[NSString stringWithFormat:#"%02d˚", (i - 20)] textStyle:yRoll.labelTextStyle];
CGFloat location = i;
label.tickLocation = CPTDecimalFromCGFloat(location);
label.offset = -16.0f;
if (label) {
[rollLabels addObject:label];
[rollLocations addObject:[NSNumber numberWithInteger:i]];
}
}
yRoll.axisLabels = rollLabels;
yRoll.majorTickLocations = rollLocations;
NSInteger majorIncrement = 500;
NSInteger minorIncrement = 100;
CGFloat yMax = maxAlt; // should determine dynamically based on max price
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:#"%i ft", 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)]];
}
}
// Position the y2 axis
// y2.axisConstraints = [CPTConstraints constraintWithUpperOffset:40.0];
axisSet.yAxis.axisConstraints = [CPTConstraints constraintWithUpperOffset:40.0];
y.axisLabels = yLabels;
y.majorTickLocations = yMajorLocations;
y.minorTickLocations = yMinorLocations;
self.hostView.hostedGraph.axisSet.axes = [NSArray arrayWithObjects:x,y,yRoll,nil];
// Position floating YAxis
// y2.axisConstraints = [CPTConstraints constraintWithUpperOffset:150.0];
}
EDIT::
I tried adding the following lines and they did nothing either
y.orthogonalCoordinateDecimal = CPTDecimalFromFloat(0.0f);
x.orthogonalCoordinateDecimal = CPTDecimalFromFloat(0.0f);
I seem to be making progress actually: It appears that if I remove
yAxis2.axisConstraints = [CPTConstraints constraintWithLowerOffset:40.0];
Then my axis actually seems to pin to the x-axis (although its off the screen) now but its a start.
Problem Solved:
I had some conflicting directives going on.
In order to achieve what I needed I had to use the two calls:
yAxis2.orthogonalCoordinateDecimal = CPTDecimalFromFloat(0.0f);
y.orthogonalCoordinateDecimal = CPTDecimalFromFloat(maxEpoch); // maximum X value
x.orthogonalCoordinateDecimal = CPTDecimalFromFloat(0.0f);
Then in order to make sure everything could be seen correctly I had to play with the padding values:
float padding = 50.0f;
[graph.plotAreaFrame setPaddingLeft:padding];
[graph.plotAreaFrame setPaddingBottom:50.0f];
[graph.plotAreaFrame setPaddingRight:padding];
[graph.plotAreaFrame setPaddingTop:padding];
And I had to remove all the constraints that were messing with things:
// yAxis2.axisConstraints = [CPTConstraints constraintWithLowerOffset:40.0];
// y.axisConstraints = [CPTConstraints constraintWithUpperOffset:150.0];

Core Plot unable to draw a line

Based on the example RealTime presented in the library Core Plot, I tried to reimplement it on my project.
I am able to update y axis, add a symbol, draw label, etc. But I'm totally unable to draw the line.
CPTMutableLineStyle object seems to be correctly instantied and correctly setted to the CPTGraph object but is not rendered in the graph
Here is how I add line style to my graph
CPTMutableLineStyle *lineStyle = [CPTMutableLineStyle lineStyle]; // [dataSourceLinePlot.dataLineStyle mutableCopy];
lineStyle.lineWidth = 3.0;
lineStyle.lineColor = [CPTColor greenColor];
dataSourceLinePlot.dataLineStyle = lineStyle;
And here is the full class code
#import "TUTSimpleScatterPlot.h"
const double kFrameRate = 5.0; // frames per second
const double kAlpha = 0.15; // smoothing constant
const NSUInteger kMaxDataPoints = 21;
NSString *kPlotIdentifier = #"Data Source Plot";
#implementation TUTSimpleScatterPlot
// Initialise the scatter plot in the provided hosting view with the provided data.
// The data array should contain NSValue objects each representing a CGPoint.
-(id)initWithHostingView:(CPTGraphHostingView *)hostingView andData:(NSMutableArray *)data
{
self = [super init];
if ( self != nil ) {
self.hostingView = hostingView;
self.graphData = data;
self.graph = nil;
}
return self;
}
-(void)initialisePlot
{
self.graphData = [NSMutableArray array];
CGRect bounds = self.hostingView.bounds;
CPTGraph *graph = [[CPTXYGraph alloc] initWithFrame:bounds] ;
[self.hostingView setHostedGraph:graph];
graph.title = #"Measure";
CPTMutableTextStyle *textStyle = [CPTMutableTextStyle textStyle];
textStyle.color = [CPTColor grayColor];
textStyle.fontName = #"Helvetica-Bold";
textStyle.fontSize = round(bounds.size.height / (CGFloat)20.0);
graph.titleTextStyle = textStyle;
graph.titleDisplacement = CGPointMake( 0.0f, round(bounds.size.height / (CGFloat)18.0) ); // Ensure that title displacement falls on an integral pixel
graph.titlePlotAreaFrameAnchor = CPTRectAnchorTop;
CGFloat boundsPadding = round(bounds.size.width / (CGFloat)20.0); // Ensure that padding falls on an integral pixel
graph.paddingLeft = boundsPadding;
if ( graph.titleDisplacement.y > 0.0 ) {
graph.paddingTop = graph.titleDisplacement.y * 2;
}
else {
graph.paddingTop = boundsPadding;
}
graph.paddingRight = boundsPadding;
graph.paddingBottom = boundsPadding;
graph.plotAreaFrame.paddingTop = 15.0;
graph.plotAreaFrame.paddingRight = 15.0;
graph.plotAreaFrame.paddingBottom = 55.0;
graph.plotAreaFrame.paddingLeft = 55.0;
// Grid line styles
CPTMutableLineStyle *majorGridLineStyle = [CPTMutableLineStyle lineStyle];
majorGridLineStyle.lineWidth = 0.75;
majorGridLineStyle.lineColor = [[CPTColor colorWithGenericGray:0.2] colorWithAlphaComponent:0.75];
CPTMutableLineStyle *minorGridLineStyle = [CPTMutableLineStyle lineStyle];
minorGridLineStyle.lineWidth = 0.25;
minorGridLineStyle.lineColor = [[CPTColor whiteColor] colorWithAlphaComponent:0.1];
// Axes
// X axis
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)graph.axisSet;
CPTXYAxis *x = axisSet.xAxis;
x.labelingPolicy = CPTAxisLabelingPolicyAutomatic;
x.orthogonalCoordinateDecimal = CPTDecimalFromUnsignedInteger(0);
x.majorGridLineStyle = majorGridLineStyle;
x.minorGridLineStyle = minorGridLineStyle;
x.minorTicksPerInterval = 9;
x.title = #"X Axis";
x.titleOffset = 35.0;
NSNumberFormatter *labelFormatter = [[NSNumberFormatter alloc] init];
labelFormatter.numberStyle = NSNumberFormatterNoStyle;
x.labelFormatter = labelFormatter;
// Y axis
CPTXYAxis *y = axisSet.yAxis;
y.labelingPolicy = CPTAxisLabelingPolicyAutomatic;
y.orthogonalCoordinateDecimal = CPTDecimalFromUnsignedInteger(0);
y.majorGridLineStyle = majorGridLineStyle;
y.minorGridLineStyle = minorGridLineStyle;
y.minorTicksPerInterval = 3;
y.labelOffset = 5.0;
y.title = #"Y Axis";
y.titleOffset = 30.0;
y.axisConstraints = [CPTConstraints constraintWithLowerOffset:0.0];
// Rotate the labels by 45 degrees, just to show it can be done.
x.labelRotation = M_PI * 0.25;
// Create the plot
CPTScatterPlot *dataSourceLinePlot = [[CPTScatterPlot alloc] init];
dataSourceLinePlot.identifier = kPlotIdentifier;
dataSourceLinePlot.cachePrecision = CPTPlotCachePrecisionDouble;
// dataSourceLinePlot.interpolation = CPTScatterPlotInterpolationCurved;
CPTMutableLineStyle *lineStyle = [CPTMutableLineStyle lineStyle]; // [dataSourceLinePlot.dataLineStyle mutableCopy];
lineStyle.lineWidth = 3.0;
lineStyle.lineColor = [CPTColor greenColor];
dataSourceLinePlot.dataLineStyle = lineStyle;
CPTMutableLineStyle *symbolLineStyle = [CPTMutableLineStyle lineStyle];
symbolLineStyle.lineColor = [[CPTColor blackColor] colorWithAlphaComponent:0.5];
CPTPlotSymbol *plotSymbol = [CPTPlotSymbol ellipsePlotSymbol];
plotSymbol.fill = [CPTFill fillWithColor:[[CPTColor blueColor] colorWithAlphaComponent:0.5]];
plotSymbol.lineStyle = symbolLineStyle;
plotSymbol.size = CGSizeMake(10.0, 10.0);
dataSourceLinePlot.plotSymbol = plotSymbol;
dataSourceLinePlot.dataSource = self;
[graph addPlot:dataSourceLinePlot];
// Plot space
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)graph.defaultPlotSpace;
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromUnsignedInteger(0) length:CPTDecimalFromUnsignedInteger(kMaxDataPoints - 1)];
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromUnsignedInteger(0) length:CPTDecimalFromUnsignedInteger(1)];
self.graph = graph;
self.dataTimer = [NSTimer timerWithTimeInterval:1.0 / kFrameRate
target:self
selector:#selector(newData:)
userInfo:nil
repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:self.dataTimer forMode:NSDefaultRunLoopMode];
}
#pragma mark -
#pragma mark Timer callback
-(void)newData:(NSTimer *)theTimer
{
CPTGraph *theGraph = self.graph;
CPTPlot *thePlot = [theGraph plotWithIdentifier:kPlotIdentifier];
if ( thePlot ) {
// if ( self.graphData.count >= kMaxDataPoints - 5 ) {
// [self.graphData removeObjectAtIndex:0];
// [thePlot deleteDataInIndexRange:NSMakeRange(0, 1)];
// }
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)theGraph.defaultPlotSpace;
NSUInteger location = (_currentIndex >= kMaxDataPoints ? _currentIndex - kMaxDataPoints + 5 : 0);
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromUnsignedInteger(location)
length:CPTDecimalFromUnsignedInteger(kMaxDataPoints - 1)];
_currentIndex++;
NSNumber * num;
if (_currentIndex == 1) {
num = [NSNumber numberWithDouble: 5 + (arc4random() % 15) ];
} else {
NSLog(#"lastVal: %d", [[self.graphData lastObject] intValue]);
float low_bound = (1 - kAlpha) * [[self.graphData lastObject] floatValue];
float high_bound = (1.01 + kAlpha) * [[self.graphData lastObject] floatValue];
float random = (((float)arc4random()/0x100000000)*(high_bound-low_bound)+low_bound);
NSLog(#"random: %f", random);
num = [NSNumber numberWithDouble:random];
}
// Update y range if necessary
if (_currentIndex < kMaxDataPoints) {
int maxValue = -1;
for (int i = self.graphData.count -1 ; (i >= 0); i--) {
if ([[self.graphData objectAtIndex:i] intValue] > maxValue) {
maxValue = [[self.graphData objectAtIndex:i] intValue];
}
}
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromUnsignedInteger(0) length:CPTDecimalFromUnsignedInteger(maxValue + 1)];
} else if (_currentIndex >= kMaxDataPoints) {
int maxValue = -1;
for (int i = self.graphData.count -1 ; (i >= self.graphData.count - kMaxDataPoints + 2); i--) {
if ([[self.graphData objectAtIndex:i] intValue] > maxValue) {
maxValue = [[self.graphData objectAtIndex:i] intValue];
}
}
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromUnsignedInteger(0) length:CPTDecimalFromUnsignedInteger(maxValue + 1)];
}
[self.graphData addObject:num];
[thePlot insertDataAtIndex:self.graphData.count - 1 numberOfRecords:1];
}
}
#pragma mark -
#pragma mark Plot Data Source Methods
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{
return [self.graphData count];
}
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
NSNumber *num = nil;
switch ( fieldEnum ) {
case CPTScatterPlotFieldX:
num = [NSNumber numberWithUnsignedInteger:index + _currentIndex - self.graphData.count];
break;
case CPTScatterPlotFieldY:
num = [self.graphData objectAtIndex:index];
break;
default:
break;
}
return num;
}
#end
Any ideas ? Tips ? Hack ?
UPDATE 1
In my project I used the 1.2 version of the library. I tried to regress to 1.0 version and lines are now displayed. Any ideas on how to convert my project to work with the last version ?
UPDATE 2*
Changing the Podfile from pod 'CorePlot' to pod 'CorePlot', '~> 1.2' seems to be different. My line is now correctly drawn...
Seems there is difference by using cocoapods by this way
pod 'CorePlot'
or by this way
pod 'CorePlot', '~> 1.2'
Then reinstalling the libaries by executing pod install
Now the project is able to draw line

x-axis labels in coreplot not displayed

I have attached the entire code which I am using but the x-axis label is not being generated .I have no clue where it is going wrong .I am a noob in core plot .PLease Help me out .Thanks in Advance and Happy New Year.
#import "BarPlotViewController.h"
#interface BarPlotViewController ()
#end
#implementation BarPlotViewController
#define BAR_POSITION #"POSITION"
#define BAR_HEIGHT #"HEIGHT"
#define COLOR #"COLOR"
#define CATEGORY #"CATEGORY"
#define AXIS_START 0
#define AXIS_END 50
//
#synthesize data;
#synthesize graph;
#synthesize hostingView;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.data = [NSMutableArray array];
int bar_heights[] = {20,30,10,40};
UIColor *colors[] = {
[UIColor redColor],
[UIColor blueColor],
[UIColor orangeColor],
[UIColor purpleColor]};
NSString *categories[] = {#"Plain Milk", #"Milk + Caramel", #"White", #"Dark"};
for (int i = 0; i < 4 ; i++){
double position = i*10; //Bars will be 10 pts away from each other
double height = bar_heights[i];
NSDictionary *bar = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithDouble:position],BAR_POSITION,
[NSNumber numberWithDouble:height],BAR_HEIGHT,
colors[i],COLOR,
categories[i],CATEGORY,
nil];
[self.data addObject:bar];
}
[self generateBarPlot];
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)generateBarPlot
{
//Create host view
self.hostingView = [[CPTGraphHostingView alloc]
initWithFrame:[[UIScreen mainScreen]bounds]];
[self.view addSubview:self.hostingView];
//Create graph and set it as host view's graph
self.graph = [[CPTXYGraph alloc] initWithFrame:self.hostingView.bounds];
[self.hostingView setHostedGraph:self.graph];
//set graph padding and theme
self.graph.plotAreaFrame.paddingTop = 20.0f;
self.graph.plotAreaFrame.paddingRight = 20.0f;
self.graph.plotAreaFrame.paddingBottom = 70.0f;
self.graph.plotAreaFrame.paddingLeft = 70.0f;
[self.graph applyTheme:[CPTTheme themeNamed:kCPTDarkGradientTheme]];
//set axes ranges
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;
// plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(AXIS_START) length:CPTDecimalFromFloat((AXIS_END - AXIS_START)+5)];
// plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(-1) length:CPTDecimalFromInt(8)];
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)self.graph.axisSet;
//X labels
int labelLocations = 0;
NSMutableArray *customXLabels = [NSMutableArray array];
NSArray *dates = [NSArray arrayWithObjects:#"2012-05-01", #"2012-05-02", #"2012-05-03",
#"2012-05-04", #"2012-05-05", #"2012-05-06", #"2012-05-07", nil];
for (NSString *day in dates) {
CPTAxisLabel *newLabel = [[CPTAxisLabel alloc] initWithText:day textStyle:axisSet.xAxis.labelTextStyle];
newLabel.tickLocation = [[NSNumber numberWithInt:labelLocations] decimalValue];
newLabel.offset = axisSet.xAxis.labelOffset + axisSet.xAxis.majorTickLength;
// newLabel.rotation = M_PI / 4;
[customXLabels addObject:newLabel];
labelLocations++;
}
axisSet.xAxis.axisLabels = [NSSet setWithArray:customXLabels];
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:
CPTDecimalFromFloat(AXIS_START)
length:CPTDecimalFromFloat((AXIS_END - AXIS_START)+5)];
//set axes' title, labels and their text styles
CPTMutableTextStyle *textStyle = [CPTMutableTextStyle textStyle];
textStyle.fontName = #"Helvetica";
textStyle.fontSize = 14;
textStyle.color = [CPTColor whiteColor];
axisSet.xAxis.title = #"Years";
axisSet.yAxis.title = #"Expenses";
axisSet.xAxis.titleTextStyle = textStyle;
axisSet.yAxis.titleTextStyle = textStyle;
axisSet.xAxis.titleOffset = 30.0f;
axisSet.yAxis.titleOffset = 40.0f;
axisSet.xAxis.labelTextStyle = textStyle;
axisSet.xAxis.labelOffset = 3.0f;
axisSet.yAxis.labelTextStyle = textStyle;
axisSet.yAxis.labelOffset = 3.0f;
//set axes' line styles and interval ticks
CPTMutableLineStyle *lineStyle = [CPTMutableLineStyle lineStyle];
lineStyle.lineColor = [CPTColor whiteColor];
lineStyle.lineWidth = 3.0f;
axisSet.xAxis.axisLineStyle = lineStyle;
axisSet.yAxis.axisLineStyle = lineStyle;
axisSet.xAxis.majorTickLineStyle = lineStyle;
axisSet.yAxis.majorTickLineStyle = lineStyle;
axisSet.xAxis.majorIntervalLength = CPTDecimalFromFloat(5.0f);
axisSet.yAxis.majorIntervalLength = CPTDecimalFromFloat(5.0f);
axisSet.xAxis.majorTickLength = 7.0f;
axisSet.yAxis.majorTickLength = 7.0f;
axisSet.xAxis.minorTickLineStyle = lineStyle;
axisSet.yAxis.minorTickLineStyle = lineStyle;
axisSet.xAxis.minorTicksPerInterval = 1;
axisSet.yAxis.minorTicksPerInterval = 1;
axisSet.xAxis.minorTickLength = 5.0f;
axisSet.yAxis.minorTickLength = 5.0f;
// Create bar plot and add it to the graph
CPTBarPlot *plot = [[CPTBarPlot alloc] init] ;
plot.dataSource = self;
plot.delegate = self;
plot.barWidth = [[NSDecimalNumber decimalNumberWithString:#"5.0"]
decimalValue];
plot.barOffset = [[NSDecimalNumber decimalNumberWithString:#"10.0"]
decimalValue];
plot.barCornerRadius = 5.0;
// Remove bar outlines
CPTMutableLineStyle *borderLineStyle = [CPTMutableLineStyle lineStyle];
borderLineStyle.lineColor = [CPTColor clearColor];
plot.lineStyle = borderLineStyle;
// Identifiers are handy if you want multiple plots in one graph
plot.identifier = #"chocoplot";
[self.graph addPlot:plot];
}
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{
if ( [plot.identifier isEqual:#"chocoplot"] )
return [self.data count];
return 0;
}
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
if ( [plot.identifier isEqual:#"chocoplot"] )
{
NSDictionary *bar = [self.data objectAtIndex:index];
if(fieldEnum == CPTBarPlotFieldBarLocation)
return [bar valueForKey:BAR_POSITION];
else if(fieldEnum ==CPTBarPlotFieldBarTip)
return [bar valueForKey:BAR_HEIGHT];
}
return [NSNumber numberWithFloat:0];
}
-(CPTLayer *)dataLabelForPlot:(CPTPlot *)plot recordIndex:(NSUInteger)index
{
if ( [plot.identifier isEqual: #"chocoplot"] )
{
CPTMutableTextStyle *textStyle = [CPTMutableTextStyle textStyle];
textStyle.fontName = #"Helvetica";
textStyle.fontSize = 14;
textStyle.color = [CPTColor whiteColor];
NSDictionary *bar = [self.data objectAtIndex:index];
// CPTTextLayer *label = [[CPTTextLayer alloc] initWithText:[NSString stringWithFormat:#"%#", [bar valueForKey:#"CATEGORY"]]];
CPTTextLayer *label = [[CPTTextLayer alloc] initWithText:[NSString stringWithFormat:#"%#", [bar valueForKey:#"HEIGHT"]]];
label.textStyle =textStyle;
return label;
}
CPTTextLayer *defaultLabel = [[CPTTextLayer alloc] initWithText:#"Label"];
return defaultLabel;
}
-(void)barPlot:(CPTBarPlot *)plot barWasSelectedAtRecordIndex:(NSUInteger)index
{
NSLog(#"barWasSelectedAtRecordIndex %d", index);
}
-(CPTFill *)barFillForBarPlot:(CPTBarPlot *)barPlot
recordIndex:(NSUInteger)index
{
if ( [barPlot.identifier isEqual:#"chocoplot"] )
{
NSDictionary *bar = [self.data objectAtIndex:index];
CPTGradient *gradient = [CPTGradient gradientWithBeginningColor:[CPTColor whiteColor]
endingColor:[bar valueForKey:#"COLOR"]
beginningPosition:0.0 endingPosition:0.3 ];
[gradient setGradientType:CPTGradientTypeAxial];
[gradient setAngle:320.0];
CPTFill *fill = [CPTFill fillWithGradient:gradient];
return fill;
}
return [CPTFill fillWithColor:[CPTColor colorWithComponentRed:1.0 green:1.0 blue:1.0 alpha:1.0]];
}
#end
Main Code for plotting x-axis labels :
This is the code for x-axis labels:
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)self.graph.axisSet;
//X labels
int labelLocations = 0;
NSMutableArray *customXLabels = [NSMutableArray array];
NSArray *dates = [NSArray arrayWithObjects:#"2012-05-01", #"2012-05-02", #"2012-05-03",
#"2012-05-04", #"2012-05-05", #"2012-05-06", #"2012-05-07", nil];
for (NSString *day in dates) {
CPTAxisLabel *newLabel = [[CPTAxisLabel alloc] initWithText:day textStyle:axisSet.xAxis.labelTextStyle];
newLabel.tickLocation = [[NSNumber numberWithInt:labelLocations] decimalValue];
newLabel.offset = axisSet.xAxis.labelOffset + axisSet.xAxis.majorTickLength;
// newLabel.rotation = M_PI / 4;
[customXLabels addObject:newLabel];
labelLocations++;
}
axisSet.xAxis.axisLabels = [NSSet setWithArray:customXLabels];
Have you tried this? You have to handle the padding correctly.
graph.plotAreaFrame.paddingBottom=40;

Multiple Bar plot legend

I have a chart with 2 bar plots (Example: A and B).
For each hour i have 2 bar plots.
When i set the legend, i get swatch and text for every hour and bar
plot.
Example: In my chart have 4 hours then my legend will be like this
A A A A
B B B B
And i only want
A B
Because on every hour, the bars means the same.
How can i do this ??
I have tried everything to make this happen but no success till now....
Bellow is my
// CPTLegend *theLegend = [CPTLegend legendWithGraph:barChart];
CPTLegend *theLegend = [CPTLegend legendWithPlots:[NSArray arrayWithObjects:[barChart plotAtIndex:0],[barChart plotAtIndex:1], nil]];
theLegend.numberOfRows = 1;
theLegend.numberOfColumns = 2;//[horas count] +1 / 2;
//theLegend.fill = [CPTFill fillWithColor:[CPTColor colorWithGenericGray:0.15]];
//theLegend.borderLineStyle = barLineStyle;
theLegend.cornerRadius = 10.0;
theLegend.swatchSize = CGSizeMake(15, 15);
//whiteTextStyle.fontSize = 16.0;
//theLegend.textStyle = whiteTextStyle;
theLegend.rowMargin = 10.0;
theLegend.paddingLeft = 12.0;
theLegend.paddingTop = 12.0;
theLegend.paddingRight = 12.0;
theLegend.paddingBottom = 12.0;
//theLegend.equalColumns = YES;
//theLegend.equalRows = YES;
theLegend.delegate = self;
barChart.legend = theLegend;
-(NSString *)legendTitleForBarPlot:(CPTBarPlot *)barPlot recordIndex:(NSUInteger)index{
if ( [barPlot.identifier isEqual:#"Embarque"] ) {
if (index == 0)
{
return #"Embarque";
}else {
return #"";
}
}else {
if (index == 0)
{
return #"Desembarque";
}else {
return #"";
}
}
}
-(BOOL)legend:(CPTLegend *)legend shouldDrawSwatchAtIndex:(NSUInteger)index forPlot:(CPTPlot *)plot inRect:(CGRect)rect inContext:(CGContextRef)context{
if (index == 0) {
return YES;
}else{
return NO;
}
}
Don't implement the -legendTitleForBarPlot:recordIndex: method unless you want a separate label for each bar. Use the title property to set a single legend title for the plot.
The -legend:shouldDrawSwatchAtIndex:forPlot:inRect:inContext: method is only needed if you want to change the default swatch drawing in some way.
-(void) exibirGraficoEmbarqueDescarga {
// Create barChart from theme
barChart = [[CPTXYGraph alloc] initWithFrame:CGRectZero];
CPTTheme *theme = [CPTTheme themeNamed:kCPTPlainWhiteTheme];
[barChart applyTheme:theme];
//CPTGraphHostingView *hostingView = (CPTGraphHostingView *)self.view;
//hostingView.hostedGraph = barChart;
barChart.delegate = self;
if (chartView == nil)
{
chartView = [[CPTGraphHostingView alloc] initWithFrame:CGRectMake(-15, 30, 350, 320)];
// chartView = [[CPTGraphHostingView alloc] initWithFrame:CGRectMake(0, 35, 510, 280)];
[self.view addSubview:chartView];
}
chartView.hostedGraph = barChart;
// Border
barChart.plotAreaFrame.borderLineStyle = nil;
barChart.plotAreaFrame.cornerRadius = 0.0f;
// Paddings
barChart.paddingLeft = 0.0f;
barChart.paddingRight = 0.0f;
barChart.paddingTop = 0.0f;
barChart.paddingBottom = 0.0f;
barChart.plotAreaFrame.paddingLeft = 70.0;
barChart.plotAreaFrame.paddingTop = 20.0;
barChart.plotAreaFrame.paddingRight = 20.0;
barChart.plotAreaFrame.paddingBottom = 80.0;
// Graph title
barChart.title = #"Embarque / Descarga";
CPTMutableTextStyle *textStyle = [CPTTextStyle textStyle];
textStyle.color = [CPTColor grayColor];
textStyle.fontSize = 16.0f;
textStyle.textAlignment = CPTTextAlignmentCenter;
barChart.titleTextStyle = textStyle;
barChart.titleDisplacement = CGPointMake(1.0f, -20.0f);
barChart.titlePlotAreaFrameAnchor = CPTRectAnchorTop;
// Add plot space for horizontal bar charts
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)barChart.defaultPlotSpace;
Apoio *apoio = [[Apoio alloc] init];
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0f) length:CPTDecimalFromFloat([apoio retornaMaiorDadosGrafico:qtdEmb :qtdDesc])];
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0f) length:CPTDecimalFromFloat(16.0f)];
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)barChart.axisSet;
CPTXYAxis *x = axisSet.xAxis;
CPTMutableLineStyle *marcacaoLineStyle = [CPTLineStyle lineStyle];
marcacaoLineStyle.lineColor = [CPTColor lightGrayColor];
marcacaoLineStyle.lineWidth = 1;
x.axisLineStyle = marcacaoLineStyle;
x.majorTickLineStyle = marcacaoLineStyle;
x.minorTickLineStyle = marcacaoLineStyle;
x.majorIntervalLength = CPTDecimalFromString(#"5");
x.orthogonalCoordinateDecimal = CPTDecimalFromString(#"0");
//x.title = #"Horas";
//x.titleLocation = CPTDecimalFromFloat(15.0f);
//x.titleOffset = 55.0f;
// Define some custom labels for the data elements
x.labelingPolicy = CPTAxisLabelingPolicyNone;
NSArray *customTickLocations = posicao;//[NSArray arrayWithObjects:[NSDecimalNumber numberWithFloat:0.7], [NSDecimalNumber numberWithFloat:2.7], [NSDecimalNumber numberWithFloat:4.7], nil];
NSArray *xAxisLabels = horas;//[NSArray arrayWithObjects:#"10", #"11", #"12", nil];
NSUInteger labelLocation = 0;
NSMutableArray *customLabels = [NSMutableArray arrayWithCapacity:[xAxisLabels count]];
for ( NSNumber *tickLocation in customTickLocations ) {
CPTAxisLabel *newLabel = [[CPTAxisLabel alloc] initWithText:[xAxisLabels objectAtIndex:labelLocation++] textStyle:x.labelTextStyle];
newLabel.tickLocation = [tickLocation decimalValue];
newLabel.offset = x.labelOffset; //+ x.majorTickLength;
[customLabels addObject:newLabel];
}
x.axisLabels = [NSSet setWithArray:customLabels];
CPTXYAxis *y = axisSet.yAxis;
y.axisLineStyle = marcacaoLineStyle;
y.majorTickLineStyle = marcacaoLineStyle;
y.minorTickLineStyle = marcacaoLineStyle;
y.majorIntervalLength = CPTDecimalFromInt([apoio retornaMaiorDadosGrafico:qtdEmb :qtdDesc]/7); //CPTDecimalFromString(#"5");
y.orthogonalCoordinateDecimal = CPTDecimalFromString(#"0");
y.title = #"Containers";
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:0];
y.labelFormatter = formatter;
CPTMutableLineStyle *majorGridLineStyle = [CPTMutableLineStyle lineStyle];
majorGridLineStyle.lineWidth = 0.75;
majorGridLineStyle.lineColor = [CPTColor lightGrayColor ];
y.majorGridLineStyle = majorGridLineStyle ;
y.preferredNumberOfMajorTicks = 10;
CPTMutableTextStyle *EixostextStyle = [CPTTextStyle textStyle];
EixostextStyle.fontSize = 12.0f;
y.labelTextStyle = EixostextStyle;
x.labelTextStyle = EixostextStyle;
// Embaque
CPTBarPlot *barPlot = [CPTBarPlot tubularBarPlotWithColor:[CPTColor darkGrayColor] horizontalBars:NO];
barPlot.baseValue = CPTDecimalFromString(#"0");
barPlot.dataSource = self;
barPlot.delegate = self;
barPlot.barOffset = CPTDecimalFromFloat(0.25f);
barPlot.identifier = #"Embarque";
barPlot.title = #"Embarque";
barPlot.labelOffset = 0;
[barChart addPlot:barPlot toPlotSpace:plotSpace];
//Descarga
CPTBarPlot *barPlot2 = [CPTBarPlot tubularBarPlotWithColor:[CPTColor blueColor] horizontalBars:NO];
barPlot2.baseValue = CPTDecimalFromString(#"0");
barPlot2.dataSource = self;
barPlot2.delegate = self;
//barPlot2.barOffset = CPTDecimalFromFloat(25f);
barPlot2.identifier = #"Descarga";
barPlot2.title = #"Descarga";
barPlot2.labelOffset = 0;
[barChart addPlot:barPlot2 toPlotSpace:plotSpace];
CPTLegend *theLegend = [CPTLegend legendWithGraph:barChart];
theLegend.numberOfRows = 1;
theLegend.numberOfColumns = 2;
theLegend.cornerRadius = 10.0;
theLegend.swatchSize = CGSizeMake(15, 15);
//whiteTextStyle.fontSize = 16.0;
//theLegend.textStyle = whiteTextStyle;
theLegend.rowMargin = 10.0;
theLegend.paddingLeft = 12.0;
theLegend.paddingTop = 12.0;
theLegend.paddingRight = 12.0;
theLegend.paddingBottom = 12.0;
//theLegend.equalColumns = YES;
//theLegend.equalRows = YES;
barChart.legend = theLegend;
}
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot{
return [horas count];}
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
NSDecimalNumber *num = nil;
if ( [plot isKindOfClass:[CPTBarPlot class]] ) {
switch ( fieldEnum ) {
case CPTBarPlotFieldBarLocation:
if ( [plot.identifier isEqual:#"Embarque"] ) {
num = (NSDecimalNumber *)[NSDecimalNumber numberWithUnsignedInteger:index*2];
} else{
num = (NSDecimalNumber *)[NSDecimalNumber numberWithUnsignedInteger:(index*2+1)];
}
break;
case CPTBarPlotFieldBarTip:
if ( [plot.identifier isEqual:#"Embarque"] ) {
num = [qtdEmb objectAtIndex:index];
} else{
num = [qtdDesc objectAtIndex:index];
}
break;
}
}
return num;
}
-(CPTFill *)barFillForBarPlot:(CPTBarPlot *)barPlot recordIndex:(NSUInteger)index
{
if ( [barPlot.identifier isEqual:#"Embarque"] ) {
return [CPTFill fillWithColor:[CPTColor colorWithComponentRed:(175/255.0 ) green:(238/255.0) blue:(238/255.0) alpha:1.0]];
}
if ( [barPlot.identifier isEqual:#"Descarga"] ) {
return [CPTFill fillWithColor:[CPTColor colorWithComponentRed:(255./255.0 ) green:(228.0/255.0) blue:(181.0/255.0) alpha:1.0]];
}
}
-(CPTLayer *)dataLabelForPlot:(CPTPlot *)plot recordIndex:(NSUInteger)index
{
int valor;
if ( [plot.identifier isEqual:#"Embarque"] )
{
valor = [qtdEmb objectAtIndex:index];
}else{
valor = [qtdDesc objectAtIndex:index];
}
CPTTextLayer *newLayer = [[CPTTextLayer alloc] initWithText:[[NSString alloc] initWithFormat:#"%#",valor]];
CPTMutableTextStyle *estiloTexto = [[CPTMutableTextStyle alloc] init];
estiloTexto.color = [CPTColor blackColor];
estiloTexto.fontSize = 10;
newLayer.textStyle = estiloTexto;
return newLayer;
}

Resources