Search code examples
pythonmatplotliblabelcontour

Labelling contour levels with personalized labels


I would like to label contour levels in a density plot, with personalized labels. I have written something like

contours = plt.contour(X, Y, Z, 3, colors='black')
plt.clabel(contours, inline=True, levels=[1,2], fontsize=8)

plt.imshow(Z, extent=[0, 5, 0, 5], origin='lower',
       cmap='RdGy', alpha=0.5)
plt.colorbar();

I would like that the contours are labelled by a name like r'\textbf{1-}'+r'$\sigma$'


Solution

  • What you're asking for is directly shown in the second example of the contour_label_demo. I will just quote that example here:

    ##################################################
    # Label contours with arbitrary strings using a
    # dictionary
    ##################################################
    plt.figure()
    
    # Basic contour plot
    CS = plt.contour(X, Y, Z)
    
    fmt = {}
    strs = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh']
    for l, s in zip(CS.levels, strs):
        fmt[l] = s
    
    # Label every other level using strings
    plt.clabel(CS, CS.levels[::2], inline=True, fmt=fmt, fontsize=10)