Matplotlib - 显示 .plot 和 .bar 的图例

Matplotlib - show legend for .plot and .bar

下面的代码

import numpy as np
import matplotlib.pyplot as plt

x = [1,2,3,4,5]
y = np.array([0.1,0.5,0.4,0.3,0.4])
p = [0.6,0.3,0.15,0.1,0.5]

f, axes = plt.subplots(1,2,figsize=(20,4))   

axes[0].plot(x,y)
axes[0].plot(x,y+0.05)
axes[0].bar(x,p,color="r",alpha=0.2)
axes[1].plot(x,y)
axes[1].plot(x,y+0.05)
axes[1].bar(x,p,color="r",alpha=0.2)

aliases = ["data1","data2","probabiity"]

handles = axes[1].get_lines()
f.legend(handles, aliases, loc='upper center', ncol=len(aliases),  fontsize=10, bbox_to_anchor=(0.5, 1))
plt.savefig("temp.pdf")

生成下图。它只显示折线图的图例 data1data2,但条形图的图例是空的。我怎样才能让 matplotlib 在同一个图例中包含条形图?

问题是

handles = axes[1].get_lines()

显然bar的结果不是一行。您还需要包括补丁集合对象:

handles = axes[1].get_lines() + axes[1].containers

参考这里:

  • How do I get all bars in a matplotlib bar chart?