Issue
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')
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?
Solution
The easiest way, I think the example in the official reference, is to assign the graph of pandas to it as axs
creates a graph for each of the subplots. For a summary title, use plt.suptitle
. If you need individual titles, specify a title for each, as in the reference example.
fig, axs = plt.subplots(2,2, figsize=(8,6))
plt.subplots_adjust(wspace=0.2, hspace=0.6)
df.plot(x='type_sale', kind='bar', stacked=True, ax=axs[0,0])
df.plot(x='type_sale', kind='bar', stacked=True, ax=axs[0,1])
df.plot(x='type_sale', kind='bar', stacked=True, ax=axs[1,0])
df.plot(x='type_sale', kind='bar', stacked=True, ax=axs[1,1])
plt.suptitle(t='Stacked Bar Graph by dataframe', fontsize=16)
plt.show()
Answered By - r-beginners
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.