使用python为直方图中的特定条形上色 [英] Color a specific bar in histogram using python

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

问题描述

我有一个直方图(matplotlib或绘图),想要给特定的条着色,女巫在条范围内具有N值(例如,如果N = 131,则色条必须为130-132).我该怎么办?

I have a histogram (matplotlib or plotly) and want to color a specific bar, witch has value N in the bar range (for example if N=131 the colored bar must be 130-132). How can i do that?

推荐答案

调用plt.hist()时,它将返回三件事.首先,一个数组在每个bin中保存值.其次,每个仓的值,最后是patches的数组.这些使您可以分别修改每个条.因此,您要做的就是确定哪个容器属于130-132范围,然后修改颜色,例如:

When calling plt.hist(), it will return three things. Firstly an array holding the value in each bin. Secondly the values for each of the bins, and lastly an array of patches. These let you modify each bar individually. So all you need to do is determine which bin is for the range 130-132 and then modify the colour, for example:

import numpy as np
import matplotlib.pyplot as plt

values =  np.random.randint(51, 140, 1000)
n, bins, patches = plt.hist(values, bins=np.arange(50, 140, 2), align='left', color='g')
patches[40].set_fc('r')
plt.show()

将显示如下内容:

在这里,第41个补丁对应于范围130-132,因为我选择的容器从50开始并以2的步长升至140.因此总共将有45个容器.如果您print bins,您会看到索引40是您想要的索引:

Here the 41st patch corresponds to the range 130-132 as the bins I have chosen start at 50 and go up to 140 in steps of 2. So there will be 45 bins in total. If you print bins you would see that index 40 is the one you want:

[ 50  52  54  56  58  60  62  64  66  68  70  72  74  76  78  80  82  84
  86  88  90  92  94  96  98 100 102 104 106 108 110 112 114 116 118 120
 122 124 126 128 130 132 134 136 138]

这篇关于使用python为直方图中的特定条形上色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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