Pivot Chart with custom mapping for x-axis

Pivot Chart with sortf_mapf_mts defined to map custom names for x-axis and to customize the x-axis sorting. In this chart we would like to plot region:city instead of state:city. However region is not available in the database. So custom mapf function comes to the rescue.

Points to note:

  • Note that mapf receives a tuple and returns a tuple. This is true even when categories is a single element.
  • mts=True causes the elements to be mapped and then sorted. So all the N region cities are on the left and the S region cities are on the right hand side of the plot.


def region_state(x):
    region = {'CA': 'S', 'MA': 'N', 'TX': 'S', 'NY': 'N'}
    return (region[x[0]], x[1])

ds = PivotDataPool(
      series= [
          'source': SalesHistory.objects.all(),
          'categories': [
          'legend_by': 'book__genre__name'},
        'terms': {
      sortf_mapf_mts = (None, region_state, True))

pivcht = PivotChart(
          datasource = ds, 
          series_options = [
            {'options': {
               'type': 'column',
               'stacking': True},
             'terms': [