编辑:FWIW我正在Illustrator中修复图例,但希望自动执行,因为我要绘制大约20个图
我遵循了this的非常有用的答案,即将自定义图例添加到不支持其自身图例的matplotlib小提琴图中。效果很好,除了我尝试添加图案填充时。
这是标签的代码(我尝试了两种不同的方式添加补丁):
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( '//' )
孵化小提琴本身的代码很好用:
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] )
垃圾箱所涉及的数据(未显示)已经用其他类别进行了颜色编码,因此我真的想在不同的阴影处显示垃圾箱。
答案 0 :(得分:3)
您快到了-只需要注意带有补丁的color参数。有两个子组件: edge (edgecolor
)和 face (facecolor
);使用该补丁艺术家设置,color=
定义了这两种颜色。然后,阴影线和背景将显示为相同的颜色,您将看不到彼此。
底线:对补丁构造函数使用类似的内容:
p = matplotlib.patches.Patch(facecolor='#DCDCDC', hatch=hatch_dict[i])
此图的完整代码:
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 xrange(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')