【问题标题】:matplotlib custom legend with hatchingmatplotlib 带有阴影的自定义图例
【发布时间】:2017-07-05 22:38:55
【问题描述】:

我似乎可以弄清楚如何将句柄和标签从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()

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

【问题讨论】:

    标签: python matplotlib legend


    【解决方案1】:

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

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

    这是你看到的吗?

    【讨论】:

    • 一定是hatch=['\\\\']。现在事情似乎正在运行。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-24
    相关资源
    最近更新 更多