python matplotlib直方图为不同的条指定不同的颜色

时间:2018-03-15 01:41:11

标签: python matplotlib histogram

我想根据它们所属的bin来为直方图中的不同条纹着色。例如在下面的例子中,我希望前3个条形为蓝色,接下来的2条为红色,其余为黑色(实际条形和颜色由代码的其他部分决定)。

我可以使用颜色选项更改所有条形的颜色,但我希望能够提供所使用的颜色列表。

import numpy as np
import matplotlib.pyplot as plt

data = np.random.rand(1000)
plt.hist(data,color = 'r')

1 个答案:

答案 0 :(得分:4)

一种方法可能类似于other answer中的方法:

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
data = np.random.rand(1000)

N, bins, patches = ax.hist(data, edgecolor='white', linewidth=1)

for i in range(0,3):
    patches[i].set_facecolor('b')
for i in range(3,5):    
    patches[i].set_facecolor('r')
for i in range(5, len(patches)):
    patches[i].set_facecolor('black')

plt.show()

结果:

enter image description here

相关问题