如何在 matplotlib 中向自定义图例添加剖面线?

Ama*_*nda 4 python matplotlib

编辑:FWIW 我正在 Illustrator 中修复图例,但更喜欢自动完成,因为我有大约 20 个这样的图要制作

我遵循这个非常有用的答案,将自定义图例添加到 matplotlib violinplot,它不支持自己的图例。除了当我尝试添加舱口时,它效果很好。

这是我的标签代码(我尝试以两种不同的方式添加补丁):

    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( '//' )
Run Code Online (Sandbox Code Playgroud)

孵化小提琴本身的代码运行良好:

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] )
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

与垃圾箱相关的数据(未显示)已经针对其他类别进行了颜色编码,因此我真的很想在不同的舱口中显示垃圾箱。

Bon*_*fum 5

你就快到了 - 只需要小心带有补丁的颜色参数。有两个子组件:( edgecolor) 和( facecolor);通过这个补丁艺术家设置color=定义这两种颜色。然后,舱口和背景会呈现相同的颜色,并且您无法看到其中一个。

底线:对补丁构造函数使用类似的内容:

p = matplotlib.patches.Patch(facecolor='#DCDCDC', hatch=hatch_dict[i])
Run Code Online (Sandbox Code Playgroud)

舱口

该图的完整代码:

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')
Run Code Online (Sandbox Code Playgroud)