matplotlib-为小提琴图制作标签 [英] matplotlib - making labels for violin plots

查看:384
本文介绍了matplotlib-为小提琴图制作标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通常以以下方式使用"bar"方法中的参数"label"来制作条形标签.

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()

现在,我想按以下方式绘制小提琴图并为每个集合制作标签,但是由于"violinplot"没有参数"label",因此它不起作用.

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?

推荐答案

正如注释中提到的,matplotlib中的某些图不支持图例.文档仍然提供了一种为它们添加自定义图例的简单方法: http://matplotlib. org/users/legend_guide.html#proxy-legend-handles

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()

这篇关于matplotlib-为小提琴图制作标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆