I have the following code below to display two Y axes (one on the right and one on the left). I would like to be able to plot to each graph per a different data set (mapping to the same X value). I can't seem to get two CPTXYPlotSpaces to display at the same time. How would I go about this so I can plot to two different Plot Spaces and see the graphed lines at the same time.
-(void)configureHost
{
CGRect bounds = self.view.bounds;
bounds.size.height = bounds.size.height;
self.hostView = [[CPTGraphHostingView alloc] initWithFrame:bounds];
self.hostView.allowPinchScaling = YES;
[self.view addSubview:self.hostView];
}
-(void)configureGraph
{
self.graph = [[CPTXYGraph alloc] initWithFrame:self.hostView.bounds];
[self.graph applyTheme:[CPTTheme themeNamed:kCPTPlainWhiteTheme]];
self.hostView.hostedGraph = self.graph;
self.graph.paddingLeft = 20.0;
self.graph.paddingTop = 20.0;
self.graph.paddingRight = 20.0;
self.graph.paddingBottom = 20.0;
}
NSString *const kPlot1 = #"Plot 1";
NSString *const kPlot2 = #"Plot 2";
-(void)configurePlots
{
CGRect bounds = self.hostView.bounds;
self.plotSpace1 = (CPTXYPlotSpace *) self.graph.defaultPlotSpace;
self.plotSpace1.allowsUserInteraction = NO;
self.scatterPlot1 = [[CPTScatterPlot alloc]init];
self.scatterPlot1.identifier = kPlot1;
self.scatterPlot1.dataSource = self;
[self.graph addPlot:self.scatterPlot1 toPlotSpace:self.plotSpace1];
self.scatterPlot2 = [[CPTScatterPlot alloc]init];
self.scatterPlot2.identifier = kPlot2;
self.scatterPlot2.dataSource =self;
[self.graph addPlot:self.scatterPlot2 toPlotSpace:self.plotSpace2];
[self.plotSpace1 scaleToFitPlots:#[self.scatterPlot1, self.scatterPlot2]];
[self.plotSpace2 scaleToFitPlots:#[self.scatterPlot1, self.scatterPlot2]];
CPTGraph *graph = self.hostView.hostedGraph;
graph.plotAreaFrame.fill = [CPTFill fillWithColor:[CPTColor whiteColor]];
[self setTitleDefaultsForGraph:graph withBounds:bounds];
[self setPaddingDefaultsForGraph:graph withBounds:bounds];
graph.plotAreaFrame.paddingTop = 20.0;
graph.plotAreaFrame.paddingBottom = 50.0;
graph.plotAreaFrame.paddingLeft = 50.0;
graph.plotAreaFrame.paddingRight = 50.0;
graph.plotAreaFrame.cornerRadius = 10.0;
graph.plotAreaFrame.masksToBorder = NO;
graph.plotAreaFrame.axisSet.borderLineStyle = [CPTLineStyle lineStyle];
// Setup plot space
self.plotSpace1.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(0.0) length:CPTDecimalFromDouble(10.0)];
self.plotSpace1.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(0.0) length:CPTDecimalFromDouble(10.0)];
self.plotSpace2 = [[CPTXYPlotSpace alloc] init];
self.plotSpace2.xRange = self.plotSpace1.xRange;
self.plotSpace2.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(0.0) length:CPTDecimalFromDouble(10.0)];
[graph addPlotSpace:self.plotSpace2];
}
-(void)setPaddingDefaultsForGraph:(CPTGraph *)graph withBounds:(CGRect)bounds
{
// CGFloat boundsPadding = round( bounds.size.width / CPTFloat(20.0) ); // Ensure that padding falls on an integral pixel
//
// graph.paddingLeft = boundsPadding;
//
// if ( graph.titleDisplacement.y > 0.0 ) {
// graph.paddingTop = graph.titleTextStyle.fontSize * 2.0;
// }
// else {
// graph.paddingTop = boundsPadding;
// }
//
// graph.paddingRight = boundsPadding;
// graph.paddingBottom = boundsPadding;
graph.paddingTop = 0.0f;
graph.paddingBottom = 0.0f;
graph.paddingLeft = 0.0f;
graph.paddingRight = 0.0f;
}
-(void)setTitleDefaultsForGraph:(CPTGraph *)graph withBounds:(CGRect)bounds
{
graph.title = self.title;
CPTMutableTextStyle *textStyle = [CPTMutableTextStyle textStyle];
textStyle.color = [CPTColor grayColor];
textStyle.fontName = #"Helvetica-Bold";
textStyle.fontSize = round( bounds.size.height / CPTFloat(20.0) );
graph.titleTextStyle = textStyle;
graph.titleDisplacement = CPTPointMake( 0.0, textStyle.fontSize * CPTFloat(1.5) );
graph.titlePlotAreaFrameAnchor = CPTRectAnchorTop;
}
-(void)configureAxis
{
CPTGraph *graph = self.hostView.hostedGraph;
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)graph.axisSet;
// Line styles
CPTMutableLineStyle *axisLineStyle = [CPTMutableLineStyle lineStyle];
axisLineStyle.lineWidth = 3.0;
axisLineStyle.lineCap = kCGLineCapRound;
// Text styles
CPTMutableTextStyle *axisTitleTextStyle = [CPTMutableTextStyle textStyle];
axisTitleTextStyle.fontName = #"Helvetica-Bold";
axisTitleTextStyle.fontSize = 14.0;
CPTXYAxis *x = axisSet.xAxis;
x.orthogonalCoordinateDecimal = CPTDecimalFromDouble(0.0);//Where the Y Axis meets the X axis
x.majorIntervalLength = CPTDecimalFromDouble(1.5);//Interval for X Axis
x.minorTicksPerInterval = 4;
x.tickDirection = CPTSignNone;
x.axisLineStyle = axisLineStyle;
x.majorTickLength = 12.0;
x.majorTickLineStyle = axisLineStyle;
x.minorTickLength = 8.0;
x.title = #"X Axis";
x.titleTextStyle = axisTitleTextStyle;
x.titleOffset = 25.0;
x.axisConstraints = [CPTConstraints constraintWithLowerOffset:0.0];
// Label y with an automatic labeling policy.
axisLineStyle.lineColor = [CPTColor greenColor];
CPTXYAxis *y = axisSet.yAxis;
y.labelingPolicy = CPTAxisLabelingPolicyAutomatic;
y.minorTicksPerInterval = 9;
y.tickDirection = CPTSignNegative;
y.axisLineStyle = axisLineStyle;
y.majorTickLength = 6.0;
y.majorTickLineStyle = axisLineStyle;
y.minorTickLength = 4.0;
y.title = #"Y Axis";
y.titleTextStyle = axisTitleTextStyle;
y.titleOffset = 30.0;
// Label y2 with an equal division labeling policy.
axisLineStyle.lineColor = [CPTColor orangeColor];
CPTXYAxis *y2 = [[CPTXYAxis alloc] init];
y2.coordinate = CPTCoordinateY;
y2.plotSpace = self.plotSpace2;
y2.orthogonalCoordinateDecimal = CPTDecimalFromDouble(10.0);//Where the Y Axis meets the X axis
y2.labelingPolicy = CPTAxisLabelingPolicyEqualDivisions;
y2.preferredNumberOfMajorTicks = 6;
y2.minorTicksPerInterval = 9;
y2.tickDirection = CPTSignPositive;
y2.axisLineStyle = axisLineStyle;
y2.majorTickLength = 6.0;
y2.majorTickLineStyle = axisLineStyle;
y2.minorTickLength = 4.0;
y2.title= #"Y2 Axis";
y2.titleTextStyle = axisTitleTextStyle;
y2.titleOffset = 30.0;
// Add the y2 axis to the axis set
graph.axisSet.axes = #[x, y, y2];
}
#pragma mark CPTPlotDataSource
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{
if ( [(NSString *)plot.identifier isEqualToString:kPlot1] ) {
return 10;
}
else if ( [(NSString *)plot.identifier isEqualToString:kPlot2] ) {
return 5;
} else {
return 0;
}
}
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)idx
{
switch (fieldEnum) {
case CPTScatterPlotFieldX:
if ([plot.identifier isEqual:kPlot1]) {
return [NSNumber numberWithUnsignedInt:idx];
break;
}else if ([plot.identifier isEqual:kPlot2]){
return [NSNumber numberWithUnsignedInt:idx];
break;
}
case CPTScatterPlotFieldY:
if ([plot.identifier isEqual:kPlot1]) {
return #(idx *2);
} else if ([plot.identifier isEqual:kPlot2]) {
return #(idx +2);
}
}
return 0;
}
You're (re-)initializing plotSpace2 after you scale it. Move the call to [self.plotSpace2 scaleToFitPlots:...] after setting up the plot space.
Related
I'm trying to plot a histogram. The x-axis range should be about 881 to 1281 (I've verified that I'm using a location of 881 and range of 400 when constructing the CPTPlotRange for xRange). The axis draws with the correct range, but my bars end up near 2000 (data space), even though my data source method is sending location values between 881 and 1281.
Here's the code:
- (void)
viewDidLoad
{
[super viewDidLoad];
InputVariable temp(1081.0, 50.0);
self.hist = new Histogram(temp.mean(), temp.stdDev(), 5.0);
for (Histogram::SizeT i = 0; i < 1000; ++i)
{
double v = temp.randomValue();
self.hist->add(v);
}
const Histogram& hist = *self.hist;
CPTXYGraph* graph = [[CPTXYGraph alloc] initWithFrame: self.chart1.bounds];
graph.fill = [CPTFill fillWithColor: [CPTColor lightGrayColor]];
graph.cornerRadius = 4.0;
self.chart1.hostedGraph = graph;
self.graph = graph;
// Plot area
graph.plotAreaFrame.fill = [CPTFill fillWithColor:[CPTColor lightGrayColor]];
graph.plotAreaFrame.paddingTop = 4.0;
graph.plotAreaFrame.paddingBottom = 50.0;
graph.plotAreaFrame.paddingLeft = 50.0;
graph.plotAreaFrame.paddingRight = 4.0;
graph.plotAreaFrame.cornerRadius = 4.0;
graph.plotAreaFrame.masksToBorder = NO;
graph.plotAreaFrame.axisSet.borderLineStyle = [CPTLineStyle lineStyle];
graph.plotAreaFrame.plotArea.fill = [CPTFill fillWithColor:[CPTColor whiteColor]];
// Setup plot space
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)graph.defaultPlotSpace;
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(hist.lowValue()) length:CPTDecimalFromDouble(hist.range())];
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(0.0) length:CPTDecimalFromDouble(hist.maxBinCount() * 1.2)];
//plotSpace.yScaleType = CPTScaleTypeLog;
// Line styles
CPTMutableLineStyle *axisLineStyle = [CPTMutableLineStyle lineStyle];
axisLineStyle.lineWidth = 2.0;
//axisLineStyle.lineCap = kCGLineCapRound;
CPTMutableLineStyle *majorGridLineStyle = [CPTMutableLineStyle lineStyle];
majorGridLineStyle.lineWidth = 0.75;
majorGridLineStyle.lineColor = [CPTColor redColor];
CPTMutableLineStyle *minorGridLineStyle = [CPTMutableLineStyle lineStyle];
minorGridLineStyle.lineWidth = 0.25;
minorGridLineStyle.lineColor = [CPTColor blueColor];
// Text styles
CPTMutableTextStyle *axisTitleTextStyle = [CPTMutableTextStyle textStyle];
axisTitleTextStyle.fontName = #"Helvetica Neue Bold";
axisTitleTextStyle.fontSize = 14.0;
// Axes
// Label x axis with a fixed interval policy
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)graph.axisSet;
CPTXYAxis *x = axisSet.xAxis;
x.separateLayers = NO;
x.orthogonalCoordinateDecimal = CPTDecimalFromDouble(0.0);
x.majorIntervalLength = CPTDecimalFromDouble(0.5);
x.minorTicksPerInterval = 4;
x.tickDirection = CPTSignNone;
x.axisLineStyle = axisLineStyle;
x.majorTickLength = 12.0;
x.majorTickLineStyle = axisLineStyle;
//x.majorGridLineStyle = majorGridLineStyle;
x.minorTickLength = 8.0;
//x.minorGridLineStyle = minorGridLineStyle;
x.title = #"Temperature";
x.titleTextStyle = axisTitleTextStyle;
x.titleOffset = 25.0;
//x.alternatingBandFills = #[[[CPTColor redColor] colorWithAlphaComponent:0.1], [[CPTColor greenColor] colorWithAlphaComponent:0.1]];
x.labelingPolicy = CPTAxisLabelingPolicyAutomatic;
// Label y with an automatic label policy.
//axisLineStyle.lineColor = [CPTColor greenColor];
CPTXYAxis *y = axisSet.yAxis;
y.separateLayers = YES;
y.orthogonalCoordinateDecimal = plotSpace.xRange.location;//CPTDecimalFromDouble(hist.lowValue());
y.minorTicksPerInterval = 9;
y.tickDirection = CPTSignNone;
y.axisLineStyle = axisLineStyle;
y.majorTickLength = 12.0;
y.majorTickLineStyle = axisLineStyle;
//y.majorGridLineStyle = majorGridLineStyle;
//y.minorTickLength = 8.0;
//y.minorGridLineStyle = minorGridLineStyle;
y.title = #"Number of Samples";
y.titleTextStyle = axisTitleTextStyle;
y.titleOffset = 40.0;
//y.alternatingBandFills = #[[[CPTColor blueColor] colorWithAlphaComponent:0.1], [NSNull null]];
y.labelingPolicy = CPTAxisLabelingPolicyAutomatic;
//CPTFill *bandFill = [CPTFill fillWithColor:[[CPTColor darkGrayColor] colorWithAlphaComponent:0.5]];
//[y addBackgroundLimitBand:[CPTLimitBand limitBandWithRange:[CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(7.0) length:CPTDecimalFromDouble(1.5)] fill:bandFill]];
//[y addBackgroundLimitBand:[CPTLimitBand limitBandWithRange:[CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(1.5) length:CPTDecimalFromDouble(3.0)] fill:bandFill]];
// Set up the bar plot…
//CPTXYPlotSpace *barPlotSpace = [[CPTXYPlotSpace alloc] init];
CPTXYPlotSpace *barPlotSpace = (CPTXYPlotSpace *) self.graph.defaultPlotSpace;
//barPlotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(0.0) length:CPTDecimalFromDouble(200.0)];
//barPlotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(0.0) length:CPTDecimalFromDouble(15.00)];
//[self.graph addPlotSpace:barPlotSpace];
CPTBarPlot *barPlot = [CPTBarPlot tubularBarPlotWithColor:[CPTColor darkGrayColor] horizontalBars: false];
barPlot.dataSource = self;
barPlot.barsAreHorizontal = false;
barPlot.barWidth = CPTDecimalFromDouble(1.0);
barPlot.barBasesVary = false;
barPlot.baseValue = CPTDecimalFromDouble(0.0);
barPlot.barOffset = CPTDecimalFromDouble(hist.lowValue());
barPlot.identifier = #"Bar Plot";
//barPlot.plotRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(0.0) length:CPTDecimalFromDouble(7.0)];
CPTMutableTextStyle *whiteTextStyle = [CPTMutableTextStyle textStyle];
whiteTextStyle.color = [CPTColor whiteColor];
//barPlot.labelTextStyle = whiteTextStyle;
[self.graph addPlot:barPlot toPlotSpace:barPlotSpace];
}
- (NSUInteger)
numberOfRecordsForPlot: (CPTPlot*) inPlot
{
return self.hist->numBins();
}
- (double)
doubleForPlot: (CPTPlot*) inPlot
field: (NSUInteger) inField
recordIndex: (NSUInteger) inIdx
{
const Histogram& h = *self.hist;
if (inField == CPTBarPlotFieldBarLocation)
{
double v = h.binMid(inIdx);
NSLog(#"v: %f", v);
return v;
}
else if (inField == CPTBarPlotFieldBarTip)
{
return h[inIdx];
}
return 0.0;
}
And the resulting graph:
Any idea what I'm doing wrong? Thanks!
For this application, the barOffset should be zero (0). The offset is used to displace the bars from the location given by the datasource. The most common use is to separate the bars at the same location when plotting multiple bar plots on the same graph that might have overlapping bars at common locations.
I created a core plot graph, have one x-axis, two y-axis, now, I want to have two lines and first use the first y-axis, second use the second y-axis, but it doesn't work. Who can guide me?
- (void)viewDidLoad
{
[super viewDidLoad];
graph = [[CPTXYGraph alloc] initWithFrame:CGRectMake(10, 100, 300, 300)];
// graph.backgroundColor = [CPTColor clearColor].cgColor;
CPTTheme * theme = [CPTTheme themeNamed:kCPTPlainWhiteTheme];
[graph applyTheme:theme];
CPTGraphHostingView * hostingView = [[CPTGraphHostingView alloc] initWithFrame:CGRectMake(10, 100, 300, 300)];
hostingView.hostedGraph = graph;
[self.view addSubview:hostingView];
[hostingView release];
graph.fill = [CPTFill fillWithColor:[CPTColor clearColor]];
// Plot area
// graph.plotAreaFrame.fill = [CPTFill fillWithColor:[CPTColor clearColor]];
graph.plotAreaFrame.paddingTop = 10;
graph.plotAreaFrame.paddingBottom = 50;
graph.plotAreaFrame.paddingLeft = 20.0;
graph.plotAreaFrame.paddingRight = 20.0;
graph.plotAreaFrame.cornerRadius = 10.0;
graph.plotAreaFrame.masksToBorder = NO;
// graph.plotAreaFrame.axisSet.borderLineStyle = [CPTLineStyle lineStyle];
graph.plotAreaFrame.plotArea.fill = [CPTFill fillWithColor:[CPTColor clearColor]];
// Setup plot space
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)graph.defaultPlotSpace;
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(1) length:CPTDecimalFromDouble(7)];
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(53.0) length:CPTDecimalFromDouble(4)];
// Line styles
CPTMutableLineStyle *axisLineStyle = [CPTMutableLineStyle lineStyle];
axisLineStyle.lineWidth = 3.0;
axisLineStyle.lineCap = kCGLineCapRound;
// Label x axis with a fixed interval policy
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)graph.axisSet;
CPTXYAxis *x = axisSet.xAxis;
x.separateLayers = YES;//
x.orthogonalCoordinateDecimal = CPTDecimalFromDouble(53);
x.majorIntervalLength = CPTDecimalFromDouble(1);
x.minorTicksPerInterval = 1;
x.tickDirection = CPTSignNegative;
x.axisLineStyle = axisLineStyle;
x.majorTickLength = 2.0;
x.majorTickLineStyle = axisLineStyle;
// Label y with an automatic labeling policy.
axisLineStyle.lineColor = [CPTColor greenColor];
CPTXYAxis *y = axisSet.yAxis;
y.labelingPolicy = CPTAxisLabelingPolicyAutomatic;
y.separateLayers = YES;//
y.minorTicksPerInterval = 0;
y.tickDirection = CPTSignNegative;
y.orthogonalCoordinateDecimal = CPTDecimalFromDouble(1.0);
y.axisLineStyle = axisLineStyle;
y.majorTickLength = 6.0;
y.majorTickLineStyle = axisLineStyle;
// Label y2 with an equal division labeling policy.
axisLineStyle.lineColor = [CPTColor orangeColor];
CPTXYPlotSpace * plotSpace2 = [[CPTXYPlotSpace alloc] init];
plotSpace2.xRange = plotSpace.xRange;
plotSpace2.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(1) length:CPTDecimalFromFloat(5)];
[graph addPlotSpace:plotSpace2];
CPTXYAxis *y2 = [[[CPTXYAxis alloc] init] autorelease];
y2.coordinate = CPTCoordinateY;
y2.plotSpace = plotSpace2;
y2.orthogonalCoordinateDecimal = CPTDecimalFromDouble(8.0);
y2.labelingPolicy = CPTAxisLabelingPolicyAutomatic;//
y2.separateLayers = NO;
y2.preferredNumberOfMajorTicks = 0;
y2.minorTicksPerInterval = 0;
y2.tickDirection = CPTSignPositive;
y2.axisLineStyle = axisLineStyle;
y2.majorTickLength = 6.0;
y2.majorTickLineStyle = axisLineStyle;
y2.minorTickLength = 4.0;
y2.titleOffset = 30.0;
//
CPTMutableLineStyle * lineStyle1 = [[CPTMutableLineStyle lineStyle] retain];
lineStyle1.lineWidth = 3.0f;
lineStyle1.lineColor = [CPTColor blueColor];
dataSourceLinePlot1 = [[CPTScatterPlot alloc] init];
dataSourceLinePlot1.identifier = #"1plot";
CPTPlotSymbol *plotSymbol1 = [CPTPlotSymbol ellipsePlotSymbol];
plotSymbol1.size = CGSizeMake(10, 10);
plotSymbol1.fill = [CPTFill fillWithColor:[CPTColor redColor]];
plotSymbol1.lineStyle = lineStyle1;
CPTMutableShadow *shadow1 = [CPTMutableShadow shadow];
shadow1.shadowColor = [CPTColor blueColor];
shadow1.shadowBlurRadius = 10.0;
dataSourceLinePlot1.shadow = shadow1;
dataSourceLinePlot1.plotSymbol = plotSymbol1;
dataSourceLinePlot1.dataLineStyle = lineStyle1;
dataSourceLinePlot1.dataSource = self;
[graph addPlot:dataSourceLinePlot1];
//-----------------------------------
CPTMutableLineStyle * lineStyle2 = [[CPTMutableLineStyle lineStyle] retain];
lineStyle2.lineWidth = 3.0f;
lineStyle2.lineColor = [CPTColor greenColor];
dataSourceLinePlot2 = [[CPTScatterPlot alloc] init];
dataSourceLinePlot2.identifier = #"2plot";
CPTPlotSymbol * plotSymbol2 = [CPTPlotSymbol ellipsePlotSymbol];
plotSymbol2.size = CGSizeMake(10, 10);
plotSymbol2.fill = [CPTFill fillWithColor:[CPTColor redColor]];
plotSymbol2.lineStyle = lineStyle2;
CPTMutableShadow *shadow2 = [CPTMutableShadow shadow];
shadow2.shadowColor = [CPTColor greenColor];
shadow2.shadowBlurRadius = 10.0;
dataSourceLinePlot2.shadow = shadow2;
dataSourceLinePlot2.plotSymbol = plotSymbol2;
dataSourceLinePlot2.dataLineStyle = lineStyle2;
dataSourceLinePlot2.dataSource = self;
[graph addPlot:dataSourceLinePlot2];
// Add the y2 axis to the axis set
graph.axisSet.axes = [NSArray arrayWithObjects:x, y, y2, nil];
dataArray1 = [[NSMutableArray alloc] init];
dataArray2 = [[NSMutableArray alloc] init];
for(int i=0; i< 7; i++){
float a = (float)(random()%40 + 530) / 10;
[dataArray1 addObject:[NSNumber numberWithFloat:a]];
}
for (int i = 0; i < 7; i++) {
// float a = (float)(random()%40 + 530) / 10;
[dataArray2 addObject:[NSNumber numberWithFloat:4]];
}
NSLog(#"array1 = %#,array2 = %#",dataArray1,dataArray2);
}
there is my delegate:
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{
NSLog(#"%d",[dataArray1 count]);
if ([[plot identifier] isEqual:#"1plot"]) {
return [dataArray1 count];
}
return [dataArray2 count];
}
- (NSNumber *) numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index {
if(fieldEnum == CPTScatterPlotFieldY){
if ([[plot identifier] isEqual:#"1plot"]) {
return [dataArray1 objectAtIndex:index];
}else{
return [dataArray2 objectAtIndex:index];
}
}else{
return [NSNumber numberWithFloat:index];
}
}
You are setting the datasource delegate to self before the arrays have any data put into them. You need to either initialize the array earlier or call [graph reloadData];
Based on the example RealTime presented in the library Core Plot, I tried to reimplement it on my project.
I am able to update y axis, add a symbol, draw label, etc. But I'm totally unable to draw the line.
CPTMutableLineStyle object seems to be correctly instantied and correctly setted to the CPTGraph object but is not rendered in the graph
Here is how I add line style to my graph
CPTMutableLineStyle *lineStyle = [CPTMutableLineStyle lineStyle]; // [dataSourceLinePlot.dataLineStyle mutableCopy];
lineStyle.lineWidth = 3.0;
lineStyle.lineColor = [CPTColor greenColor];
dataSourceLinePlot.dataLineStyle = lineStyle;
And here is the full class code
#import "TUTSimpleScatterPlot.h"
const double kFrameRate = 5.0; // frames per second
const double kAlpha = 0.15; // smoothing constant
const NSUInteger kMaxDataPoints = 21;
NSString *kPlotIdentifier = #"Data Source Plot";
#implementation TUTSimpleScatterPlot
// Initialise the scatter plot in the provided hosting view with the provided data.
// The data array should contain NSValue objects each representing a CGPoint.
-(id)initWithHostingView:(CPTGraphHostingView *)hostingView andData:(NSMutableArray *)data
{
self = [super init];
if ( self != nil ) {
self.hostingView = hostingView;
self.graphData = data;
self.graph = nil;
}
return self;
}
-(void)initialisePlot
{
self.graphData = [NSMutableArray array];
CGRect bounds = self.hostingView.bounds;
CPTGraph *graph = [[CPTXYGraph alloc] initWithFrame:bounds] ;
[self.hostingView setHostedGraph:graph];
graph.title = #"Measure";
CPTMutableTextStyle *textStyle = [CPTMutableTextStyle textStyle];
textStyle.color = [CPTColor grayColor];
textStyle.fontName = #"Helvetica-Bold";
textStyle.fontSize = round(bounds.size.height / (CGFloat)20.0);
graph.titleTextStyle = textStyle;
graph.titleDisplacement = CGPointMake( 0.0f, round(bounds.size.height / (CGFloat)18.0) ); // Ensure that title displacement falls on an integral pixel
graph.titlePlotAreaFrameAnchor = CPTRectAnchorTop;
CGFloat boundsPadding = round(bounds.size.width / (CGFloat)20.0); // Ensure that padding falls on an integral pixel
graph.paddingLeft = boundsPadding;
if ( graph.titleDisplacement.y > 0.0 ) {
graph.paddingTop = graph.titleDisplacement.y * 2;
}
else {
graph.paddingTop = boundsPadding;
}
graph.paddingRight = boundsPadding;
graph.paddingBottom = boundsPadding;
graph.plotAreaFrame.paddingTop = 15.0;
graph.plotAreaFrame.paddingRight = 15.0;
graph.plotAreaFrame.paddingBottom = 55.0;
graph.plotAreaFrame.paddingLeft = 55.0;
// Grid line styles
CPTMutableLineStyle *majorGridLineStyle = [CPTMutableLineStyle lineStyle];
majorGridLineStyle.lineWidth = 0.75;
majorGridLineStyle.lineColor = [[CPTColor colorWithGenericGray:0.2] colorWithAlphaComponent:0.75];
CPTMutableLineStyle *minorGridLineStyle = [CPTMutableLineStyle lineStyle];
minorGridLineStyle.lineWidth = 0.25;
minorGridLineStyle.lineColor = [[CPTColor whiteColor] colorWithAlphaComponent:0.1];
// Axes
// X axis
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)graph.axisSet;
CPTXYAxis *x = axisSet.xAxis;
x.labelingPolicy = CPTAxisLabelingPolicyAutomatic;
x.orthogonalCoordinateDecimal = CPTDecimalFromUnsignedInteger(0);
x.majorGridLineStyle = majorGridLineStyle;
x.minorGridLineStyle = minorGridLineStyle;
x.minorTicksPerInterval = 9;
x.title = #"X Axis";
x.titleOffset = 35.0;
NSNumberFormatter *labelFormatter = [[NSNumberFormatter alloc] init];
labelFormatter.numberStyle = NSNumberFormatterNoStyle;
x.labelFormatter = labelFormatter;
// Y axis
CPTXYAxis *y = axisSet.yAxis;
y.labelingPolicy = CPTAxisLabelingPolicyAutomatic;
y.orthogonalCoordinateDecimal = CPTDecimalFromUnsignedInteger(0);
y.majorGridLineStyle = majorGridLineStyle;
y.minorGridLineStyle = minorGridLineStyle;
y.minorTicksPerInterval = 3;
y.labelOffset = 5.0;
y.title = #"Y Axis";
y.titleOffset = 30.0;
y.axisConstraints = [CPTConstraints constraintWithLowerOffset:0.0];
// Rotate the labels by 45 degrees, just to show it can be done.
x.labelRotation = M_PI * 0.25;
// Create the plot
CPTScatterPlot *dataSourceLinePlot = [[CPTScatterPlot alloc] init];
dataSourceLinePlot.identifier = kPlotIdentifier;
dataSourceLinePlot.cachePrecision = CPTPlotCachePrecisionDouble;
// dataSourceLinePlot.interpolation = CPTScatterPlotInterpolationCurved;
CPTMutableLineStyle *lineStyle = [CPTMutableLineStyle lineStyle]; // [dataSourceLinePlot.dataLineStyle mutableCopy];
lineStyle.lineWidth = 3.0;
lineStyle.lineColor = [CPTColor greenColor];
dataSourceLinePlot.dataLineStyle = lineStyle;
CPTMutableLineStyle *symbolLineStyle = [CPTMutableLineStyle lineStyle];
symbolLineStyle.lineColor = [[CPTColor blackColor] colorWithAlphaComponent:0.5];
CPTPlotSymbol *plotSymbol = [CPTPlotSymbol ellipsePlotSymbol];
plotSymbol.fill = [CPTFill fillWithColor:[[CPTColor blueColor] colorWithAlphaComponent:0.5]];
plotSymbol.lineStyle = symbolLineStyle;
plotSymbol.size = CGSizeMake(10.0, 10.0);
dataSourceLinePlot.plotSymbol = plotSymbol;
dataSourceLinePlot.dataSource = self;
[graph addPlot:dataSourceLinePlot];
// Plot space
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)graph.defaultPlotSpace;
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromUnsignedInteger(0) length:CPTDecimalFromUnsignedInteger(kMaxDataPoints - 1)];
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromUnsignedInteger(0) length:CPTDecimalFromUnsignedInteger(1)];
self.graph = graph;
self.dataTimer = [NSTimer timerWithTimeInterval:1.0 / kFrameRate
target:self
selector:#selector(newData:)
userInfo:nil
repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:self.dataTimer forMode:NSDefaultRunLoopMode];
}
#pragma mark -
#pragma mark Timer callback
-(void)newData:(NSTimer *)theTimer
{
CPTGraph *theGraph = self.graph;
CPTPlot *thePlot = [theGraph plotWithIdentifier:kPlotIdentifier];
if ( thePlot ) {
// if ( self.graphData.count >= kMaxDataPoints - 5 ) {
// [self.graphData removeObjectAtIndex:0];
// [thePlot deleteDataInIndexRange:NSMakeRange(0, 1)];
// }
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)theGraph.defaultPlotSpace;
NSUInteger location = (_currentIndex >= kMaxDataPoints ? _currentIndex - kMaxDataPoints + 5 : 0);
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromUnsignedInteger(location)
length:CPTDecimalFromUnsignedInteger(kMaxDataPoints - 1)];
_currentIndex++;
NSNumber * num;
if (_currentIndex == 1) {
num = [NSNumber numberWithDouble: 5 + (arc4random() % 15) ];
} else {
NSLog(#"lastVal: %d", [[self.graphData lastObject] intValue]);
float low_bound = (1 - kAlpha) * [[self.graphData lastObject] floatValue];
float high_bound = (1.01 + kAlpha) * [[self.graphData lastObject] floatValue];
float random = (((float)arc4random()/0x100000000)*(high_bound-low_bound)+low_bound);
NSLog(#"random: %f", random);
num = [NSNumber numberWithDouble:random];
}
// Update y range if necessary
if (_currentIndex < kMaxDataPoints) {
int maxValue = -1;
for (int i = self.graphData.count -1 ; (i >= 0); i--) {
if ([[self.graphData objectAtIndex:i] intValue] > maxValue) {
maxValue = [[self.graphData objectAtIndex:i] intValue];
}
}
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromUnsignedInteger(0) length:CPTDecimalFromUnsignedInteger(maxValue + 1)];
} else if (_currentIndex >= kMaxDataPoints) {
int maxValue = -1;
for (int i = self.graphData.count -1 ; (i >= self.graphData.count - kMaxDataPoints + 2); i--) {
if ([[self.graphData objectAtIndex:i] intValue] > maxValue) {
maxValue = [[self.graphData objectAtIndex:i] intValue];
}
}
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromUnsignedInteger(0) length:CPTDecimalFromUnsignedInteger(maxValue + 1)];
}
[self.graphData addObject:num];
[thePlot insertDataAtIndex:self.graphData.count - 1 numberOfRecords:1];
}
}
#pragma mark -
#pragma mark Plot Data Source Methods
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{
return [self.graphData count];
}
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
NSNumber *num = nil;
switch ( fieldEnum ) {
case CPTScatterPlotFieldX:
num = [NSNumber numberWithUnsignedInteger:index + _currentIndex - self.graphData.count];
break;
case CPTScatterPlotFieldY:
num = [self.graphData objectAtIndex:index];
break;
default:
break;
}
return num;
}
#end
Any ideas ? Tips ? Hack ?
UPDATE 1
In my project I used the 1.2 version of the library. I tried to regress to 1.0 version and lines are now displayed. Any ideas on how to convert my project to work with the last version ?
UPDATE 2*
Changing the Podfile from pod 'CorePlot' to pod 'CorePlot', '~> 1.2' seems to be different. My line is now correctly drawn...
Seems there is difference by using cocoapods by this way
pod 'CorePlot'
or by this way
pod 'CorePlot', '~> 1.2'
Then reinstalling the libaries by executing pod install
Now the project is able to draw line
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.
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;
}