Home > Enterprise >  Matlplotlib and four plots in same picture
Matlplotlib and four plots in same picture

Time:07-09

I am working with matplotlib and I want to make four subplots in the same picture. Below you can see example of my data and my desired plot.

    import pandas as pd
    import numpy as np
    pd.set_option('max_columns', None)
    import matplotlib.pyplot as plt

    data = {
                     'type_sale': ['group_1','group_2','group_3','group_4','group_5','group_6','group_7','group_8','group_9','group_10'],
                     'open':[70,20,24,80,20,20,60,20,20,20],
                     'closed':[30,14,20,10,10,40,10,10,10,10],
                    }
df = pd.DataFrame(data, columns = ['type_sale',
                                               'open',
                                               'closed',
                                               ])
# Barplot with matplotlib    
            
df.plot(x='type_sale', kind='bar', stacked=True,
                    title='Stacked Bar Graph by dataframe')

enter image description here

Now I want to replicate this barplot four times in the same picture with the subplot command and save it in pdf. I tried this with the lines of codes below :

# Setup the subplot2grid Layout
fig = plt.figure()
# Plot 1
ax1 = plt.subplot2grid((2,2), (0,0))
ax1.df.plot(x='type_sale', kind='bar', stacked=True,
        title='Stacked Bar Graph by dataframe')

# Plot 2
ax2 = plt.subplot2grid((2,2), (1,0))
ax2.df.plot(x='type_sale', kind='bar', stacked=True,
        title='Stacked Bar Graph by dataframe')

# Plot 3
ax3 = plt.subplot2grid((2,2), (0,1))
ax3.df.plot(x='type_sale', kind='bar', stacked=True,
        title='Stacked Bar Graph by dataframe')


# Plot 4
ax4 = plt.subplot2grid((2,2), (1,1))
ax4.df.plot(x='type_sale', kind='bar', stacked=True,
        title='Stacked Bar Graph by dataframe')

fig.tight_layout()
plt.savefig('fig_name.pdf') 
plt.show()

So can anybody help me how to solve this problem?

CodePudding user response:

The easiest way, I think the example in the official enter image description here

  • Related