pythonpandasmatplotlibgrouped-bar-chart

Bars' order in combined plot


I need to change the order of combined bars on a plot - first 'group_b', last 'group_a'. It seems like very simple ... but I have no good idea.

I can change columns name, after that to change a legend and get what I need - but I think it is a wrong way.

I have checked similar questions and didn't find an answer(((

Is there any simple and clear way to do it?

enter image description here


Solution

  • pandas will plot the bars according to the order of the columns in the dataframe. So we just need to reorder the columns to get the plot you want.

    Consider the following:

    import pandas as pd
    import matplotlib.pyplot as plt
    
    df = pd.DataFrame({'group_a': [1, 2, 3, 4, 5], 'group_b': [6, 5, 4, 3, 2]})
    
    df.plot(kind='bar')
    plt.show()
    
    my_order = ['group_b', 'group_a']
    df[my_order].plot(kind='bar')
    plt.show()
    

    The first image, before we reordered, has group_a first: enter image description here

    The second image, after reordering, has group_b first: enter image description here