pythonmatplotliblabel

matplotlib - making labels for violin plots


I usually make labels for bars in the following manner using parameter 'label' in the method 'bar'.

axes[0].bar(x, y, bar_width, label='abc')
axes[0].legend()

Now I'd like to plot violin plots and make label for each collection as follows, but it doesn't work since 'violinplot' doesn't have the parameter 'label'.

axes[0].violinplot(data1, label='abc1')
axes[1].violinplot(data2, label='abc2')

Can anyone help me out to make a label for each collection?


Solution

  • As it was mentioned in comment, some plots in matplotlib don't support legends. Documentation still provides a simple way to add custom legends for them: http://matplotlib.org/users/legend_guide.html#proxy-legend-handles

    Main idea : add 'fake' objects, which can be not shown in the plot, then use it to form a handles list for legend method.

        import random
        import numpy as np
        import matplotlib.pyplot as pl
        import matplotlib.patches as mpatches
        from itertools import repeat
    
        red_patch = mpatches.Patch(color='red')
        # 'fake' invisible object
    
        pos   = [1, 2, 4, 5, 7, 8]
        label = ['plot 1','plot2','ghi','jkl','mno','pqr']
        data  = [np.random.normal(size=100) for i in pos]
    
        fake_handles = repeat(red_patch, len(pos))
    
        pl.figure()
        ax = pl.subplot(111)
        pl.violinplot(data, pos, vert=False)
        ax.legend(fake_handles, label)
        pl.show()
    

    violinplot with custom legend