Home > OS >  Python Shows Only One Figure Output
Python Shows Only One Figure Output

Time:07-20

I use the below given code. It works fine but shows only the last code's output. I want to see all figures when the code is run. How can i achieve this?

by_marry_data = data.groupby('Marital_Status')['Churn_Flag'].mean()

by_marry_data.plot(kind='bar', ylabel='Churn Ratio')

by_income_data = data.groupby('Income_Category')['Churn_Flag'].mean()

by_income_data.plot(kind='bar', ylabel='Churn Ratio')


by_gender_data = data.groupby('Gender')['Churn_Flag'].mean()

by_gender_data.plot(kind='bar', ylabel='Churn Ratio')

CodePudding user response:

If they are in the same script or cell you need to put plt.show() after each plot, unless you want the data to plot on the same figure.

by_marry_data = data.groupby('Marital_Status')['Churn_Flag'].mean()
by_marry_data.plot(kind='bar', ylabel='Churn Ratio')
plt.show();

by_income_data = data.groupby('Income_Category')['Churn_Flag'].mean()
by_income_data.plot(kind='bar', ylabel='Churn Ratio')
plt.show();

by_gender_data = data.groupby('Gender')['Churn_Flag'].mean()
by_gender_data.plot(kind='bar', ylabel='Churn Ratio')
plt.show();

CodePudding user response:

I think you are trying to draw subplots, for example as in: Creating multiple subplots using plt.subplots.

If you want to draw each plot in an horizontal row, you could use something like:

import matplotlib.pyplot as plt

plt.subplot(1, 3, 1)
by_marry_data.plot(kind='bar', ylabel='Churn Ratio')

plt.subplot(1, 3, 2)
by_income_data.plot(kind='bar', ylabel='Churn Ratio')

plt.subplot(1, 3, 3)
by_gender_data.plot(kind='bar', ylabel='Churn Ratio')

Also, you can switch from horizontal to vertical swapping first two arguments in each plt.subplot calls above.

CodePudding user response:

Try as said below.

May be call reset_index() on each groupby. Then get those dataframes and plot (rough code. Not tested below)

by_marry_data = data.reset_index().groupby('Marital_Status')['Churn_Flag'].mean()
by_income_data = data.reset_index().groupby('Income_Category')['Churn_Flag'].mean()
by_gender_data = data.reset_index().groupby('Gender')['Churn_Flag'].mean()

Now get axis from first plot and assign further.

ax = by_marry_data.plot(kind='bar', ylabel='Churn Ratio')
by_income_data.plot(ax=ax)
by_gender_data.plot(ax=ax)
  • Related