【问题标题】:User defined legend in pythonpython中用户定义的图例
【发布时间】:2017-02-23 19:55:45
【问题描述】:
我有这个图,其中曲线之间的某些区域被定义填充。有没有办法将它们包含在传说中?特别是在那些填充区域重叠的地方,以及出现新的不同颜色的地方。

或者无论曲线的数据如何,都可以定义任意图例?

【问题讨论】:

标签: python matplotlib legend-properties


【解决方案1】:

使用fill_bettween 绘制数据将自动在图例中包含填充区域。

要包含两个数据集重叠的区域,您可以将两个数据集的图例句柄合并为一个图例句柄。

正如 cmets 中所指出的,您还可以使用代理定义任意图例句柄。

最后,您可以准确定义要在图例中显示的句柄和标签,而不管图表中绘制的数据如何。

请参阅下面说明上述要点的 MWE:

import matplotlib.pyplot as plt
import numpy as np

plt.close('all')

# Gererate some datas:
x = np.random.rand(50)
y = np.arange(len(x))

# Plot data:
fig, ax = plt.subplots(figsize=(11, 4))
fillA = ax.fill_between(y, x-0.25, 0.5, color='darkolivegreen', alpha=0.65, lw=0)
fillB = ax.fill_between(y, x, 0.5, color='indianred', alpha=0.75, lw=0)

linec, = ax.plot(y, np.zeros(len(y))+0.5, color='blue', lw=1.5)
linea, = ax.plot(y, x, color='orange', lw=1.5)
lineb, = ax.plot(y, x-0.25, color='black', lw=1.5)

# Define an arbitrary legend handle with a proxy:
rec1 = plt.Rectangle((0, 0), 1, 1, fc='blue', lw=0, alpha=0.25)

# Generate the legend:
handles = [linea, lineb, linec, fillA, fillB, (fillA, fillB),
           rec1, (fillA, fillB, rec1)]
labels = ['a', 'b', 'c', 'A', 'B', 'A+B', 'C', 'A+B+C']
ax.legend(handles, labels, loc=2, ncol=4)

ax.axis(ymin=-1, ymax=2)

plt.show()

【讨论】:

    【解决方案2】:

    是的,ian_itor、tacaswell 和 Jean-Sébastien 完全正确,用户定义的图例似乎是唯一的解决方案,此外我为这些区域制作了不同的 linewidth 以便与曲线区分开来,和 alpha 一起玩得到了正确的颜色。

    handles, labels = ax.get_legend_handles_labels()
    display = (0,1,2,3,4)
    
    overlap_1 = plt.Line2D((0,1),(0,0), color='firebrick', linestyle='-',linewidth=15, alpha = 0.85)
    overlap_2= plt.Line2D((0,1),(0,0), color='darkolivegreen',linestyle='-',linewidth=15, alpha = 0.65)
    over_lo_3= plt.Line2D((0,1),(0,0), color='indianred',linestyle='-',linewidth=15, alpha = 0.75) 
    
    ax.legend([handle for i,handle in enumerate(handles) if i in display]+[overlap_1 , overlap_2 , overlap_3 ],
          [label for i,label in enumerate(labels) if i in display]+['D','F','G'])
    

    【讨论】:

    • 除了为over_lo_3寻找正确的颜色外,还可以通过简单地使用(overlap_1, overlap_2)而不是over_lo_3来简单地组合overlap_1overlap_2句柄当您定义图例时。但是您的解决方案也很有效,做得很好。
    猜你喜欢
    • 2019-04-13
    • 2014-11-02
    • 2015-04-28
    • 2021-12-09
    • 2011-09-12
    • 1970-01-01
    • 2020-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多