将颜色条添加到具有相同宽高比的两个子图

时间:2014-04-24 13:32:00

标签: python matplotlib

我试图将颜色条添加到由两个具有相同宽高比的子图组成的图中,即使用set_aspect('equal')

enter image description here

用于创建此图的代码可以在this IPython notebook中找到。

使用下面显示的代码(and here in the notebook)创建的图像是我能得到的最好结果,但它仍然不是我想要的。

plt.subplot(1,2,1)
plt.pcolormesh(rand1)
plt.gca().set_aspect('equal')

plt.subplot(1,2,2)
plt.pcolormesh(rand2)
plt.gca().set_aspect('equal')

plt.tight_layout()

from mpl_toolkits.axes_grid1 import make_axes_locatable
divider = make_axes_locatable(plt.gca())
cax = divider.append_axes("right", size="5%", pad=0.05)

plt.colorbar(cax=cax)

enter image description here

这个问题似乎有关:

3 个答案:

答案 0 :(得分:6)

我仍然不确定你到底想要什么,但我想你想在添加色条时使用pcolormesh使用相同大小的子图?

我现在所拥有的是一个黑客,因为我为两个子图添加colorbar以确保它们具有相同的大小。后来我删除了第一个colorbar。如果结果是你想要的,我可以用更加pythonic的方式来实现它。目前,对于你究竟想要的东西,它仍然有点模糊。

import numpy
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable


data = numpy.random.random((10, 10))

fig = plt.figure()

ax1 = fig.add_subplot(1,2,1, aspect = "equal")
ax2 = fig.add_subplot(1,2,2, aspect = "equal")

im1 = ax1.pcolormesh(data)
im2 = ax2.pcolormesh(data)

divider1 = make_axes_locatable(ax1)
cax1 = divider1.append_axes("right", size="5%", pad=0.05)

divider2 = make_axes_locatable(ax2)
cax2 = divider2.append_axes("right", size="5%", pad=0.05)

#Create and remove the colorbar for the first subplot
cbar1 = fig.colorbar(im1, cax = cax1)
fig.delaxes(fig.axes[2])

#Create second colorbar
cbar2 = fig.colorbar(im2, cax = cax2)

plt.tight_layout()

plt.show()

enter image description here

答案 1 :(得分:2)

此解决方案与上述解决方案类似,但不需要创建和丢弃颜色条。

请注意,两种解决方案都存在潜在缺陷:颜色条将使用其中一个颜色网格的颜色图和标准化。如果两者都相同,则不是问题。

ImageGrid class看起来像你想要的东西:

from mpl_toolkits.axes_grid1 import make_axes_locatable
fig = plt.figure(1, (4., 4.))
ax = plt.subplot(1,1,1)
divider = make_axes_locatable(ax)

cm = plt.pcolormesh(rand1)
ax.set_aspect('equal')

cax = divider.append_axes("right", size="100%", pad=0.4)
plt.pcolormesh(rand2)
cax.set_aspect('equal')

sm = plt.cm.ScalarMappable(cmap=cm.cmap, norm=cm.norm)
sm._A = []

cax = divider.append_axes("right", size="10%", pad=0.1)
plt.colorbar(sm, cax=cax)
None # Prevent text output

答案 2 :(得分:0)

尽管公认的解决方案有效,但它相当笨拙。我认为更简洁的方法是使用 GridSpec。它还可以更好地扩展到更大的网格。

import numpy
import matplotlib.pyplot as plt
import matplotlib

nb_cols = 5
data = numpy.random.random((10, 10))

fig = plt.figure()
gs = matplotlib.gridspec.GridSpec(1, nb_cols)        
axes = [fig.add_subplot(gs[0, col], aspect="equal") for col in range(nb_cols)]

for col, ax in enumerate(axes):
    im = ax.pcolormesh(data, vmin=data.min(), vmax=data.max())
    if col > 0:
        ax.yaxis.set_visible(False)

fig.colorbar(im, ax=axes, pad=0.01, shrink=0.23)

enter image description here

相关问题