python matplotlib直方图为不同的条指定不同的颜色 [英] python matplotlib histogram specify different colours for different bars

查看:311
本文介绍了python matplotlib直方图为不同的条指定不同的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

 将numpy导入为np导入matplotlib.pyplot作为plt数据= np.random.rand(1000)plt.hist(data,color ='r') 

解决方案

一种方法可能类似于

I want to colour different bars in a histogram based on which bin they belong to. e.g. in the below example, I want the first 3 bars to be blue, the next 2 to be red, and the rest black (the actual bars and colour is determined by other parts of the code).

I can change the colour of all the bars using the color option, but I would like to be able to give a list of colours that are used.

import numpy as np
import matplotlib.pyplot as plt

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

解决方案

One way may be similar to approach in 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()

Result:

这篇关于python matplotlib直方图为不同的条指定不同的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆