0

I am using a for loop to make some bar charts but they are overriding each other as it's possible to see in the screenshot below enter image description here

This is the code that I am using to draw the plot charts.

# Exploration: Categorical Vs Categorical -- bar charts
 
fig, PlotCanvas=plt.subplots(nrows=len(categFeatures), 
                             ncols=1, figsize=(15,10))
 
# Creating Grouped bar plots for each categorical predictor against the Target Variable "lifequality"
for CategoricalCol,i in zip(categFeatures,range(len(categFeatures))):
    CrossTabResult=pd.crosstab(index=df[CategoricalCol], 
                               columns=df['lifequality'])
    CrossTabResult.plot.bar(color=['red','green'], ax=PlotCanvas[i])
plt.show()

How can i fix this? After using

plt.tight_layout()

enter image description here

Fábio Pires
  • 51
  • 1
  • 7
  • 2
    `plt.tight_layout()` usually takes care of overlappings. You could also leave out the individual legends, and add one external legend, e.g. on top. – JohanC Apr 21 '22 at 15:47
  • @JohanC should I use tight_layout inside or outside for loop? Also what do you mean by external legend? – Fábio Pires Apr 21 '22 at 16:32
  • See e.g. [matplotlib external legend](https://stackoverflow.com/questions/46133157/matplotlib-external-legend-spread-across-multiple-subplots). `plt.tight_layout()` should only be called at the end, just before `plt.show(`). – JohanC Apr 21 '22 at 16:36
  • @JohanC tried with tight_layout() but still overriding. I edit my question with the new result – Fábio Pires Apr 21 '22 at 16:39
  • Maybe you could turn off the individual legends, as they are all the same? You could also rotate the x tick labels to 0 degrees (`for ax in PlotCanvas: ax.tickparams(rotation=0)`). Maybe you could choose a higher `figsize`, as things can't fit very well. (Also note that `PlotCanvas` can be a rather confusing name, especially if you want to compare tutorials and example code). You could consider adding some reproducible test data to make it easier for people to answer your question. – JohanC Apr 21 '22 at 17:51

0 Answers0