我正在尝试为重叠直方图中的重叠添加颜色图例。目前图例仅包括非重叠部分的颜色。我想在图例中添加第三行颜色,从而导致其他两种颜色之间重叠。
X = [3,2,1,30,20,16]
Y = [4,1,6,4,34,21]
bins=[0,10,20,30,40]
plt.figure
plt.hist(X,bins=bins,edgecolor='black',color='red',alpha=0.5,label='X')
plt.hist(Y,bins=bins,edgecolor='black',color='blue',alpha=0.5,label='Y')
plt.legend()
plt.show
这是我的输出:
直接使用手柄可以非常优雅地支持此功能。这种方法不需要手动实例化艺术家或混合颜色。
X = [3,2,1,30,20,16]
Y = [4,1,6,4,34,21]
#TMM_norm(X,Y,1)
bins=[0,10,20,30,40]
plt.figure
_,_,x_handle = plt.hist(X,bins=bins,edgecolor='black',color='red',alpha=0.5)
_,_,y_handle = plt.hist(Y,bins=bins,edgecolor='black',color='blue',alpha=0.5)
plt.legend((x_handle, y_handle, (x_handle, y_handle)), ('X','Y','X & Y'))
plt.show()
您需要混合颜色并将其添加到图例中。下面的代码将为您完成此操作。请记住先添加第二种颜色(下面代码中的 b2,然后是 b1),以便正确显示颜色。您可以根据需要编辑最后一行中图例(X、Y、X & Y)的文本。代码借自here。希望这有帮助。
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
X = [3,2,1,30,20,16]
Y = [4,1,6,4,34,21]
bins=[0,10,20,30,40]
def mix_colors(cf, cb): # cf = foreground color, cb = background color
a = cb[-1] + cf[-1] - cb[-1] * cf[-1] # fixed alpha calculation
r = (cf[0] * cf[-1] + cb[0] * cb[-1] * (1 - cf[-1])) / a
g = (cf[1] * cf[-1] + cb[1] * cb[-1] * (1 - cf[-1])) / a
b = (cf[2] * cf[-1] + cb[2] * cb[-1] * (1 - cf[-1])) / a
return [r,g,b,a]
b1 = [1.0, 0.0, 0.0, 0.5]
b2 = [0.0, 0.0, 1.0, 0.5]
b12 = mix_colors(b2, b1) # mix b2 over b1
plt.figure()
plt.hist(X,bins=bins,edgecolor='black',color='red',alpha=0.5)
plt.hist(Y,bins=bins,edgecolor='black',color='blue',alpha=0.5)
plt.legend()
plt.show
b1 = Line2D([0], [0], linestyle='none', marker='s', markersize=10, markerfacecolor=b1)
b2 = Line2D([0], [0], linestyle='none', marker='s', markersize=10, markerfacecolor=b2)
b12 = Line2D([0], [0], linestyle='none', marker='s', markersize=10, markerfacecolor=b12)
plt.legend((b1, b2, b12), ('X', 'Y', 'X & Y'), numpoints=1, loc='best')
输出图