Matplotlib错误的colorbar分配给subplot

时间:2014-06-24 04:37:28

标签: python matplotlib plot colorbar

我有一个包装器plot2d,用于matplotlib函数imshow,它也调用colorbar(参见下面的代码)。当我以非连续顺序在子图上使用它时(例如子图2后跟子图1),在至少一个子图轴上绘制错误的颜色条。这方面的一个例子是函数bad_cb_on_top,在下面的代码中。但是,当我使用works_just_fine时,我得到了预期的结果。这两个函数之间的唯一区别是它们绘制到子图轴的顺序。

我的两个问题是:

  1. 为什么我绘制子绘图轴的顺序很重要?
  2. 如何让bad_cb_on_top产生works_just_fine当前给出的相同结果,修改bad_cp_on_top
  3. 版本信息:

    • python 2.7.3
    • matplotlib 1.1.1

    示例代码:

    from pylab import *
    
    x = linspace(-1, 1, 100)
    x, y = meshgrid(x, x)
    data = 1./(x**2 + y**2)
    
    def plot2d(data, ax=None, vmax=None):
      '''A simple wrapper for implot.'''
      # if ax was given, set ax as the current axis for plotting
      if ax :
        sca(ax)
    
      # Plot the data
      im = imshow(data, vmax=vmax, interpolation='lanczos')
      # This line assures that ax is the axis which was just plotted on
      # even if ax was not specified
      ax = im.axes
    
      # Add the colorbar
      cb = colorbar(ax=ax, orientation='vertical')
    
      return None
    
    figsize=[4, 7]
    
    def bad_cb_on_top():
      # This function copies the color bar from the bottom panel 
      # to the top panel for some unknown reason.
      fig, axs = subplots(2, 1, figsize=figsize)
      plot2d(data, vmax=31, ax=axs[1])
      plot2d(data, vmax=314, ax=axs[0])
      fig.show()
    
    def works_just_fine():
      # This function works as intended despite little change
      fig, axs = subplots(2, 1, figsize=figsize)
      plot2d(data, vmax=314, ax=axs[0])
      plot2d(data, vmax=31, ax=axs[1])
      fig.show()
    
    bad_cb_on_top()
    works_just_fine()
    

    bad_cp_on_top()的输出:

    Output from <code>bad_cp_on_top()</code>

    works_just_fine()

    的输出

    Output from <code>works_just_fine()</code>

1 个答案:

答案 0 :(得分:4)

我可能非常错误,但您可以通过将im传递给colorbar()作为mappable来强制执行正确的。在plot2d:

cb = colorbar(im, ax=ax, orientation='vertical')

我认为这样不仅可以指定轴,还可以指定可映射的输入。仅供参考,它对我没有任何影响(使用1.3.1),所以没有任何损失,但这也意味着我无法测试它。