【问题标题】:Matplotlib histogram with multiple legend entries具有多个图例条目的 Matplotlib 直方图
【发布时间】:2017-10-07 22:05:03
【问题描述】:

我有这段代码可以生成直方图,识别三种类型的字段; “低”、“中”和“高”:

import pylab as plt
import pandas as pd


df = pd.read_csv('April2017NEW.csv', index_col =1)
df1 = df.loc['Output Energy, (Wh/h)']  # choose index value and Average
df1['Average'] = df1.mean(axis=1)

N, bins, patches = plt.hist(df1['Average'], 30)

cmap = plt.get_cmap('jet')
low = cmap(0.5)
medium =cmap(0.25)
high = cmap(0.8)


for i in range(0,4):
    patches[i].set_facecolor(low)
for i in range(4,11):
    patches[i].set_facecolor(medium)
for i in range(11,30):
    patches[i].set_facecolor(high)

plt.xlabel("Watt Hours", fontsize=16)  
plt.ylabel("Households", fontsize=16)
plt.xticks(fontsize=14)  
plt.yticks(fontsize=14)
ax = plt.subplot(111)  
ax.spines["top"].set_visible(False)  
ax.spines["right"].set_visible(False)

plt.show()

产生这个:

如何在其中获得三种不同颜色的图例?

【问题讨论】:

    标签: python matplotlib histogram


    【解决方案1】:

    您需要自己创建图例。为此,创建一些图中未显示的矩形(所谓的代理艺术家)。

    #create legend
    handles = [Rectangle((0,0),1,1,color=c,ec="k") for c in [low,medium, high]]
    labels= ["low","medium", "high"]
    plt.legend(handles, labels)
    

    完整示例:

    import matplotlib.pyplot as plt
    import numpy as np
    from matplotlib.patches import Rectangle
    
    data = np.random.rayleigh(size=1000)*35
    
    N, bins, patches = plt.hist(data, 30, ec="k")
    
    cmap = plt.get_cmap('jet')
    low = cmap(0.5)
    medium =cmap(0.25)
    high = cmap(0.8)
    
    
    for i in range(0,4):
        patches[i].set_facecolor(low)
    for i in range(4,11):
        patches[i].set_facecolor(medium)
    for i in range(11,30):
        patches[i].set_facecolor(high)
    
    #create legend
    handles = [Rectangle((0,0),1,1,color=c,ec="k") for c in [low,medium, high]]
    labels= ["low","medium", "high"]
    plt.legend(handles, labels)
    
    plt.xlabel("Watt Hours", fontsize=16)  
    plt.ylabel("Households", fontsize=16)
    plt.xticks(fontsize=14)  
    plt.yticks(fontsize=14)
    
    plt.gca().spines["top"].set_visible(False)  
    plt.gca().spines["right"].set_visible(False)
    
    plt.show()
    

    【讨论】:

      【解决方案2】:

      据我所知,您只需将所需的标签作为参数传递给 hist 函数,例如

      plt.hist(x, bins=20, alpha=0.5, label='my label')
      

      也可以在这里查看示例https://matplotlib.org/examples/statistics/histogram_demo_multihist.html

      【讨论】:

      • 这应该是公认的答案;它更简洁,更容易做到。
      猜你喜欢
      • 2022-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多