How to generate grouped BAR plot in Python?
0

How to generate grouped BAR plot in Python?

This recipe helps you generate grouped BAR plot in Python
In [3]:
## How to generate grouped BAR plot in Python
def Snippet_117():
    print()
    print(format('How to generate grouped BAR plot in Python','*^82'))

    import warnings
    warnings.filterwarnings("ignore")

    # load libraries
    import pandas as pd
    import matplotlib.pyplot as plt

    # Create dataframe
    raw_data = {'first_name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'],
                'pre_score': [4, 24, 31, 2, 3],
                'mid_score': [25, 94, 57, 62, 70],
                'post_score': [5, 43, 23, 23, 51]}
    df = pd.DataFrame(raw_data, columns = ['first_name', 'pre_score', 'mid_score', 'post_score'])
    print(); print(df)

    # Setting the positions and width for the bars
    pos = list(range(len(df['pre_score'])))
    width = 0.25

    # Plotting the bars
    fig, ax = plt.subplots(figsize=(10,5))

    # Create a bar with pre_score data
    plt.bar(pos, df['pre_score'], width, alpha=0.5, color='#EE3224')
    #plt.show()

    # Create a bar with mid_score data,
    plt.bar([p + width for p in pos], df['mid_score'], width, alpha=0.5, color='#F78F1E')
    #plt.show()

    # Create a bar with post_score data,
    plt.bar([p + width*2 for p in pos], df['post_score'], width, alpha=0.5, color='#FFC222')
    #plt.show()

    # Set the y axis label
    ax.set_ylabel('Score')

    # Set the chart's title
    ax.set_title('Test Subject Scores')

    # Set the position of the x ticks
    ax.set_xticks([p + 1.5 * width for p in pos])

    # Set the labels for the x ticks
    ax.set_xticklabels(df['first_name'])

    # Setting the x-axis and y-axis limits
    plt.xlim(min(pos)-width, max(pos)+width*4)
    plt.ylim([0, max(df['pre_score'] + df['mid_score'] + df['post_score'])] )

    # Adding the legend and showing the plot
    plt.legend(['Pre Score', 'Mid Score', 'Post Score'], loc='upper left')
    plt.grid()
    plt.show()

Snippet_117()
********************How to generate grouped BAR plot in Python********************

  first_name  pre_score  mid_score  post_score
0      Jason          4         25           5
1      Molly         24         94          43
2       Tina         31         57          23
3       Jake          2         62          23
4        Amy          3         70          51