2017-07-05 39 views
2

我似乎弄清楚如何将手柄和标签从matplotlib.patches.Patch传递到图例。matplotlib自定义传奇与孵化

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

我无法重现您的问题,或者您错过了一个很大的错误。当我在上面运行你的代码时,我得到一个关于list不可排队的错误,这个错误似乎来自第一个Patch调用的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

这是你看到的是什么?

+1

它已经成为'hatch = ['\\\'']'。现在事情似乎表现得很好。谢谢! – dubbbdan