Core Plot ScatterPlot on Horizontal Bar plot - ios

I'm trying to display a line using a ScatterPlot on Bar plot, which is horizontal. It does work for vertical bar plots, but not for the horizontal one.
This is the source code:
-(id)init
{
if ( (self = [super init]) ) {
self.section = kBarPlots;
self.isOneBarPlot = TRUE;
}
return self;
}
-(void)generateData
{
[[BPDatabaseController sharedController] dataForTopFiveObservationPeriodIncidents:^(NSArray *resultArray) {
self.plotData = resultArray;
FilterManager *fm = [FilterManager sharedInstance];
self.isOneBarPlot = fm.filterPendingIncidents; //is responsible for showing the legend correctly
[self renderInLayer:self.defaultLayerHostingView withTheme:self.theme animated:YES];
[super generateData];
}];
}
-(void)renderInLayer:(CPTGraphHostingView *)layerHostingView withTheme:(CPTTheme *)theme animated:(BOOL)animated
{
CGRect bounds = layerHostingView.bounds;
CPTGraph *graph = [[CPTXYGraph alloc] initWithFrame:bounds];
[self addGraph:graph toHostingView:layerHostingView];
[self applyTheme:theme toGraph:graph withDefault:nil];
[self setTitleDefaultsForGraph:graph withBounds:bounds];
[self setPaddingDefaultsForGraph:graph withBounds:bounds];
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
graph.paddingLeft = 0.0f;
}else{
graph.paddingLeft = 65.0f;
}
graph.paddingRight = 0.0f;
NSNumberFormatter *format = [[NSNumberFormatter alloc] init];
[format setNumberStyle:NSNumberFormatterNoStyle];
// Create bar plot
CPTBarPlot *barPlot = [[CPTBarPlot alloc] init];
barPlot.lineStyle = [[CPTTheme themeNamed:kCPTDarkBlueTheme] axisLineStyle:kBarLineStyle];
barPlot.barWidth = CPTDecimalFromFloat(0.60f); // bar is 75% of the available space
barPlot.barCornerRadius = 0.0;
barPlot.barsAreHorizontal = YES;
barPlot.dataSource = self;
barPlot.identifier = kBarPlotPending;
barPlot.delegate = self;
barPlot.fill = [[CPTTheme themeNamed:kCPTDarkBlueTheme] barFillForBarPlotOfType:kHorizontalRed];
barPlot.labelTextStyle = [[CPTTheme themeNamed:kCPTDarkBlueTheme] barTextStyle];
barPlot.labelFormatter = format;
barPlot.labelOffset = 1.0;
barPlot.anchorPoint = CGPointMake(0.0, 0.0);
[barPlot addAnimation:[self plotAnimationWithKeyPath:#"transform.scale.x"] forKey:#"someKey"];
if(!self.isOneBarPlot){
[graph addPlot:barPlot];
}
// Create bar plot
CPTBarPlot *barPlot2 = [[CPTBarPlot alloc] init];
barPlot2.lineStyle = [[CPTTheme themeNamed:kCPTDarkBlueTheme] axisLineStyle:kBarLineStyle];;
barPlot2.barWidth = CPTDecimalFromFloat(0.60f); // bar is 75% of the available space
barPlot2.barCornerRadius = 0.0;
barPlot2.barsAreHorizontal = YES;
barPlot2.dataSource = self;
barPlot2.identifier = kBarPlotOfficial;
barPlot2.delegate = self;
barPlot2.labelFormatter = format;
barPlot2.fill = [[CPTTheme themeNamed:kCPTDarkBlueTheme] barFillForBarPlotOfType:kHorizontalBlue];
barPlot2.anchorPoint = CGPointMake(0.0, 0.0);
barPlot2.labelTextStyle = [[CPTTheme themeNamed:kCPTDarkBlueTheme] barTextStyle];
if(!self.isOneBarPlot){
barPlot2.labelOffset = -1.0;
}
[graph addPlot:barPlot2];
[barPlot2 addAnimation:[self plotAnimationWithKeyPath:#"transform.scale.x"] forKey:#"someKey"];
// make the bars thinner if only one data set is available
if ([self.plotData count] == 1) {
barPlot.barWidthScale = kBarWithScaleOneItem;
barPlot2.barWidthScale = kBarWithScaleOneItem;
}
if ([self.plotData count] > 0) {
// Plot space
CPTMutablePlotRange *barRange = [[barPlot plotRangeEnclosingBars] mutableCopy];
[barRange expandRangeByFactor:CPTDecimalFromDouble(1.05)];
CPTXYPlotSpace *barPlotSpace = (CPTXYPlotSpace *)graph.defaultPlotSpace;
barPlotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0f) length:CPTDecimalFromFloat([self calculateDatasourcePeak])];
barPlotSpace.yRange = barRange;
CPTScatterPlot *targetLinePlot = [[CPTScatterPlot alloc] init];
targetLinePlot.identifier = kBarPlotTarget;
targetLinePlot.title = NSLocalizedString(kBarPlotTarget, nil);
CPTMutableLineStyle *barLineStyleTarget = [[CPTMutableLineStyle alloc] init];
barLineStyleTarget.lineWidth = 2.0;
barLineStyleTarget.lineColor = [CPTColor grayColor];
targetLinePlot.dataLineStyle = barLineStyleTarget;
targetLinePlot.dataSource = self;
[graph addPlot:targetLinePlot toPlotSpace:barPlotSpace];
[self configureAxis:graph];
[self createDarkBackgroundPlot:graph isHorizontal:TRUE];
}else{
self.emtyPlot.alpha = 1.0;
// Create axes
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)graph.axisSet;
CPTXYAxis *y = axisSet.yAxis;
{
y.majorIntervalLength = CPTDecimalFromInteger(0);
y.axisLineStyle = nil;
y.labelingPolicy = CPTAxisLabelingPolicyNone;
y.labelTextStyle = nil;
y.majorTickLineStyle = nil;
y.minorTickLineStyle = nil;
y.axisConstraints = [CPTConstraints constraintWithLowerOffset:7.0];
}
CPTXYAxis *x = axisSet.xAxis;
{
x.majorIntervalLength = CPTDecimalFromInteger(0);
x.axisConstraints = [CPTConstraints constraintWithLowerOffset:8.0];
x.axisLineStyle = nil;
x.labelingPolicy = CPTAxisLabelingPolicyAutomatic;
x.majorTickLineStyle = nil;
x.minorTickLineStyle = nil;
x.labelTextStyle = nil;
}
}
}
-(void)configureAxis:(CPTGraph *)graph{
[super configureAxis:graph];
NSNumberFormatter *format = [[NSNumberFormatter alloc] init];
[format setNumberStyle:NSNumberFormatterNoStyle];
//legend
CPTLegend *theLegend = [CPTLegend legendWithGraph:graph];
theLegend.borderLineStyle = [[CPTTheme themeNamed:kCPTDarkBlueTheme] axisLineStyle:kBarLineStyle];
theLegend.cornerRadius = 0.0;
theLegend.swatchSize = CGSizeMake(16.0, 16.0);
theLegend.textStyle = [[CPTTheme themeNamed:kCPTDarkBlueTheme] barTextStyle];
theLegend.numberOfRows = 1;
graph.legend = theLegend;
graph.legendAnchor = CPTRectAnchorBottom;
graph.legendDisplacement = CGPointMake(0.0, 0.0);
// Create axes
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)graph.axisSet;
CPTXYAxis *y = axisSet.yAxis;
{
y.majorIntervalLength = CPTDecimalFromInteger(1);
y.axisLineStyle = [[CPTTheme themeNamed:kCPTDarkBlueTheme] axisLineStyle:kYAxisLineStyle];
y.labelingPolicy = CPTAxisLabelingPolicyNone;
y.orthogonalCoordinateDecimal = CPTDecimalFromInteger(1);
y.labelTextStyle = [[CPTTheme themeNamed:kCPTDarkBlueTheme] barTextStyle];
y.axisConstraints = [CPTConstraints constraintWithLowerOffset:5.0];
}
NSMutableSet *yAxisLegend = [NSMutableSet set];
for (int i = 0; i < self.plotData.count; i++) {
CPTAxisLabel *label = [[CPTAxisLabel alloc] initWithText:[self addLineBreakToString:(NSString*)[[self.plotData objectAtIndex:i] objectForKey:kResultLabel] ]textStyle:[[CPTTheme themeNamed:kCPTDarkBlueTheme] barTextStyle]];
label.tickLocation = CPTDecimalFromInteger(i);
[yAxisLegend addObject:label];
}
y.axisLabels = yAxisLegend;
CPTXYAxis *x = axisSet.xAxis;
{
x.majorIntervalLength = CPTDecimalFromInteger(1);
x.axisConstraints = [CPTConstraints constraintWithLowerOffset:8.0];
x.axisLineStyle = [[CPTTheme themeNamed:kCPTDarkBlueTheme] axisLineStyle:kXAxisLineStyle];
x.labelingPolicy = CPTAxisLabelingPolicyAutomatic;
x.majorTickLineStyle = nil;
x.minorTickLineStyle = nil;
//x.labelFormatter = format;
x.orthogonalCoordinateDecimal = CPTDecimalFromInteger(-1);
x.labelTextStyle = [[CPTTheme themeNamed:kCPTDarkBlueTheme] barTextStyle];
x.labelOffset = 5.0f;
}
}
#pragma mark -
#pragma mark Plot Data Source Methods
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{
return self.plotData.count;
}
-(NSArray *)numbersForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndexRange:(NSRange)indexRange
{
NSArray *nums = [super numbersForPlot:plot field:fieldEnum recordIndexRange:indexRange];
if (!nums) {
switch ( fieldEnum ) {
case CPTBarPlotFieldBarLocation:
nums = [NSMutableArray arrayWithCapacity:indexRange.length];
for ( NSUInteger i = indexRange.location; i < NSMaxRange(indexRange); i++ ) {
[(NSMutableArray *)nums addObject : #(i)];
}
break;
case CPTBarPlotFieldBarTip: {
if ([plot.identifier isEqual:kBarPlotTarget]) {
nums = [NSMutableArray arrayWithCapacity:indexRange.length];
for ( NSUInteger i = indexRange.location; i < NSMaxRange(indexRange); i++ ) {
[(NSMutableArray *)nums addObject:#(100)];
}
}else{
NSString *dataKey = nil;
if ([plot.identifier isEqual:kBarPlotOfficial]) {
dataKey = kResultOfficial;
}
else {
dataKey = kResultSum;
}
nums = [NSMutableArray arrayWithCapacity:indexRange.length];
for ( NSUInteger i = indexRange.location; i < NSMaxRange(indexRange); i++ ) {
NSNumber *number = [[self.plotData objectAtIndex:i] objectForKey:dataKey];
[(NSMutableArray *)nums addObject : number];
}
}
break;
}
default:
break;
}
}
return nums;
}
-(CPTLayer *)dataLabelForPlot:(CPTPlot *)plot recordIndex:(NSUInteger)idx
{
CPTTextLayer *textLayer = (id)[NSNull null];;
NSNumber *number = nil;
if ([plot.identifier isEqual:kBarPlotPending]) {
number = [[self.plotData objectAtIndex:idx] objectForKey:kResultSum];
}
else if ([plot.identifier isEqual:kBarPlotOfficial]) {
NSNumber *officialNumber = [[self.plotData objectAtIndex:idx] objectForKey:kResultOfficial];
NSNumber *pendingNumber = [[self.plotData objectAtIndex:idx] objectForKey:kResultSum];
CGFloat maxNumber = [self calculateDatasourcePeak];
// 1.) if the max peak it to high and the current value to low the
// official is not shown correclty (not enough space) => do not show it
// 2.) do not show the official if its the same number as pending
if (!(maxNumber > 100 && [officialNumber intValue] < 50) && ([officialNumber intValue] != [pendingNumber intValue])) {
number = officialNumber;
}
}
if ([number intValue] > 0) {
textLayer = [[CPTTextLayer alloc] initWithText:[number stringValue] style:[[CPTTheme themeNamed:kCPTDarkBlueTheme] barTextStyle]];
}
return textLayer;
}
#pragma mark - CPTBarPlot delegate methods
-(void)plot:(CPTPlot *)plot dataLabelWasSelectedAtRecordIndex:(NSUInteger)index
{
NSLog(#"Data label for '%#' was selected at index %d.", plot.identifier, (int)index);
}
The legend on the bottom does show that there should be a target line, but no one is displayed

Different plot types use different datasource field enumerations. Bar plots will use CPTBarPlotFieldBarLocation and CPTBarPlotFieldBarTip. Scatter plots like the target line plot will use CPTScatterPlotFieldX and CPTScatterPlotFieldY. Make sure the datasource is checking the right field enum values for each plot.

Related

ScatterPlot doens't work properly - dots isn't connected

I am developing a project using Core-Plot with Objective-C. The client asks to create a line chart (using Scatter Plot for this) where plots the number of ocurrencies x the time.
Well, after study for almost a week, this isn't working. My dots aren't connected and I don't know why.
This blue line should've been connected, since it is one plot.
Here is my code:
-(void)renderInLayer:(CPTGraphHostingView *)layerHostingView withTheme:(CPTTheme *)theme animated:(BOOL)animated{
CPTGraph *graph = [[CPTXYGraph alloc] initWithFrame:bounds];
[self addGraph:graph toHostingView:layerHostingView];
[self applyTheme:theme toGraph:graph withDefault:[CPTTheme themeNamed:kCPTDarkGradientTheme]];
graph.paddingTop = 20.0;
graph.paddingRight = 20.0;
graph.paddingLeft = 20.0;
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)graph.defaultPlotSpace;
plotSpace.allowsUserInteraction = YES;
plotSpace.delegate = self;
CPTMutableLineStyle *axesLineStyle = [CPTMutableLineStyle lineStyle];
axesLineStyle.lineWidth = 1.0f;
axesLineStyle.miterLimit = 1.0f;
axesLineStyle.lineColor = [CPTColor grayColor];
CPTTextStyle *labelTextStyle = [CPTTextStyle textStyleWithAttributes:#{ NSForegroundColorAttributeName: BoardGraphValueColor, NSFontAttributeName: BoardGraphValueFont}];
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)graph.axisSet;
NSNumberFormatter * axisFormat = [[NSNumberFormatter alloc] init];
[axisFormat setNumberStyle:NSNumberFormatterNoStyle];
CPTXYAxis *x = axisSet.xAxis;{
x.visibleRange = [CPTPlotRange plotRangeWithLocation:#(-1.0) length:#(100)];
x.labelingPolicy = CPTAxisLabelingPolicyAutomatic;
x.majorIntervalLength = #2;
x.minorTicksPerInterval = 1;
x.majorTickLineStyle = axesLineStyle;
x.minorTickLineStyle = axesLineStyle;
x.axisLineStyle = axesLineStyle;
x.plotSpace = plotSpace;
x.labelTextStyle = labelTextStyle;
x.labelFormatter = axisFormat;
x.labelOffset = 5.0;
}
CPTXYAxis *y = axisSet.yAxis;{
y.visibleRange = [CPTPlotRange plotRangeWithLocation:#(-1.0) length:#(200)];
y.labelingPolicy = CPTAxisLabelingPolicyAutomatic;
y.majorIntervalLength = #30;
y.minorTicksPerInterval = 6;
y.majorTickLineStyle = axesLineStyle;
y.minorTickLineStyle = axesLineStyle;
y.axisLineStyle = axesLineStyle;
y.plotSpace = plotSpace;
y.labelTextStyle = labelTextStyle;
y.labelFormatter = axisFormat;
y.labelOffset = 5.0;
}
graph.axisSet.axes = #[x, y];
CPTMutableLineStyle *lineStyle = [[CPTMutableLineStyle alloc] init];
lineStyle.lineWidth = 2.0;
CPTScatterPlot *scatterLinePlot = [[CPTScatterPlot alloc] init];
scatterLinePlot.areaBaseValue = #(0.0);
scatterLinePlot.identifier = #(1);
scatterLinePlot.title = #"Title";
lineStyle.lineColor = [CPTColor blueColor];
scatterLinePlot.dataLineStyle = lineStyle;
scatterLinePlot.histogramOption = self.histogramOption;
scatterLinePlot.areaBaseValue = #(0);
scatterLinePlot.delegate = self;
scatterLinePlot.plotSymbolMarginForHitDetection = 5.0;
scatterLinePlot.dataSource = self;
[graph addPlot:scatterLinePlot];
CPTPlotRange *globalYRange = [CPTPlotRange plotRangeWithLocation:#0.0
length:#12.0];
plotSpace.globalYRange = globalYRange;
[plotSpace scaleToFitEntirePlots:[graph allPlots]];}
This is the code for create just one plot, but I need to create six. I did a loop but it is working that way too.
Here's the datasource:
-(NSUInteger)numberOfRecordsForPlot:(nonnull CPTPlot *)plot{
return [self.plotData objectAtIndex:0].count;}
-(NSNumber *)numberForPlot:(nonnull CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index{
NSNumber *num = nil;
NSString *key;
NSArray *currentDataPoint;
NSString *plotIdentifier = (NSString *)plot.identifier;
if ([plotIdentifier isEqual:#(1)]){
currentDataPoint = [self.plotData objectAtIndex:0];
} else if ([plotIdentifier isEqual:#(2)]){
currentDataPoint = [self.plotData objectAtIndex:1];
} else if ([plotIdentifier isEqual:#(3)]){
currentDataPoint = [self.plotData objectAtIndex:2];
} else if ([plotIdentifier isEqual:#(4)]){
currentDataPoint = [self.plotData objectAtIndex:3];
} else if ([plotIdentifier isEqual:#(5)]){
currentDataPoint = [self.plotData objectAtIndex:4];
} else if ([plotIdentifier isEqual:#(6)]){
currentDataPoint = [self.plotData objectAtIndex:5];
}
if (fieldEnum == CPTScatterPlotFieldX) {
return #(index);
} else if (fieldEnum == CPTScatterPlotFieldY) {
key = #"count";
int number = [[[currentDataPoint objectAtIndex:index] valueForKey:key] intValue];
NSLog(#"Y value for index %lu is %d", index, number);
num = [[currentDataPoint objectAtIndex:index] valueForKey:key];
return num;}
return num;
}
What am I doing wrong?
PS: Well, another bug is the color of the bar chart. Each of this should have a different color, but it doesn't work too. The colors provided is that for the legends.
Thanks in advance.
To change the bar color for each bar, implement the -barFillForBarPlot:recordIndex: method in the datasource and return the correct fill for each index. You can also set the border line style for each bar (e.g., to use a different color) with the -barLineStyleForBarPlot:recordIndex: datasource method.
It looks like the data line is getting clipped outside the visible area. Make sure the plot data is available from the datasource when you call -scaleToFitEntirePlots:.

Why one of my y-axis labels relabel correctly when I have called scaleToFit Method?

I have added CPTSCatterPlot and CPTBarPlot for two CPTPlotSpaces in one graph.I have worten a method to reloadData for the graph but not working so correctly.I want two of graph reload the y-axis labels after I have called the ScaleToFit method. Here is my Code:
plotSpace1 = (CPTXYPlotSpace*)graph.defaultPlotSpace;
barPlot = [CPTBarPlot tubularBarPlotWithColor:[CPTColor colorWithCGColor:TJCOLOR1.CGColor] horizontalBars:_isHorizontal];
barPlot.identifier = #"Bar";
barPlot.delegate = self;
barPlot.dataSource = self;
[graph addPlot:barPlot toPlotSpace:plotSpace1];
[plotSpace1 scaleToFitPlots:[NSArray arrayWithObject:barPlot]];
plotSpace2 = [[CPTXYPlotSpace alloc]init];
[graph addPlotSpace:plotSpace2];
scatterPlot = [[CPTScatterPlot alloc]init];
scatterPlot.identifier = #"Scatter";
scatterPlot.delegate = self;
scatterPlot.dataSource = self;
[graph addPlot:scatterPlot toPlotSpace:plotSpace2];
[plotSpace2 scaleToFitPlots:[NSArray arrayWithObject:scatterPlot]];
CPTXYAxis *x = axisSet.xAxis;
x.labelingPolicy = CPTAxisLabelingPolicyNone;
x.tickDirection = CPTSignNegative;
x.labelOffset = -20.0f;
x.labelTextStyle = axisTextStyle;
[self xlabelS:x];
x.hidden = YES;
// x.axisConstraints = [CPTConstraints constraintWithLowerOffset:-3.0];
y = [[CPTXYAxis alloc]initWithFrame:CGRectZero];
y.labelingPolicy = CPTAxisLabelingPolicyAutomatic;
y.plotSpace = plotSpace1;
y.coordinate = CPTCoordinateY;
y.orthogonalCoordinateDecimal = CPTDecimalFromFloat(0);
y.labelExclusionRanges = nil;
y.labelTextStyle = axisTextStyle;
y.orthogonalCoordinateDecimal = CPTDecimalFromCGFloat(-0.5);
y.hidden = YES;
y2 = [[CPTXYAxis alloc]initWithFrame:CGRectZero];
y2.labelingPolicy = CPTAxisLabelingPolicyAutomatic;
y2.plotSpace = plotSpace2;
y2.coordinate = CPTCoordinateY;
y2.orthogonalCoordinateDecimal = CPTDecimalFromFloat([_titleArray count]);
y2.titleLocation = CPTDecimalFromInt(0);
y2.labelExclusionRanges = nil;
y2.titleOffset = -10.0f;
y2.labelOffset = -40.0f;
y2.labelTextStyle = axisTextStyle;
y2.hidden = YES;
y2.majorGridLineStyle = gridLineStyle;
NSArray *axies = [NSArray arrayWithObjects:x,y,y2, nil];
// [axies addObject:y2];
graph.axisSet.axes = axies;
- (void)reloadData
{
[graph.plotAreaFrame.plotArea removeAllAnnotations];
[graph reloadData];
[plotSpace1 scaleToFitPlots:[NSArray arrayWithObject:barPlot]];
[plotSpace2 scaleToFitPlots:[NSArray arrayWithObject:scatterPlot]];
CPTXYAxisSet *axisSet = (CPTXYAxisSet*)hostingView.hostedGraph.axisSet;
CPTXYAxis *x = axisSet.xAxis;
[self xlabelS:x];
}
- (void)xlabelS:(CPTXYAxis *)x
{
NSMutableSet *xLabels = [NSMutableSet set];
NSMutableSet *xLocations = [NSMutableSet set];
NSInteger i = 0;
for (NSString *date in _titleArray) {
CPTAxisLabel *label = [[CPTAxisLabel alloc] initWithText:date textStyle:x.labelTextStyle];
CGFloat location = i++;
label.tickLocation = CPTDecimalAdd(CPTDecimalFromCGFloat(location), barPlot.barWidth);
label.offset = x.majorTickLength;
if (label) {
[xLabels addObject:label];
[xLocations addObject:[NSNumber numberWithFloat:location]];
}
}
// x.labelingOrigin = CPTDecimalFromInt(1);
x.axisLabels = xLabels;
y.plotSpace = plotSpace1;
y.labelingPolicy = CPTAxisLabelingPolicyAutomatic;
y2.orthogonalCoordinateDecimal = CPTDecimalFromFloat([_titleArray count] );
}
Only the right y-axies relabeled correctly.Was anywhere I code wrong?Help me please!
The y-axis is tied to plotSpace1. It is independent of the other plot space. No matter how plotSpace2 changes, it won't affect the y-axis. If you want to see both scales, you'll need to add another y-axis to plotSpace2.

Objective C Core Plot Fixed Y Axis for Bar Graph

I'm trying to create a class that I can use to create bar, pie, and line graphs using the Core Plot library for an iOS application. I want to create some standardization in this class so that I only have to change a few options for each view controller that inherits my graph class. I have the pie graphs working the way I want, but I'm having issues with the bar graphs. I want a bar graph that is horizontal and where the Y axis is fixed for each plot based on how many plots there are.
Code:
enum
{
PieGraph = 0,
LineGraph,
BarGraph
};
Graph.h:
#import "CorePlot-CocoaTouch.h"
#import "BaseViewController.h"
CPTGraphHostingView *hostView;
CPTTheme *selectedTheme;
/*************** graphing options *******************/
int graphType;
int fillPercentage;
CGFloat xMax;
CGFloat yMax;
NSString *graphTitle;
NSString *xAxisTitle;
NSString *yAxisTitle;
BOOL graphOnBottom;
#interface Graph : BaseViewController<CPTPlotDataSource, UIActionSheetDelegate, CPTBarPlotDataSource, CPTBarPlotDelegate>
/*************** Methods *****************/
// graphing methods
-(void)initPlot;
-(void)configureHost;
-(void)configureGraph;
-(void)configureChart;
-(void)configureLegend;
-(void)configurePlots;
-(void)configureAxes;
#end
Graph.m:
#import "Graph.h"
#implementation Graph
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[self initPlot];
}
/************************ Methods *************************/
// initialize the entire graph plot
-(void)initPlot
{
[self configureHost];
[self configureGraph];
if (graphType == PieGraph)
{
[self configureChart];
[self configureLegend];
}
else if (graphType == BarGraph)
{
[self configurePlots];
[self configureAxes];
}
}
// configure the host
-(void)configureHost
{
CGRect parentRect = self.view.bounds;
int maxHeight = (parentRect.size.height - 55);
int height = (maxHeight - ((100 - fillPercentage) * maxHeight / 100));
int yPosition;
if (graphOnBottom) yPosition = (maxHeight - height + 55);
else yPosition = 55;
parentRect = CGRectMake(parentRect.origin.x, yPosition, parentRect.size.width, height);
hostView = [(CPTGraphHostingView *) [CPTGraphHostingView alloc] initWithFrame:parentRect];
hostView.allowPinchScaling = NO;
[self.view addSubview:hostView];
}
// configure the graph
-(void)configureGraph
{
CPTGraph *graph = [[CPTXYGraph alloc] initWithFrame:hostView.bounds];
hostView.hostedGraph = graph;
if (graphType == PieGraph)
{
graph.paddingLeft = 0.0f;
graph.paddingTop = 0.0f;
graph.paddingRight = 0.0f;
graph.paddingBottom = 0.0f;
graph.axisSet = nil;
}
else if (graphType == BarGraph)
{
graph.plotAreaFrame.masksToBorder = NO;
if ([xAxisTitle isEqualToString:#""]) graph.paddingBottom = 0.0f;
else graph.paddingBottom = 30.0f;
if ([yAxisTitle isEqualToString:#""]) graph.paddingLeft = 0.0f;
else graph.paddingLeft = 30.0f;
graph.paddingTop = 0.0f;
graph.paddingRight = 0.0f;
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *) graph.defaultPlotSpace;
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromCGFloat(0.0f) length:CPTDecimalFromCGFloat(xMax)];
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromCGFloat(0.0f) length:CPTDecimalFromCGFloat(yMax)];
}
else if (graphType == LineGraph)
{
}
CPTMutableTextStyle *textStyle = [CPTMutableTextStyle textStyle];
textStyle.color = [CPTColor blackColor];
textStyle.fontName = #"Helvetica-Bold";
textStyle.fontSize = 12.0f;
graph.title = graphTitle;
graph.titleTextStyle = textStyle;
graph.titlePlotAreaFrameAnchor = CPTRectAnchorTop;
selectedTheme = [CPTTheme themeNamed:kCPTPlainWhiteTheme];
[graph applyTheme:selectedTheme];
}
// configure the chart
-(void)configureChart
{
CPTGraph *graph = hostView.hostedGraph;
CPTGradient *overlayGradient = [[CPTGradient alloc] init];
overlayGradient.gradientType = CPTGradientTypeRadial;
overlayGradient = [overlayGradient addColorStop:[[CPTColor blackColor] colorWithAlphaComponent:0.0] atPosition:0.9];
overlayGradient = [overlayGradient addColorStop:[[CPTColor blackColor] colorWithAlphaComponent:0.4] atPosition:1.0];
CPTPieChart *pieChart = [[CPTPieChart alloc] init];
pieChart.dataSource = self;
pieChart.delegate = self;
pieChart.pieRadius = (hostView.bounds.size.height * 0.7) / 2.5;
pieChart.identifier = graph.title;
pieChart.startAngle = M_PI_4;
pieChart.sliceDirection = CPTPieDirectionClockwise;
pieChart.overlayFill = [CPTFill fillWithGradient:overlayGradient];
[graph addPlot:pieChart];
}
// configure plots
-(void)configurePlots
{
CPTGraph *graph = hostView.hostedGraph;
if (graphType == BarGraph)
{
CPTMutableLineStyle *barLineStyle = [[CPTMutableLineStyle alloc] init];
barLineStyle.lineColor = [CPTColor lightGrayColor];
barLineStyle.lineWidth = 0.5;
CPTBarPlot *bar = [CPTBarPlot tubularBarPlotWithColor:[CPTColor redColor] horizontalBars:YES];
bar.dataSource = self;
bar.delegate = self;
bar.barWidth = CPTDecimalFromFloat(2.5f);
bar.barOffset = CPTDecimalFromFloat(2.5f);
bar.identifier = #"redBar";
bar.lineStyle = barLineStyle;
CPTBarPlot *bar2 = [CPTBarPlot tubularBarPlotWithColor:[CPTColor greenColor] horizontalBars:YES];
bar2.dataSource = self;
bar2.delegate = self;
bar2.barWidth = CPTDecimalFromFloat(2.5f);
bar2.barOffset = CPTDecimalFromFloat(2.5f);
bar2.identifier = #"greenBar";
bar2.lineStyle = barLineStyle;
[graph addPlot:bar toPlotSpace:graph.defaultPlotSpace];
[graph addPlot:bar2 toPlotSpace:graph.defaultPlotSpace];
}
else if (graphType == LineGraph)
{
}
}
// configure axes
-(void)configureAxes
{
if (graphType == BarGraph)
{
CPTMutableTextStyle *axisTitleStyle = [CPTMutableTextStyle textStyle];
axisTitleStyle.color = [CPTColor blackColor];
axisTitleStyle.fontName = #"Helvetica-Bold";
axisTitleStyle.fontSize = 12.0f;
CPTMutableLineStyle *axisLineStyle = [CPTMutableLineStyle lineStyle];
axisLineStyle.lineWidth = 2.0f;
axisLineStyle.lineColor = [[CPTColor blackColor] colorWithAlphaComponent:1];
CPTXYAxisSet *axisSet = (CPTXYAxisSet *) hostView.hostedGraph.axisSet;
axisSet.xAxis.labelingPolicy = CPTAxisLabelingPolicyNone;
axisSet.xAxis.title = xAxisTitle;
axisSet.xAxis.titleTextStyle = axisTitleStyle;
axisSet.xAxis.titleOffset = 5.0f;
axisSet.xAxis.axisLineStyle = axisLineStyle;
axisSet.yAxis.labelingPolicy = CPTAxisLabelingPolicyNone;
axisSet.yAxis.title = yAxisTitle;
axisSet.yAxis.titleTextStyle = axisTitleStyle;
axisSet.yAxis.titleOffset = 5.0f;
axisSet.yAxis.axisLineStyle = axisLineStyle;
}
else if (graphType == LineGraph)
{
}
}
// configure the legend
-(void)configureLegend
{
CPTGraph *graph = hostView.hostedGraph;
CPTLegend *legend = [CPTLegend legendWithGraph:graph];
legend.numberOfColumns = 1;
legend.fill = [CPTFill fillWithColor:[CPTColor whiteColor]];
legend.borderLineStyle = [CPTLineStyle lineStyle];
legend.cornerRadius = 5.0;
graph.legend = legend;
graph.legendAnchor = CPTRectAnchorBottomLeft;
//CGFloat legendPadding = -(self.view.bounds.size.width / 8);
graph.legendDisplacement = CGPointMake(3.0, 3.0);
}
#end
And finally the view controller class I am testing all of this on:
TestView.h:
#import "Graph.h"
NSArray *channel;
int offline;
int online;
#interface TestView : Graph
/*************** Methods *****************/
// back button
- (IBAction)backButtonClicked:(id)sender;
// handle view load
-(void) handleViewLoad;
// set arrays
-(void)setArrays;
#end
TestView.m:
#import "TestView.h"
#interface TestView ()
#end
#implementation TestView
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
[self handleViewLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)backButtonClicked:(id)sender
{
[self dismissViewControllerAnimated:YES completion:nil];
}
/*************** graph things ****************/
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{
return 1;
}
-(NSNumber*)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)idx
{
int returnVal = 0;
NSLog([NSString stringWithFormat:#"idx: %d", idx]);
/*switch (idx)
{
case 0:
for (int x = 0; x < [channel count]; x++)
{
if ([channel[x] integerValue] == 20) returnVal ++;
}
offline = returnVal;
return [NSNumber numberWithInt:returnVal];
break;
case 1:
for (int x = 0; x < [channel count]; x++)
{
if ([channel[x] integerValue] != 20) returnVal ++;
}
online = returnVal;
return [NSNumber numberWithInt:returnVal];
break;
}*/
if ([plot.identifier isEqual:#"greenBar"])
{
for (int x = 0; x < [channel count]; x++)
{
if ([channel[x] integerValue] != 20) returnVal ++;
}
online = returnVal;
return [NSNumber numberWithInt:returnVal];
}
else if ([plot.identifier isEqual:#"redBar"])
{
for (int x = 0; x < [channel count]; x++)
{
if ([channel[x] integerValue] == 20) returnVal ++;
}
offline = returnVal;
return [NSNumber numberWithInt:returnVal];
}
return 0;
}
-(CPTLayer*)dataLabelForPlot:(CPTPlot *)plot recordIndex:(NSUInteger)idx
{
/*switch (idx)
{
case 0:
return [[CPTTextLayer alloc] initWithText:[NSString stringWithFormat:#"Offline: %d", offline]];
break;
default:
return [[CPTTextLayer alloc] initWithText:[NSString stringWithFormat:#"Online: %d", online]];
break;
}*/
if ([plot.identifier isEqual:#"greenBar"])
{
return [[CPTTextLayer alloc] initWithText:[NSString stringWithFormat:#"Online: %d", online]];
}
else if ([plot.identifier isEqual:#"redBar"])
{
return [[CPTTextLayer alloc] initWithText:[NSString stringWithFormat:#"Offline: %d", offline]];
}
return nil;
}
-(NSString*)legendTitleForPieChart:(CPTPieChart*)pieChart recordIndex:(NSUInteger)idx
{
switch (idx)
{
case 0:
return #"Offline";
break;
default:
return #"Online";
break;
}
return #"";
}
// handle view load
-(void)handleViewLoad
{
session = [BaseViewController getSession];
[self setArrays];
graphType = BarGraph;
fillPercentage = 50;
graphOnBottom = NO;
graphTitle = #"Coordinators Online/Offline";
xAxisTitle = #"Number of Devices";
yAxisTitle = #"";
xMax = (CGFloat)([channel count] + ([channel count] * 0.30f));
yMax = (CGFloat)([channel count] + ([channel count] * 0.30f));
[self initPlot];
}
// set arrays
-(void)setArrays
{
channel = [Json extractCoordinatorChannel:session];
}
#end
Here are some examples of what my graphs look like:
As you can see, the issue is that both the x and y axes are changing based on the value. I need only the x axis to change, and the y axis to be fixed for each plot.
The datasource should check the fieldEnum parameter to see which data field (bar location or bar tip) is being requested.
switch ( fieldEnum ) {
case CPTBarPlotFieldBarLocation:
returnVal = /* y value */;
break;
case CPTBarPlotFieldBarTip:
returnVal = /* x value */;
break;
default:
break;
}

Enable x-Axis (Horizontal) scroll in coreplot

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.

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