从 matplotlib 中的颜色图中获取单个颜色 [英] Getting individual colors from a color map in matplotlib
问题描述
如果你有一个 Colormap cmap
,例如:
cmap = matplotlib.cm.get_cmap('Spectral')
如何从 0 到 1 之间获取特定颜色,其中 0 是地图中的第一种颜色,1 是地图中的最后一种颜色?
理想情况下,我可以通过执行以下操作获得地图中的中间颜色:
<预><代码>>>>do_some_magic(cmap, 0.5) # 返回一个RGBA元组(0.1, 0.2, 0.3, 1.0)你可以用下面的代码来做到这一点,你问题中的代码实际上非常接近你所需要的,你所要做的就是调用 <您拥有的 code>cmap 对象.
导入 matplotlibcmap = matplotlib.cm.get_cmap('光谱')rgba = cmap(0.5)打印(RGBA)#(0.99807766255210428,0.99923106502084169,0.74602077638401709,1.0)
对于 [0.0, 1.0] 范围之外的值,它将返回底色和底色(分别).默认情况下,这是范围内的最小和最大颜色(因此为 0.0 和 1.0).这个默认值可以用 cmap.set_under()
和 cmap.set_over()
改变.
对于诸如np.nan
和np.inf
之类的特殊"数字,默认使用0.0 值,这可以使用cmap 进行更改.set_bad()
类似于上面的 under 和 over.
最后,您可能需要对数据进行规范化,使其符合 [0.0, 1.0]
范围.这可以使用 matplotlib.colors.Normalize
来完成a> 就像下面的小例子所示,其中参数 vmin
和 vmax
描述了应该分别映射到 0.0 和 1.0 的数字.
导入 matplotlib规范 = matplotlib.colors.Normalize(vmin=10.0, vmax=20.0)打印(规范(15.0))#0.5
对数归一化器(matplotlib.colors.LogNorm)也是可用于具有大范围值的数据范围.
(感谢 Joe Kington 和 tcaswell 有关如何改进答案的建议.)
If you have a Colormap cmap
, for example:
cmap = matplotlib.cm.get_cmap('Spectral')
How can you get a particular colour out of it between 0 and 1, where 0 is the first colour in the map and 1 is the last colour in the map?
Ideally, I would be able to get the middle colour in the map by doing:
>>> do_some_magic(cmap, 0.5) # Return an RGBA tuple
(0.1, 0.2, 0.3, 1.0)
You can do this with the code below, and the code in your question was actually very close to what you needed, all you have to do is call the cmap
object you have.
import matplotlib
cmap = matplotlib.cm.get_cmap('Spectral')
rgba = cmap(0.5)
print(rgba) # (0.99807766255210428, 0.99923106502084169, 0.74602077638401709, 1.0)
For values outside of the range [0.0, 1.0] it will return the under and over colour (respectively). This, by default, is the minimum and maximum colour within the range (so 0.0 and 1.0). This default can be changed with cmap.set_under()
and cmap.set_over()
.
For "special" numbers such as np.nan
and np.inf
the default is to use the 0.0 value, this can be changed using cmap.set_bad()
similarly to under and over as above.
Finally it may be necessary for you to normalize your data such that it conforms to the range [0.0, 1.0]
. This can be done using matplotlib.colors.Normalize
simply as shown in the small example below where the arguments vmin
and vmax
describe what numbers should be mapped to 0.0 and 1.0 respectively.
import matplotlib
norm = matplotlib.colors.Normalize(vmin=10.0, vmax=20.0)
print(norm(15.0)) # 0.5
A logarithmic normaliser (matplotlib.colors.LogNorm) is also available for data ranges with a large range of values.
(Thanks to both Joe Kington and tcaswell for suggestions on how to improve the answer.)
这篇关于从 matplotlib 中的颜色图中获取单个颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!