【问题标题】:python matplotlib histogram specify different colours for different bars [duplicate]python matplotlib直方图为不同的条指定不同的颜色[重复]
【发布时间】:2018-08-23 17:19:24
【问题描述】:

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

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

import numpy as np
import matplotlib.pyplot as plt

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

【问题讨论】:

  • 如果您知道有多少个 bin 以及它们应该是什么颜色,那么 hist 接受颜色列表
  • @DavidG 你能告诉我怎么做吗?我尝试这样做,但没有成功。

标签: python matplotlib histogram


【解决方案1】:

一种方法可能类似于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()

结果:

【讨论】:

    猜你喜欢
    • 2013-09-29
    • 1970-01-01
    • 2019-11-29
    • 2021-05-14
    • 2020-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-29
    相关资源
    最近更新 更多