x-axis labels in coreplot not displayed - ios

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;

Related

CorePlot bar graph not showing up

I have an implementation of CorePlot in my project and though I have no relevant errors or warnings in Xcode, have been unsuccessful in getting the plot to show up in the graph. The axis and chart show up fine, but no bars in the graph.
Any help or advice would be appreciated!
Header File
#import <UIKit/UIKit.h>
#import "PresentedViewControllerDelegate.h"
#import <CorePlot/ios/CorePlot.h>
#interface DeviceDetailModal : UIViewController <PresentedViewControllerDelegate, UIWebViewDelegate, UITableViewDataSource, UITableViewDelegate, CPTPlotDataSource,CPTBarPlotDelegate>{
CPTGraph *graph;
}
#property (weak, nonatomic) IBOutlet UITableView *tableView;
#property (nonatomic, weak) id <PresentedViewControllerDelegate> delegate;
#property (strong,nonatomic) NSArray *dataSet;
#property (nonatomic, strong) CPTBarPlot *aaplPlot;
#property (nonatomic, strong) CPTPlotSpaceAnnotation *priceAnnotation;
#end
Main File
#import <Foundation/Foundation.h>
#import "DeviceDetailModal.h"
#import "DetailCell.h"
#import <CorePlot/ios/CorePlot.h>
#import "Constants.h"
#implementation DeviceDetailModal
NSString * const CPDTickerSymbolAAPL = #"AAPL";
CGFloat const CPDBarWidth = 0.25f;
CGFloat const CPDBarInitialX = 0.25f;
#synthesize aaplPlot = aaplPlot_;
-(void)viewDidLoad{
[super viewDidLoad];
[self.view setBackgroundColor:[UIColor colorWithRed:0.03 green:0.06 blue:0.10 alpha:1.0]];
UIBarButtonItem *closeButton = [[UIBarButtonItem alloc] initWithTitle:#"Close" style:UIBarButtonItemStylePlain target:self action:#selector(closeView)];
self.navigationItem.leftBarButtonItem = closeButton;
[[UIBarButtonItem appearance] setTintColor:[UIColor lightGrayColor]];
[[UINavigationBar appearance] setBarTintColor:[UIColor blackColor]];
self.tableView.layer.cornerRadius = 10.0;
self.tableView.layer.borderWidth = 0.7;
self.tableView.layer.borderColor = [UIColor whiteColor].CGColor;
self.tableView.opaque = NO;
self.tableView.backgroundColor = [UIColor clearColor];
self.tableView.backgroundView = nil;
self.dataSet = [[NSArray alloc] init];
self.dataSet = [NSArray arrayWithObjects:
[NSDecimalNumber numberWithFloat:571.70],
[NSDecimalNumber numberWithFloat:560.28],
[NSDecimalNumber numberWithFloat:610.00],
[NSDecimalNumber numberWithFloat:607.70],
[NSDecimalNumber numberWithFloat:603.00],
nil];
[self configureGraph];
[graph reloadData];
}
-(void)configureGraph {
CGRect hostingRect = CGRectMake(20, 350, 335, 310);
CPTGraphHostingView *hostingView = [[CPTGraphHostingView alloc] initWithFrame:hostingRect];
[self.view addSubview:hostingView];
[hostingView setBackgroundColor:[UIColor colorWithRed:0.03 green:0.06 blue:0.10 alpha:1.0]];
hostingView.layer.cornerRadius = 10.0;
hostingView.layer.borderWidth = 0.7;
hostingView.layer.borderColor = [UIColor whiteColor].CGColor;
graph = [[CPTXYGraph alloc] initWithFrame:hostingView.bounds];
hostingView.hostedGraph = graph;
[[graph defaultPlotSpace] setAllowsUserInteraction:TRUE];
// 1 - Create the graph
graph.plotAreaFrame.masksToBorder = NO;
// 2 - Configure the graph
//[graph applyTheme:[CPTTheme themeNamed:kCPTPlainBlackTheme]];
graph.paddingBottom = 30.0f;
graph.paddingLeft = 30.0f;
graph.paddingTop = -1.0f;
graph.paddingRight = -5.0f;
// 3 - Set up styles
CPTMutableTextStyle *titleStyle = [CPTMutableTextStyle textStyle];
titleStyle.color = [CPTColor whiteColor];
titleStyle.fontName = #"Helvetica-Bold";
titleStyle.fontSize = 16.0f;
// 4 - Set up title
NSString *title = #"Portfolio Prices: April 23 - 27, 2012";
graph.title = title;
graph.titleTextStyle = titleStyle;
graph.titlePlotAreaFrameAnchor = CPTRectAnchorTop;
graph.titleDisplacement = CGPointMake(0.0f, -16.0f);
// 5 - Set up plot space
CGFloat xMin = 0.0f;
CGFloat xMax = 7;
CGFloat yMin = 0.0f;
CGFloat yMax = 800.0f; // should determine dynamically based on max price
NSNumber *xAxisStart = [NSNumber numberWithFloat:xMin];
NSNumber *xAxisLength = [NSNumber numberWithDouble:xMax];
NSNumber *yAxisStart = [NSNumber numberWithFloat:yMin];
NSNumber *yAxisLength = [NSNumber numberWithDouble:yMax];
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *) graph.defaultPlotSpace;
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:xAxisStart length:xAxisLength];
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:yAxisStart length:yAxisLength];
// 1 - Set up the three plots
self.aaplPlot = [CPTBarPlot tubularBarPlotWithColor:[CPTColor redColor] horizontalBars:NO];
self.aaplPlot.identifier = CPDTickerSymbolAAPL;
// 2 - Set up line style
CPTMutableLineStyle *barLineStyle = [[CPTMutableLineStyle alloc] init];
barLineStyle.lineColor = [CPTColor lightGrayColor];
barLineStyle.lineWidth = 0.5;
// 3 - Add plots to graph
graph = hostingView.hostedGraph;
CGFloat barX = CPDBarInitialX;
NSArray *plots = [NSArray arrayWithObjects:self.aaplPlot, nil];
for (CPTBarPlot *plot in plots) {
plot.dataSource = self;
plot.delegate = self;
plot.barWidth = [NSNumber numberWithFloat:CPDBarWidth];
plot.barOffset = [NSNumber numberWithFloat:barX];
plot.lineStyle = barLineStyle;
[graph addPlot:plot toPlotSpace:graph.defaultPlotSpace];
barX += CPDBarWidth;
}
// 1 - Configure 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] colorWithAlphaComponent:1];
// 2 - Get the graph's axis set
CPTXYAxisSet *axisSet = (CPTXYAxisSet *) hostingView.hostedGraph.axisSet;
// 3 - Configure the x-axis
axisSet.xAxis.labelingPolicy = CPTAxisLabelingPolicyNone;
axisSet.xAxis.title = #"Days of Week (Mon - Fri)";
axisSet.xAxis.titleTextStyle = axisTitleStyle;
axisSet.xAxis.titleOffset = 10.0f;
axisSet.xAxis.axisLineStyle = axisLineStyle;
// 4 - Configure the y-axis
axisSet.yAxis.labelingPolicy = CPTAxisLabelingPolicyNone;
axisSet.yAxis.title = #"Price";
axisSet.yAxis.titleTextStyle = axisTitleStyle;
axisSet.yAxis.titleOffset = 5.0f;
axisSet.yAxis.axisLineStyle = axisLineStyle;
}
#pragma mark - CPTPlotDataSource methods
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot {
return [self.dataSet count];
}
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index {
NSLog(#"DATA: %#",[self.dataSet objectAtIndex:index]);
return [self.dataSet objectAtIndex:index];
}
#pragma mark - CPTBarPlotDelegate methods
-(void)barPlot:(CPTBarPlot *)plot barWasSelectedAtRecordIndex:(NSUInteger)index {
// 1 - Is the plot hidden?
if (plot.isHidden == YES) {
return;
}
// 2 - Create style, if necessary
static CPTMutableTextStyle *style = nil;
if (!style) {
style = [CPTMutableTextStyle textStyle];
style.color= [CPTColor yellowColor];
style.fontSize = 16.0f;
style.fontName = #"Helvetica-Bold";
}
// 3 - Create annotation, if necessary
NSNumber *price = [self numberForPlot:plot field:CPTBarPlotFieldBarTip recordIndex:index];
if (!self.priceAnnotation) {
NSNumber *x = [NSNumber numberWithInt:0];
NSNumber *y = [NSNumber numberWithInt:0];
NSArray *anchorPoint = [NSArray arrayWithObjects:x, y, nil];
self.priceAnnotation = [[CPTPlotSpaceAnnotation alloc] initWithPlotSpace:plot.plotSpace anchorPlotPoint:anchorPoint];
}
// 4 - Create number formatter, if needed
static NSNumberFormatter *formatter = nil;
if (!formatter) {
formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:2];
}
// 5 - Create text layer for annotation
NSString *priceValue = [formatter stringFromNumber:price];
CPTTextLayer *textLayer = [[CPTTextLayer alloc] initWithText:priceValue style:style];
self.priceAnnotation.contentLayer = textLayer;
// 6 - Get plot index based on identifier
NSInteger plotIndex = 0;
if ([plot.identifier isEqual:CPDTickerSymbolAAPL] == YES) {
plotIndex = 0;
}
// 7 - Get the anchor point for annotation
CGFloat x = index + CPDBarInitialX + (plotIndex * CPDBarWidth);
NSNumber *anchorX = [NSNumber numberWithFloat:x];
CGFloat y = [price floatValue] + 40.0f;
NSNumber *anchorY = [NSNumber numberWithFloat:y];
self.priceAnnotation.anchorPlotPoint = [NSArray arrayWithObjects:anchorX, anchorY, nil];
// 8 - Add the annotation
[plot.graph.plotAreaFrame.plotArea addAnnotation:self.priceAnnotation];
}
#end
Plot ranges are given as a starting location and length. In your case, make the starting location the min value and the length max - min. Right now it's ok since the min is zero, but the length will be wrong if you ever change the min values.
The -numberForPlot:field:recordIndex: datasource method must check the field parameter and return the correct value for the field. Return the index parameter value for the CPTBarPlotFieldBarLocation field. Return the value from the dataSet array for the CPTBarPlotFieldBarTip field.

Any special considerations for using horizontal bar chart bars

I've been trying to make a horizontal bar chart using CorePlot in iOS.
I'm trying to find documentation but I cant seem to find anything good for this area. What else do I need to change if I make the bars horizontal? Is it simply a display things, or do I need to change data too?
These would be
xRange, yRange
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index implementation
Here's what I have so far...
#pragma mark -
#pragma mark - Chart behavior
-(void)initPlot {
[self configureGraph];
[self configurePlots];
[self configureAxes];
}
-(void)configureGraph {
CPTGraph *countryGraph = [[CPTXYGraph alloc] initWithFrame:self.countryGraph.bounds];
CPTGraph *timeZoneGraph = [[CPTXYGraph alloc] initWithFrame:self.timeZoneGraph.bounds];
countryGraph.plotAreaFrame.masksToBorder = NO;
timeZoneGraph.plotAreaFrame.masksToBorder = NO;
self.countryGraph.hostedGraph = countryGraph;
self.timeZoneGraph.hostedGraph = timeZoneGraph;
CPTXYPlotSpace *countryPlotSpace = (CPTXYPlotSpace *) countryGraph.defaultPlotSpace;
countryPlotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0) length:CPTDecimalFromFloat([self.countryData[0] count])];
countryPlotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0) length:CPTDecimalFromFloat([self.countryData count]*50)];
CPTXYPlotSpace *timeZonePlotSpace = (CPTXYPlotSpace *) timeZoneGraph.defaultPlotSpace;
timeZonePlotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0) length:CPTDecimalFromFloat([self.timeZoneData[0] count])];
timeZonePlotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0) length:CPTDecimalFromFloat([self.timeZoneData count]*50)];
}
-(void)configurePlots {
CPTBarPlot *countryPlot = [CPTBarPlot tubularBarPlotWithColor:[CPTColor colorWithComponentRed:19/255.0 green:221/255.0 blue:187/255.0 alpha:1] horizontalBars:YES];
countryPlot.identifier = #"CountryPlot";
CPTBarPlot *timeZonePlot = [CPTBarPlot tubularBarPlotWithColor:[CPTColor colorWithComponentRed:30/255.0 green:33/255.0 blue:36/255.0 alpha:1] horizontalBars:YES];
timeZonePlot.identifier = #"TimeZonePlot";
CPTMutableLineStyle *barLineStyle = [[CPTMutableLineStyle alloc] init];
barLineStyle.lineColor = [CPTColor whiteColor];
barLineStyle.lineWidth = 1.0;
CPTGraph *countryGraph = self.countryGraph.hostedGraph;
CPTGraph *timeZoneGraph = self.timeZoneGraph.hostedGraph;
countryPlot.dataSource = self;
countryPlot.delegate = self;
countryPlot.barWidth = CPTDecimalFromDouble(20);
countryPlot.baseValue = CPTDecimalFromString(#"0");
countryPlot.lineStyle = barLineStyle;
countryPlot.barOffset = CPTDecimalFromFloat(0.25f);
[countryGraph addPlot:countryPlot toPlotSpace:countryGraph.defaultPlotSpace];
timeZonePlot.dataSource = self;
timeZonePlot.delegate = self;
timeZonePlot.baseValue = CPTDecimalFromString(#"0");
timeZonePlot.barWidth = CPTDecimalFromDouble(20);
timeZonePlot.lineStyle = barLineStyle;
timeZonePlot.barOffset = CPTDecimalFromFloat(0.25f);
[timeZoneGraph addPlot:timeZonePlot toPlotSpace:timeZoneGraph.defaultPlotSpace];
}
-(void)configureAxes {
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] colorWithAlphaComponent:1];
CPTXYAxisSet *countryAxisSet = (CPTXYAxisSet *) self.countryGraph.hostedGraph.axisSet;
CPTXYAxis *x = countryAxisSet.xAxis;
x.labelingPolicy = CPTAxisLabelingPolicyNone;
x.axisLineStyle = axisLineStyle;
x.majorIntervalLength = CPTDecimalFromString(#"20");
CPTXYAxis *y = countryAxisSet.yAxis;
y.labelingPolicy = CPTAxisLabelingPolicyNone;
y.axisLineStyle = axisLineStyle;
y.majorIntervalLength = CPTDecimalFromString(#"50");
CPTXYAxisSet *timeZoneAxisSet = (CPTXYAxisSet *) self.timeZoneGraph.hostedGraph.axisSet;
CPTXYAxis *x2 = timeZoneAxisSet.xAxis;
x2.labelingPolicy = CPTAxisLabelingPolicyNone;
x2.axisLineStyle = axisLineStyle;
x2.majorIntervalLength = CPTDecimalFromString(#"20");
CPTXYAxis *y2 = timeZoneAxisSet.yAxis;
y2.labelingPolicy = CPTAxisLabelingPolicyNone;
y2.axisLineStyle = axisLineStyle;
y2.majorIntervalLength = CPTDecimalFromString(#"50");
}
#pragma mark - CPTPlotDataSource methods
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot {
NSUInteger num = 0;
if ([plot.identifier isEqual:#"CountryPlot"]) {
num = self.countryData.count;
} else {
num = self.timeZoneData.count;
}
return num;
}
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index {
NSNumber *num = #0;
switch (fieldEnum) {
case CPTBarPlotFieldBarTip:
if ([plot.identifier isEqual:#"CountryPlot"]) {
num = [NSNumber numberWithInteger:[self.countryData[index] count]];
} else {
num = [NSNumber numberWithInteger:[self.timeZoneData[index] count]];
}
break;
default:
num = [NSNumber numberWithInteger:index];
break;
}
return num;
}
Here's what it makes
And I'd prefer that the bars would be stacked up on top of each other with a small separation.... so what have I missed?
Set barsAreHorizontal to YES on the bar plot to make horizontal bars. Everything else is the same except the bar locations are now on the y-axis and the bar tip and base values are on the x-axis.

Adding Coreplot Graph UIViewController to another UIViewController's view

So I am having an issue with Coreplot.
I am currently attempting to add my Coreplot graph that i implemented within one of my UIViewController's subviews.
I implemented the Coreplot graph in a UIViewCOntroller class and attempted to add the coreplot viewcontroller's ".view" to the subview of another Viewcontroller.
ScatterPlotViewController *scatterPlot = [[ScatterPlotViewController alloc] init];
[graphView addSubview:scatterPlot.view];
Where graphview is a small uiview among a few other's inside my mainview controller.
CorePlot example
The example implements a 3 graphs but currently I just implemented one (the scatter plot) without using storyboard. The graph displays fine when I ask the main view controller to push to another viewcontroller
ScatterPlotViewController *scatter = [[ScatterPlotViewController alloc] init];
[self.navigationController pushViewController:scatter animated:YES];
I am lost :(.
I tried to read several more similar questions but all lead me to using the HOSTVIEW or
graphView = [(CPTGraphHostingView *) [CPTGraphHostingView alloc] initWithFrame:CGRectMake(120, 296, 200, 120)];
graphView.backgroundColor = [UIColor redColor];
[self.view addSubview:graphView];
ScatterPlotViewController *scatterPlot = [[ScatterPlotViewController alloc] init];
[graphView.hostedGraph.hostingView addSubview:scatterPlot.hostView.inputView];
I have changed this around a few times, channging
scatterPlot.hostView.inputView to scatterPlot.view
changing
graphView.hostedGraph.hostingView to graphView.view
And several others.
Here is the entire code for the class I used, it is basically the entire code that is used in the tutorial link. I also didn't use storyboards like the tutorial. I just used the code.
.h
#import <UIKit/UIKit.h>
#import "CorePlot-CocoaTouch.h"
#import "CPDConstants.h"
#import "CPDStockPriceStore.h"
#interface ScatterPlotViewController : UIViewController <CPTPlotDataSource>
#property (nonatomic, strong) CPTGraphHostingView *hostView;
.m
#import "ScatterPlotViewController.h"
#implementation ScatterPlotViewController
#synthesize hostView = hostView_;
-(void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - UIViewController lifecycle methods
-(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[self initPlot];
}
#pragma mark - Chart behavior
-(void)initPlot {
[self configureHost];
[self configureGraph];
[self configurePlots];
[self configureAxes];
}
-(void)configureHost {
self.hostView = [(CPTGraphHostingView *) [CPTGraphHostingView alloc] initWithFrame:self.view.bounds];
self.hostView.allowPinchScaling = YES;
[self.view addSubview:self.hostView];
}
-(void)configureGraph {
// 1 - Create the graph
CPTGraph *graph = [[CPTXYGraph alloc] initWithFrame:self.hostView.bounds];
[graph applyTheme:[CPTTheme themeNamed:kCPTDarkGradientTheme]];
self.hostView.hostedGraph = graph;
// 2 - Set graph title
NSString *title = #"Portfolio Prices: April 2012";
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:30.0f];
[graph.plotAreaFrame setPaddingBottom:30.0f];
// 5 - Enable user interactions for plot space
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *) graph.defaultPlotSpace;
plotSpace.allowsUserInteraction = YES;
}
-(void)configurePlots {
// 1 - Get graph and plot space
CPTGraph *graph = self.hostView.hostedGraph;
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *) graph.defaultPlotSpace;
// 2 - Create the three plots
CPTScatterPlot *aaplPlot = [[CPTScatterPlot alloc] init];
aaplPlot.dataSource = self;
aaplPlot.identifier = CPDTickerSymbolAAPL;
CPTColor *aaplColor = [CPTColor redColor];
[graph addPlot:aaplPlot toPlotSpace:plotSpace];
CPTScatterPlot *googPlot = [[CPTScatterPlot alloc] init];
googPlot.dataSource = self;
googPlot.identifier = CPDTickerSymbolGOOG;
CPTColor *googColor = [CPTColor greenColor];
[graph addPlot:googPlot toPlotSpace:plotSpace];
CPTScatterPlot *msftPlot = [[CPTScatterPlot alloc] init];
msftPlot.dataSource = self;
msftPlot.identifier = CPDTickerSymbolMSFT;
CPTColor *msftColor = [CPTColor blueColor];
[graph addPlot:msftPlot toPlotSpace:plotSpace];
// 3 - Set up plot space
[plotSpace scaleToFitPlots:[NSArray arrayWithObjects:aaplPlot, googPlot, msftPlot, nil]];
CPTMutablePlotRange *xRange = [plotSpace.xRange mutableCopy];
[xRange expandRangeByFactor:CPTDecimalFromCGFloat(1.1f)];
plotSpace.xRange = xRange;
CPTMutablePlotRange *yRange = [plotSpace.yRange mutableCopy];
[yRange expandRangeByFactor:CPTDecimalFromCGFloat(1.2f)];
plotSpace.yRange = yRange;
// 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;
CPTMutableLineStyle *googLineStyle = [googPlot.dataLineStyle mutableCopy];
googLineStyle.lineWidth = 1.0;
googLineStyle.lineColor = googColor;
googPlot.dataLineStyle = googLineStyle;
CPTMutableLineStyle *googSymbolLineStyle = [CPTMutableLineStyle lineStyle];
googSymbolLineStyle.lineColor = googColor;
CPTPlotSymbol *googSymbol = [CPTPlotSymbol starPlotSymbol];
googSymbol.fill = [CPTFill fillWithColor:googColor];
googSymbol.lineStyle = googSymbolLineStyle;
googSymbol.size = CGSizeMake(6.0f, 6.0f);
googPlot.plotSymbol = googSymbol;
CPTMutableLineStyle *msftLineStyle = [msftPlot.dataLineStyle mutableCopy];
msftLineStyle.lineWidth = 2.0;
msftLineStyle.lineColor = msftColor;
msftPlot.dataLineStyle = msftLineStyle;
CPTMutableLineStyle *msftSymbolLineStyle = [CPTMutableLineStyle lineStyle];
msftSymbolLineStyle.lineColor = msftColor;
CPTPlotSymbol *msftSymbol = [CPTPlotSymbol diamondPlotSymbol];
msftSymbol.fill = [CPTFill fillWithColor:msftColor];
msftSymbol.lineStyle = msftSymbolLineStyle;
msftSymbol.size = CGSizeMake(6.0f, 6.0f);
msftPlot.plotSymbol = msftSymbol;
}
-(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 = #"Day of Month";
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;
CGFloat dateCount = [[[CPDStockPriceStore sharedInstance] datesInMonth] count];
NSMutableSet *xLabels = [NSMutableSet setWithCapacity:dateCount];
NSMutableSet *xLocations = [NSMutableSet setWithCapacity:dateCount];
NSInteger i = 0;
for (NSString *date in [[CPDStockPriceStore sharedInstance] datesInMonth]) {
CPTAxisLabel *label = [[CPTAxisLabel alloc] initWithText:date textStyle:x.labelTextStyle];
CGFloat location = i++;
label.tickLocation = CPTDecimalFromCGFloat(location);
label.offset = x.majorTickLength;
if (label) {
[xLabels addObject:label];
[xLocations addObject:[NSNumber numberWithFloat:location]];
}
}
x.axisLabels = xLabels;
x.majorTickLocations = xLocations;
// 4 - Configure y-axis
CPTAxis *y = axisSet.yAxis;
y.title = #"Price";
y.titleTextStyle = axisTitleStyle;
y.titleOffset = -40.0f;
y.axisLineStyle = axisLineStyle;
y.majorGridLineStyle = gridLineStyle;
y.labelingPolicy = CPTAxisLabelingPolicyNone;
y.labelTextStyle = axisTextStyle;
y.labelOffset = 16.0f;
y.majorTickLineStyle = axisLineStyle;
y.majorTickLength = 4.0f;
y.minorTickLength = 2.0f;
y.tickDirection = CPTSignPositive;
NSInteger majorIncrement = 100;
NSInteger minorIncrement = 50;
CGFloat yMax = 700.0f; // 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", j] textStyle:y.labelTextStyle];
NSDecimal location = CPTDecimalFromInteger(j);
label.tickLocation = location;
label.offset = -y.majorTickLength - y.labelOffset;
if (label) {
[yLabels addObject:label];
}
[yMajorLocations addObject:[NSDecimalNumber decimalNumberWithDecimal:location]];
} else {
[yMinorLocations addObject:[NSDecimalNumber decimalNumberWithDecimal:CPTDecimalFromInteger(j)]];
}
}
y.axisLabels = yLabels;
y.majorTickLocations = yMajorLocations;
y.minorTickLocations = yMinorLocations;
}
#pragma mark - Rotation
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft);
}
#pragma mark - CPTPlotDataSource methods
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot {
return [[[CPDStockPriceStore sharedInstance] datesInMonth] count];
}
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index {
NSInteger valueCount = [[[CPDStockPriceStore sharedInstance] datesInMonth] count];
switch (fieldEnum) {
case CPTScatterPlotFieldX:
if (index < valueCount) {
return [NSNumber numberWithUnsignedInteger:index];
}
break;
case CPTScatterPlotFieldY:
if ([plot.identifier isEqual:CPDTickerSymbolAAPL] == YES) {
return [[[CPDStockPriceStore sharedInstance] monthlyPrices:CPDTickerSymbolAAPL] objectAtIndex:index];
} else if ([plot.identifier isEqual:CPDTickerSymbolGOOG] == YES) {
return [[[CPDStockPriceStore sharedInstance] monthlyPrices:CPDTickerSymbolGOOG] objectAtIndex:index];
} else if ([plot.identifier isEqual:CPDTickerSymbolMSFT] == YES) {
return [[[CPDStockPriceStore sharedInstance] monthlyPrices:CPDTickerSymbolMSFT] objectAtIndex:index];
}
break;
}
return [NSDecimalNumber zero];
}
Any help is fine!!!
Just need to get this darn app working correctly :P
Placing one view controller under another requires special handling. Read the "Implementing a Container View Controller" section in the Overview of the UIViewController class docs.
Did you try (??):
ScatterPlotViewController *scatterPlot = [[ScatterPlotViewController alloc] init];
[(yourViewController *) addChildViewController:scatterPlot];
[graphView addSubview:scatterPlot.view];
[scatterPlot didMoveToParentViewController:(yourViewController *)];

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