【问题标题】:How do I set a matplotlib colorbar extents?如何设置 matplotlib 颜色条范围?
【发布时间】:2011-02-02 02:49:56
【问题描述】:

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

我已经能够像这样成功地绘制图像和颜色条,但是颜色条的最小值和最大值表示标准化 (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

如果有人更精通 colorbar API,我很乐意听取您的意见。

谢谢! 亚当

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    看起来您将错误的对象传递给颜色条构造函数。

    这应该可行:

    # make namespace explicit
    from matplotlib import pyplot as PLT
    
    cbar = fig.colorbar(result)
    

    上面的 sn-p 是基于你答案中的代码;这是一个完整的独立示例:

    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 语句的重点),尽管这通常是你所需要的。

    【讨论】:

    • 出于兴趣@doug,你为什么要大写PLT和NP?
    • @bdforbes:所以我喜欢干净的命名空间(不与另一个重叠),而且我只是想在我的代码中以一种快速的视觉方式来识别它们——当然,PLT和 NP 是绑定到包含其他模块的库/模块的局部变量。
    【解决方案2】:

    我知道可能为时已晚,但是...
    对我来说,将 Adam 代码的最后一行 result 替换为 ax 是可行的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-23
      • 1970-01-01
      • 1970-01-01
      • 2017-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多