pythonpandasmatplotlibplot-annotationsgrouped-bar-chart

How to add bar values, set_ylim, and set_ylabel on secondary_y


Currently have 2 problems with the following script

  1. cannot add bar labels to sets 8/9

  2. set 8 is "off the charts" regardless of what ylim I set.

     import pandas as pd
     import numpy as np
     import matplotlib.pyplot as plt
    
     categories = ['Cat1', 'Cat2', 'Cat3',
                   'Cat4', 'Cat5']
     data_sets = {'Set1': [0.151, 0.015, 0.110,  0.204,  0.110],
                  'Set2': [0.146,    0.025,  0.088,  0.151,  0.088],
                  'Set3': [0.161,    0.027,  0.122,  0.217,  0.122],
                  'Set4': [0.145,    0.015,  0.095,  0.174,  0.095],
                  'Set5': [0.216,    0.020,  0.160,  0.300,  0.160],
                  'Set6': [0.069,    0.050,  0.069,  0.088,  0.088],
                  'Set7': [0.069,    0.050,  0.069,  0.088,  0.088],
                  'Set8': [132, 131, 139, 137, 135],
                  'Set9': [132, 131, 139, 137, 135], }
    
     df = pd.DataFrame(data_sets, index=categories)
    
     ax = df.plot(kind= 'bar',secondary_y= 'Set9', rot= 0,
                   ylabel = 'test', ylim = [0, .35], grid=True )
     plt.ylabel('Check')
    
    
     for bar in ax.containers:
         ax.bar_label(bar, rotation=90)
    
    
     fig = ax.get_figure()
     ax = fig.get_axes()
     ax[1].set_ylim(0, 200)
    

Solution

  • Access the right axes with ax.right_ax as shown in the duplicates and in Plotting on a secondary y-axis.

    import pandas as pd
    
    categories = ['Cat1', 'Cat2', 'Cat3', 'Cat4', 'Cat5']
    data_sets =\
    {'Set1': [0.151, 0.015, 0.11, 0.204, 0.11],
     'Set2': [0.146, 0.025, 0.088, 0.151, 0.088],
     'Set3': [0.161, 0.027, 0.122, 0.217, 0.122],
     'Set4': [0.145, 0.015, 0.095, 0.174, 0.095],
     'Set5': [0.216, 0.02, 0.16, 0.3, 0.16],
     'Set6': [0.069, 0.05, 0.069, 0.088, 0.088],
     'Set7': [0.069, 0.05, 0.069, 0.088, 0.088],
     'Set8': [132, 131, 139, 137, 135],
     'Set9': [132, 131, 139, 137, 135]}
    
    df = pd.DataFrame(data_sets, index=categories)
    
    ax = df.plot(kind='bar', secondary_y=['Set8', 'Set9'], rot=0, width=0.9,
                 ylabel='test', ylim=[0, .35], grid=True, figsize=(10, 10))
    
    ax.right_ax.set_ylabel('Check')
    ax.right_ax.set_ylim(0, 200)
    
    for bar in ax.containers:
        ax.bar_label(bar, rotation=90, padding=3)
    
    for bar in ax.right_ax.containers:
        ax.right_ax.bar_label(bar, rotation=90, padding=3)
    

    enter image description here