Search code examples
pythonmatplotliblegendtitlesubplot

Global legend and title aside subplots


I've started with matplot and managed some basic plots, but now I find it hard to discover how to do some stuff I need now :(

My actual question is how to place a global title and global legend on a figure with subplots.

I'm doing 2x3 subplots where I have a lot of different graphs in various colors (about 200). To distinguish (most) of them I wrote something like

def style(i, total):
    return dict(color=jet(i/total),
                linestyle=["-", "--", "-.", ":"][i%4],
                marker=["+", "*", "1", "2", "3", "4", "s"][i%7])

fig=plt.figure()
p0=fig.add_subplot(321)
for i, y in enumerate(data):
    p0.plot(x, trans0(y), "-", label=i, **style(i, total))
# and more subplots with other transN functions

(any thoughts on this? :)) Each subplot has the same style function.

Now I'm trying to get a global title for all subplots and also a global legend which explains all styles. Also I need to make the font tiny to fit all 200 styles on there (I don't need completely unique styles, but at least some attempt)

Can someone help me solve this task?


Solution

  • Global title: In newer releases of matplotlib one can use Figure.suptitle() method of Figure:

    import matplotlib.pyplot as plt
    fig = plt.gcf()
    fig.suptitle("Title centered above all subplots", fontsize=14)
    

    Alternatively (based on @Steven C. Howell's comment below (thank you!)), use the matplotlib.pyplot.suptitle() function:

     import matplotlib.pyplot as plt
     # plot stuff
     # ...
     plt.suptitle("Title centered above all subplots", fontsize=14)