Python 带有多个图例条目的Matplotlib直方图
我有一个生成直方图的代码,识别三种类型的字段;“低”、“中”和“高”: 这就产生了:Python 带有多个图例条目的Matplotlib直方图,python,matplotlib,histogram,Python,Matplotlib,Histogram,我有一个生成直方图的代码,识别三种类型的字段;“低”、“中”和“高”: 这就产生了: 如何获得三种不同颜色的图例?您需要自己创建图例。为此,创建一些图中未显示的矩形(称为代理艺术家) 完整示例: import matplotlib.pyplot as plt import numpy as np from matplotlib.patches import Rectangle data = np.random.rayleigh(size=1000)*35 N, bins, patches
如何获得三种不同颜色的图例?您需要自己创建图例。为此,创建一些图中未显示的矩形(称为代理艺术家) 完整示例:
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()
根据我的说法,您只需要在
hist
函数中传递所需的标签作为参数,例如
plt.hist(x, bins=20, alpha=0.5, label='my label')
请参见此处的示例
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()
plt.hist(x, bins=20, alpha=0.5, label='my label')