PowerPlotPercolation logo

Interactive election chart

This demo shows how to respond when the user selects individual bars in a bar chart.

This page describes the class “ElectionBarsInteractive” in the PowerPlot demo app.

German Federal Elections 2009

We start from the federal election example. Adding response to a single tap is accomplished by the following lines of code:

    // Configure the single tap feature.
    WSPlotController *aCtrl = [self.electionChart plotAtIndex:0];
    aCtrl.tapEnabled = YES;
    aCtrl.delegate = self;
    aCtrl.hitTestMethod = kHitTestX;
    aCtrl.hitResponseMethod = kHitResponseDatum;

The selection of a bar is done by a single tap which is configured by setting the tapEnabled property to YES. The delegate property is set to the calling view controller (i.e. self) which implements the controller:singleTapAtDatum: method to respond to the taps. This method is called with the datum that the user has actually tapped, the behavior for the callback is selected by setting hitResponseMethod to kHitResponseDatum.

For deciding which datum the user tapped on the hitTestMethod property is set to kHitTestX, i.e., only the X-value will be used. If we had chosen kHitTestX&kHitTestY then we would get the bar whose top border is closest to the tap. This would be what we want in a regular data plot, see interactive scientific data example. But it would be inappropriate for a bar plot, where we actually want the bar closest to the tap.

Finally, the callback method with the datum is implemented:

- (void)controller:(WSPlotController *)controller
  singleTapAtDatum:(NSInteger)i {
    WSDatum *target = [self.barData datumAtIndex:i];
    self.resultLabel.text = [NSString stringWithFormat:@"%@: %2.0f%%",
                             target.annotation,
                             target.value];
}

We could optionally define a method singleTapRange in our view controller to specify the maximum distance from a data point which is still identified as a “hit”. If this function is not present – as in this example code – then the maximum distance is infinite, i.e., the controller will always be called with the closest data point available.