【问题标题】:Matplotlib - show legend for .plot and .barMatplotlib - 显示 .plot 和 .bar 的图例
【发布时间】:2021-08-12 11:17:25
【问题描述】:

下面的代码

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 在同一个图例中包含条形图?

【问题讨论】:

    标签: python matplotlib legend


    【解决方案1】:

    问题是

    handles = axes[1].get_lines()
    

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

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

    参考这里:

    【讨论】:

      猜你喜欢
      • 2021-05-25
      • 2016-10-25
      • 2015-08-18
      • 2022-12-02
      • 2020-08-01
      • 1970-01-01
      • 2020-12-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多