gpt4 book ai didi

python - Matplotlib 分配给子图的错误颜色条

转载 作者:行者123 更新时间:2023-11-28 22:49:03 25 4
gpt4 key购买 nike

我有一个包装器,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

版本信息:

  • 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>

最佳答案

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

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

我认为它不仅指定了坐标轴,还指定了可映射的输入。仅供引用,这对我(使用 1.3.1)没有影响,所以没有任何问题,但这也意味着我无法测试它。

关于python - Matplotlib 分配给子图的错误颜色条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24378414/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com