2011-05-15 71 views
0

我想知道如何創建分組條形圖?我試過了,但我只有一個條形圖。使用核心圖iphone的分組條形圖示例?

下面是我的代碼任何一個告訴我什麼是錯誤。

謝謝

-(void)viewDidLoad { 

    [super viewDidLoad]; 

[self generateDataSamples]; 

double xAxisStart = 0; 
double xAxisLength = [samples count]; 

double yAxisStart = 0; 
double yAxisLength = [[samples valueForKeyPath:@"@max.Y_VAL"] doubleValue]; 




    NSLog(@"xAxisLength===%f",xAxisLength); 

    NSLog(@"yAxisLength===%f",yAxisLength); 


CPGraphHostingView *hostingView = [[CPGraphHostingView alloc] initWithFrame:self.view.bounds]; 
[self.view addSubview:hostingView]; 

CPXYGraph *graph = [[CPXYGraph alloc] initWithFrame:self.view.bounds]; 
hostingView.hostedGraph = graph; 


CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)graph.defaultPlotSpace; 
plotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(xAxisStart) 
               length:CPDecimalFromDouble(xAxisLength+1)]; 

plotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(yAxisStart) 
               length:CPDecimalFromDouble(yAxisLength)];  


graph.plotAreaFrame.borderLineStyle = nil; 
graph.plotAreaFrame.cornerRadius = 0.0f; 

// Paddings 
graph.paddingLeft = 0.0f; 
graph.paddingRight = 0.0f; 
graph.paddingTop = 0.0f; 
graph.paddingBottom = 0.0f; 

graph.plotAreaFrame.paddingLeft = 70.0; 
graph.plotAreaFrame.paddingTop = 20.0; 
graph.plotAreaFrame.paddingRight = 20.0; 
graph.plotAreaFrame.paddingBottom = 80.0; 




CPXYAxisSet *axisSet = (CPXYAxisSet *)graph.axisSet; 

CPXYAxis *y = axisSet.yAxis; 

    y.majorIntervalLength = CPDecimalFromString(@"1"); 
    y.orthogonalCoordinateDecimal = CPDecimalFromString(@"0"); 
y.title = @"Y Axis"; 
y.titleOffset = 45.0f; 
    y.titleLocation = CPDecimalFromFloat(3.0f); 



//first bar 
CPBarPlot *plot = [[CPBarPlot alloc] initWithFrame:CGRectZero]; 
plot.plotRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(0.0) 
              length:CPDecimalFromDouble(xAxisLength)]; 

CPFill* cpFill = [[CPFill alloc] initWithColor:[CPColor greenColor]]; 
    plot.barOffset = CPDecimalFromFloat(0.25f); 
plot.fill = cpFill; 
plot.dataSource = self; 
[email protected]"plot1"; 
[graph addPlot:plot toPlotSpace:plotSpace]; 

//second bar 

plot.plotRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(1.0) 
              length:CPDecimalFromDouble(xAxisLength)]; 

CPFill* cpFill1 = [[CPFill alloc] initWithColor:[CPColor lightGrayColor]]; 
plot.fill = cpFill1; 
plot.dataSource = self; 
[email protected]"plot2"; 
[graph addPlot:plot toPlotSpace:plotSpace]; 


[graph addPlot:plot]; 
[plot release]; 
[graph release]; 
[hostingView release]; 
} 

回答

1

你永遠不會創建第二個劇情對象 - 你的代碼只是增加了一個相同的圖形兩次。您還需要確保爲第二個繪圖使用不同的barOffset。如果你沒有使用垃圾收集,請留意你的內存管理。您的問題中的代碼有幾個內存泄漏。

+0

我需要做什麼來添加第二個陰謀......你可以解釋給與示例代碼。 – user601367 2011-05-15 17:30:08

+0

您可以使用'plot = [[CPBarPlot alloc] initWithFrame:CGRectZero];'在將第一個圖添加到圖之後。你已經擁有了你需要的一切。如果你沒有使用垃圾回收,記得在你將一個新對象賦給'plot'變量之前釋放(或者自動釋放)第一個對象。 – 2011-05-16 10:54:20