matplotlib自定义传奇与孵化

时间:2017-07-05 22:38:56

标签: python matplotlib legend

我似乎可以弄清楚如何将句柄和标签从matplotlib.patches.Patch传递到图例。

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches


a_val = 0.6
colors = ['#EA5739','#FEFFBE','#4BB05C']


circ1 = mpatches.Patch( facecolor=colors[0],alpha=a_val,hatch=['\\\\'],label='Label1')
circ2= mpatches.Patch( facecolor=colors[1],alpha=a_val,hatch='o',label='Label2')
circ3 = mpatches.Patch(facecolor=colors[2],alpha=a_val,hatch='+',label='Label3')

fig,(ax) = plt.subplots()

ax.legend(handles = [circ1,circ2,circ3],loc=2)
plt.tight_layout()

为什么上面的例子中的图例是空白的?

1 个答案:

答案 0 :(得分:1)

要么我无法重现您的问题,要么您错过了一个巨大的错误。当我运行上面的代码时,我收到有关list无法清除的错误,这似乎来自第一个Patch调用hatch=['\\\\'] kwarg。删除列表语法(并使用带有4个反斜杠的原始字符串以获得额外效果)似乎对matplotlib 2.0.2有用:

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches


a_val = 0.6
colors = ['#EA5739','#FEFFBE','#4BB05C']


circ1 = mpatches.Patch( facecolor=colors[0],alpha=a_val,hatch=r'\\\\',label='Label1')
circ2= mpatches.Patch( facecolor=colors[1],alpha=a_val,hatch='o',label='Label2')
circ3 = mpatches.Patch(facecolor=colors[2],alpha=a_val,hatch='+',label='Label3')

fig,(ax) = plt.subplots()

ax.legend(handles = [circ1,circ2,circ3],loc=2)
plt.tight_layout()

result of the above

这就是你所看到的吗?