简体   繁体   English

如何在matplotlib中为自定义图例添加孵化?

[英]How to add hatch to custom legend in matplotlib?

Edit: FWIW I am fixing the legend in Illustrator, but would prefer to do it automatically because I have about 20 of these plots to make编辑:FWIW 我正在 Illustrator 中修复图例,但更愿意自动完成,因为我有大约 20 个这样的图要制作

I followed this very helpful answer for adding a custom legend to a matplotlib violinplot, which doesn't support its own legend.我遵循了这个非常有用的答案,将自定义图例添加到不支持自己的图例的 matplotlib violinplot。 It worked great except when I tried to add hatches.除非我尝试添加舱口,否则效果很好。

Here's my code for the labels (I tried adding patch two different ways):这是我的标签代码(我尝试以两种不同的方式添加补丁):

    labels = [ 'Low entropy bin', 'Medium entropy bin', 'High entropy bin' ]
    legend_patches = 3*[matplotlib.patches.Patch( color='#DCDCDC', hatch='//' )]
    for i in legend_patches:
       i.set_hatch( '//' )

The code for hatching the violins themselves works fine:孵化小提琴本身的代码工作正常:

parts = plt.violinplot( data, showmeans=False, showextrema=True, showmedians=True )

hatch_dict = { 0:'', 1:'///', 2:'xx' }

for t in range(0, 3):
    third = range( 0, len( labels ) )[ t*(int(len(labels)/3)):(((t+1)*int(len(labels)/3))) ]
    for i in third:
        face = parts['bodies'][i]
        face.set_hatch( hatch_dict[t] )

在此处输入图片说明

The data the bins relate to (not shown) is already color coded for other categories so I'd really like to show the bins in different hatches.垃圾箱相关的数据(未显示)已经为其他类别进行了颜色编码,所以我真的很想在不同的舱口中显示垃圾箱。

You are almost there - just need to be careful with the color argument with patches.你快到了 - 只需要小心带有补丁的颜色参数。 There are two sub-components: an edge ( edgecolor ) and a face ( facecolor );有两个子组件:edgecolor )和facecolor ); with this patch artist setting the color= defines both of these colors.使用此补丁艺术家设置color=定义这两种颜色。 The hatch and the background then come out the same color and you can't see one from the other.舱口和背景会出现相同的颜色,你无法从另一个中看到一个。

Bottom line: use something like this for your patch constructor:底线:对您的补丁构造函数使用这样的东西:

p = matplotlib.patches.Patch(facecolor='#DCDCDC', hatch=hatch_dict[i])

孵化

Full code for this plot:此图的完整代码:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches

# generate some data
n = 50
sigmas = np.array([0.1, 0.05, 0.15])
means  = np.array([0.2, 0.5, 0.75])
data = sigmas * np.random.randn(n, 3) + means

labels = [ 'Low entropy bin', 'Medium entropy bin', 'High entropy bin' ]

parts = plt.violinplot( data, showmeans=False, showextrema=True, showmedians=True)

# set up color and hatching on the violins
hatch_dict = { 0:'', 1:'///', 2:'xx' }
for i, face in enumerate(parts['bodies']):
    face.set_hatch(hatch_dict[i])
    face.set_facecolor('#DCDCDC')

# for completeness update all the lines (you already had this styling applied)
for elem in ['cbars', 'cmedians', 'cmaxes', 'cmins']:
    parts[elem].set_edgecolor('0.5')

# construct proxy artist patches
leg_artists = []
for i in range(len(hatch_dict)):
    p = matplotlib.patches.Patch(facecolor='#DCDCDC', hatch=hatch_dict[i])
    # can also explicitly declare 2nd color like this
    #p = matplotlib.patches.Patch(facecolor='#DCDCDC', hatch=hatch_dict[i], edgecolor='0.5')

    leg_artists.append(p)

# and add them to legend.
ax = plt.gca()
ax.legend(leg_artists, labels, loc='upper left')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM