gpt4 book ai didi

python - 如何在 matplotlib 中为自定义图例添加阴影线?

转载 作者:太空宇宙 更新时间:2023-11-04 00:08:39 25 4
gpt4 key购买 nike

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

我关注了this将自定义图例添加到不支持自己的图例的 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( '//' )

孵化 fiddle 本身的代码工作正常:

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

enter image description here

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

最佳答案

你几乎就在那里 - 只需要小心补丁的颜色参数。有两个子组件:edge (edgecolor) 和 face (facecolor);通过此补丁艺术家设置 color= 定义了这两种颜色。舱口和背景会呈现相同的颜色,您无法从另一个看到一个。

底线:为你的补丁构造函数使用类似这样的东西:

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

hatches

该图的完整代码:

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

关于python - 如何在 matplotlib 中为自定义图例添加阴影线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53255914/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com