问题描述
我使用 matplotlib 在 python 中绘制一些数据,并且这些图需要一个标准的颜色条.数据由一系列包含频率信息的 NxM 矩阵组成,因此简单的 imshow() 图给出了带有颜色描述频率的 2D 直方图.每个矩阵包含不同但重叠范围的数据.Imshow 将每个矩阵中的数据归一化到 0-1 范围内,这意味着,例如,矩阵 A 的图与矩阵 2*A 的图看起来相同(尽管颜色条将显示两倍的值).例如,我想要的是红色对应于所有图中的相同频率.换句话说,一个单一的颜色条就足以满足所有的情节.任何建议将不胜感激.
I using matplotlib to plot some data in python and the plots require a standard colour bar. The data consists of a series of NxM matrices containing frequency information so that a simple imshow() plot gives a 2D histogram with colour describing frequency. Each matrix contains data in different, but overlapping ranges. Imshow normalizes the data in each matrix to the range 0-1 which means that, for example, the plot of matrix A, will appear identical to the plot of the matrix 2*A (though the colour bar will show double the values). What I would like is for the colour red, for example, to correspond to the same frequency in all of the plots. In other words, a single colour bar would suffice for all the plots. Any suggestions would be greatly appreciated.
推荐答案
不是窃取@ianilis 的答案,但我想添加一个示例...
Not to steal @ianilis's answer, but I wanted to add an example...
有多种方法,但最简单的就是将vmin
和vmax
kwargs 指定为imshow
.或者,您可以创建一个 matplotlib.cm.Colormap
实例并指定它,但这对于简单情况来说比所需的要复杂.
There are multiple ways, but the simplest is just to specify the vmin
and vmax
kwargs to imshow
. Alternately, you can make a matplotlib.cm.Colormap
instance and specify it, but that's more complicated than necessary for simple cases.
这里有一个简单的例子,所有图片都有一个颜色条:
Here's a quick example with a single colorbar for all images:
import numpy as np
import matplotlib.pyplot as plt
# Generate some data that where each slice has a different range
# (The overall range is from 0 to 2)
data = np.random.random((4,10,10))
data *= np.array([0.5, 1.0, 1.5, 2.0])[:,None,None]
# Plot each slice as an independent subplot
fig, axes = plt.subplots(nrows=2, ncols=2)
for dat, ax in zip(data, axes.flat):
# The vmin and vmax arguments specify the color limits
im = ax.imshow(dat, vmin=0, vmax=2)
# Make an axis for the colorbar on the right side
cax = fig.add_axes([0.9, 0.1, 0.03, 0.8])
fig.colorbar(im, cax=cax)
plt.show()
这篇关于如何在 python 中为一系列绘图创建标准颜色条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!