Reputation: 3041
I have two graphs individually and I want to display them on the same plot.
This is my plot 1 code
ax1= concatenated_data_cleaned.groupby(['Cat1', 'Cat2']).median()[['Measure']].unstack()
ax1.plot.bar(rot =0)
plt.xlabel("Cat Names")
plt.ylabel("Measures")
plt.title("Title 1")
plt.show()
This is my plot 2 Code,
ax2= concatenated_data_cleaned.groupby(['Cat2', 'Cat1']).median()[['Measure']].unstack()
ax1.plot.bar(rot =0)
plt.xlabel("Cat Names")
plt.ylabel("Measures")
plt.title("Title 2")
plt.show()
Now, this gets shown in different graph (image) one after another. How Can I show this in the same graph - one below another in the same graph (image).
Kindly help me with this.
This is what I am trying,
fig, axes = plt.subplots(nrows=2)
df1= concatenated_data_cleaned.groupby(['Cat1', 'Cat2']).median()[['Measure']].unstack()
ax1 = df1.plot.bar(rot =0)
df2= concatenated_data_cleaned.groupby(['Cat2', 'Cat1']).median()[['Measure']].unstack()
ax2 = df2.plot.bar(rot =0)
ax1.plt.bar(rot=0, ax=axes[0])
ax2.plt.bar(rot=0, ax=axes[1])
plt.show()
And it is not working for me.
Upvotes: 0
Views: 278
Reputation: 10590
Your variable naming is a bit unconventional. ax
typically is used for a matplotlib Axes object. Here you have a dataframe.
Regardless, you should set up a figure with two axes. plt.subplots
is an easy way to do this. It will return the figure and an array with all the axes that you create. You can even set the axis to be equal between the two with sharex
and sharey
. Use the axes objects in your plotting call for each dataframe:
df1= concatenated_data_cleaned.groupby(['Cat1', 'Cat2']).median()[['Measure']].unstack()
df2= concatenated_data_cleaned.groupby(['Cat2', 'Cat1']).median()[['Measure']].unstack()
fig, axes = plt.subplots(nrows=2, sharex=True, sharey=True)
df1.plot.bar(rot=0, ax=axes[0])
df2.plot.bar(rot=0, ax=axes[1])
axes[0].set_title('Title 0')
axes[1].set_title('Title 1')
plt.show()
Upvotes: 2