Search code examples
pandasmatplotlibgraphchartsaxis

How to make multiple graphs with fig, ax


I'm wondering how to make multiple bar graphs.

I made a dataframe with groupby like below enter image description here

What I want is to show the min, max price of actual price and discount price each on separated two bar graph.

At first, I just tried to make graph using this code

df.plot(kind='bar', y='actual_price', stacked=False)

But this one show only one graph about the min and max of actual price.

I tried to use fig, ax = plt.subplot(1,2, figsize(10,10) as well. But it always gives the error

ax[0].bar(df.actual_price, stack=False)

enter image description here

How to solve this problem? How to know what the height is? Do I have to change the dataframe then?

Please share your opinion.

Thanks


Solution

  • Assuming a MultiIndex you might want to stack your dataset and use seaborn.catplot:

    import seaborn as sns
    
    sns.catplot(df.stack([0, 1])
                  .rename_axis(['category', 'type', 'indicator'])
                  .reset_index(name='value'),
                x='category', y='value', col='type', hue='indicator',
                kind='bar')
    

    Output:

    enter image description here

    Or, using a loop:

    import matplotlib.pyplot as plt
    
    types = df.columns.get_level_values(0).unique()
    # Index(['actual_price', 'discount_price'], dtype='object')
    
    f, axes = plt.subplots(ncols=len(types))
    
    for t, ax in zip(types, axes):
        ax.set_title(t)
        df[t].plot.bar(ax=ax)
    

    Output:

    enter image description here

    reproducible input:

    df = pd.DataFrame.from_dict({'index': ['Car', 'House', 'IT'],
                                 'columns': [('actual_price', 'min'),
                                  ('actual_price', 'max'),
                                  ('discount_price', 'min'),
                                  ('discount_price', 'max')],
                                 'data': [[10, 100, 50, 50], [5, 8, 3, 4], [1, 7, 1, 5]],
                                 'index_names': [None],
                                 'column_names': [None, None],
                                 }, orient='tight')