更新时间:2023-01-27 12:10:14
您可以使用下面的代码来完成此操作,而问题中的代码实际上与所需的代码非常接近,您所要做的就是调用cmap
您拥有的对象.
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)
对于[0.0,1.0]范围之外的值,它将分别返回底色和底色.默认情况下,这是该范围内的最小和最大颜色(即0.0和1.0).可以使用cmap.set_under()
和cmap.set_over()
更改此默认值.
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()
.
对于诸如np.nan
和np.inf
之类的特殊"数字,默认值是使用0.0值,可以使用cmap.set_bad()
进行更改,类似于上面的上下.
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.
最后,您可能需要对数据进行规范化,使其符合范围[0.0, 1.0]
.可以使用 matplotlib.colors.Normalize
来完成,如小示例所示下面的参数vmin
和vmax
描述应该分别映射到0.0和1.0的数字.
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
对数归一化器( matplotlib.colors.LogNorm )也是可用于具有较大值范围的数据范围.
A logarithmic normaliser (matplotlib.colors.LogNorm) is also available for data ranges with a large range of values.
(感谢 Joe Kington 和
(Thanks to both Joe Kington and tcaswell for suggestions on how to improve the answer.)