6

I am trying to plot a matrix to compare some data. But the title of plot is overlapping with the subplots:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sn
   
def save_graph_cm(CMatrix):
    # CMatrix is a dict with four 3x3 pandas DataFrame
    k = 'Wine'
    id = 0
    cm = 1
    plt.suptitle("#" + str(id) + " Confusion Matrix for " + k + " dataset")
    for c_matrix in CMatrix:
        plt.subplot(2, 2, cm)
        sn.heatmap(CMatrix[c_matrix], annot=True, cmap="YlOrRd")
        plt.title("CV - " + str(cm-1))
        plt.xlabel("Predicted Classes")
        plt.ylabel("Real Classes")
        cm += 1
    plt.tight_layout()
    plt.show

What I am getting now is:

enter image description here

iacob
  • 20,084
  • 6
  • 92
  • 119
  • Try w constrained_layout instead of tight_layout. The former takes into account subtitles – Jody Klymak Jul 13 '19 at 18:36
  • it didn't work... what worked was using Figure and subplots_adjust() – Gabriel Michelassi Jul 16 '19 at 01:03
  • `constrained_layout` definitely works. But you need to make your plot compatible: https://matplotlib.org/3.1.0/tutorials/intermediate/constrainedlayout_guide.html#suptitle – Jody Klymak Jul 16 '19 at 01:56
  • Does this answer your question? [Matplotlib tight\_layout() doesn't take into account figure suptitle](https://stackoverflow.com/a/66789231/9067615) – iacob Mar 24 '21 at 20:56

2 Answers2

4

As of v3.3, matplotlib's tight_layout now displays suptitle correctly:

import matplotlib.pyplot as plt

fig, axs = plt.subplots(1, 3)
for i, ax in enumerate(axs):
    ax.plot([1, 2, 3])
    ax.set_title(f'Axes {i}')

fig.suptitle('suptitle')
fig.tight_layout()

enter image description here

iacob
  • 20,084
  • 6
  • 92
  • 119
1

I had a similar problem, using GridSpec as in this answer https://stackoverflow.com/a/19627237/8079057 fixed it for me.

Adam
  • 57
  • 7