如何设置matplotlib colorbar范围?

Ada*_*ser 4 python matplotlib

我想在matplotlib imshow子图的旁边显示一个颜色条,表示图像的原始值,该子图显示该图像,进行标准化.

我已经能够像这样成功地绘制图像和颜色条,但是颜色条最小值和最大值代表标准化(0,1)图像而不是原始(0,99)图像.

f = plt.figure()
# create toy image
im = np.ones((100,100))
for x in range(100):
    im[x] = x
# create imshow subplot
ax = f.add_subplot(111)
result = ax.imshow(im / im.max())

# Create the colorbar
axc, kw = matplotlib.colorbar.make_axes(ax)
cb = matplotlib.colorbar.Colorbar(axc, result)

# Set the colorbar
result.colorbar = cb
Run Code Online (Sandbox Code Playgroud)

如果有人对colorbar API有更好的掌握,我很乐意听取您的意见.

谢谢!亚当

dou*_*oug 7

看起来你将错误的对象传递给了colorbar构造函数.

这应该工作:

# make namespace explicit
from matplotlib import pyplot as PLT

cbar = fig.colorbar(result)
Run Code Online (Sandbox Code Playgroud)

上面的代码段基于您答案中的代码; 这是一个完整的,独立的例子:

import numpy as NP
from matplotlib import pyplot as PLT

A = NP.random.random_integers(0, 10, 100).reshape(10, 10)
fig = PLT.figure()
ax1 = fig.add_subplot(111)

cax = ax1.imshow(A, interpolation="nearest")

# set the tickmarks *if* you want cutom (ie, arbitrary) tick labels:
cbar = fig.colorbar(cax, ticks=[0, 5, 10])

# note: 'ax' is not the same as the 'axis' instance created by calling 'add_subplot'
# the latter instance i bound to the variable 'ax1' to avoid confusing the two
cbar.ax.set_yticklabels(["lo", "med", "hi"])

PLT.show()
Run Code Online (Sandbox Code Playgroud)

正如我在上面的评论中所建议的那样,我会选择一个更清晰的命名空间 - 例如,NumPy和Matplotlib中都有相同名称的模块.

特别是,我将使用此import语句导入Matplotlib的"核心"绘图功能:

from matplotlib import pyplot as PLT
Run Code Online (Sandbox Code Playgroud)

当然,这并没有获得整个matplotlib命名空间(这实际上是这个import语句的重点),尽管这通常都是你需要的.