如何设置matplotlib颜色栏范围?

2024-06-11 17:54:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在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

如果有人对ColorBarAPI有更好的掌握,我很高兴听到你的消息。

谢谢! 亚当


Tags: the图像matplotlib颜色createresultax子块
2条回答

我知道可能太晚了,但是……
对我来说,用ax替换Adam的最后一行代码result是可行的。

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

这应该有效:

# make namespace explicit
from matplotlib import pyplot as PLT

cbar = fig.colorbar(result)

上面的代码片段基于您的答案中的代码;下面是一个完整的独立示例:

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()

正如我在上面的注释中所建议的,我将选择一个更干净的名称空间来说明您所拥有的——例如,在NumPy和Matplotlib中都有同名的模块。

特别是,我将使用这个import语句导入Matplotlib的“核心”绘图功能:

from matplotlib import pyplot as PLT

当然,这并不能得到整个matplotlib名称空间(这实际上是import语句的重点),尽管这通常是您所需要的全部。

相关问题 更多 >