Search code examples
cocoacore-plotnsarraycontroller

core-plot bar chart bound to a NSArrayController


I'm trying to design a bar graph that will get its data from a NSArrayController which itself is bound to another data source.

What's the correct approach here?

  • My Graph controller is a subclass of NSArrayController
  • In controller's awakeFromNib, I draw the graph and setup the bindings:

-(void)awakeFromNib {

[super awakeFromNib];

// Add plot space for horizontal bar charts
CPTXYPlotSpace *barPlotSpace = [[CPTXYPlotSpace alloc] init];
barPlotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(-20.0f) length:CPTDecimalFromFloat(200.0f)];
barPlotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(-7.0f) length:CPTDecimalFromFloat(15.0f)];
[graph addPlotSpace:barPlotSpace];
//[barPlotSpace release];

// First bar plot
CPTMutableTextStyle *whiteTextStyle = [CPTMutableTextStyle textStyle];
whiteTextStyle.color = [CPTColor whiteColor];
CPTBarPlot *barPlot = [[CPTBarPlot tubularBarPlotWithColor:[CPTColor darkGrayColor] horizontalBars:YES] retain];
barPlot.baseValue = CPTDecimalFromFloat(20.0f);
barPlot.dataSource = self;
barPlot.barOffset = CPTDecimalFromFloat(-0.25f);
barPlot.identifier = barPlot1;
barPlot.plotRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(0.0) length:CPTDecimalFromDouble(7.0)];
barPlot.labelTextStyle = whiteTextStyle;
[graph addPlot:barPlot toPlotSpace:barPlotSpace];

/*
// Second bar plot
barPlot = [CPTBarPlot tubularBarPlotWithColor:[CPTColor blueColor] horizontalBars:YES];
barPlot.dataSource = self;
barPlot.baseValue = CPTDecimalFromFloat(20.0f);
barPlot.barOffset = CPTDecimalFromFloat(0.25f);
barPlot.cornerRadius = 2.0;
barPlot.identifier = barPlot2;
barPlot.plotRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(0.0) length:CPTDecimalFromDouble(7.0)];
barPlot.delegate = self;
[graph addPlot:barPlot toPlotSpace:barPlotSpace];  
 */

[barPlot bind:CPTBarPlotBindingBarLocations
                toObject:self withKeyPath:@"arrangedObjects" options:nil];  }

is this the correct way to do this?

My arrangedObjects is a set of Managed objects that have a name and a time field that I need to graph.

Thanks!


Solution

  • When using bindings, don't set the datasource. Don't forget to bind a field to CPTBarPlotBindingBarTips, too.

    The CPTTestApp example app demonstrates binding a scatter plot to an array controller. The process for a bar plot is same except the binding constants have different names.