首页 > 解决方案 > 多个子图大小一致的 Matplotlib 颜色条

问题描述

我正在尝试创建一个包含几个具有公共颜色条的子图的图形。子图必须具有相等的纵横比,并且颜色条必须具有与子图相同的高度。但是,我无法获得与其他子图高度相同的窄色条。

我正在使用这个配方生成一个颜色条,其范围适用于所有子图;因此这个问题在 MWE 中没有解决。

使用轴分隔器配方附加颜色条时,子图的高度会因纵横比而变化。

这是MWE

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

import itertools as it
import numpy as np

mean = [0, 0]
cov = [[1, 0.5],
       [0.5, 4]]
n_samples = 10000
hrange = [[-5,5],[-5,5]]
bins = 20

# RANDOM DATA
Z_random = np.random.multivariate_normal(mean, cov, size=n_samples)
Z, xedges, yedges = np.histogram2d(Z_random[:,0], Z_random[:,1], bins=bins, range=hrange, normed=True)
X, Y = np.meshgrid(xedges, yedges)

# PLOT PCOLORMESHS
fig, axes = plt.subplots(2,3, subplot_kw=dict(aspect="equal"))
axes = dict(enumerate(fig.get_axes(),1))

for i,ax in axes.items():
    if i==6:
        break
    pcm = ax.pcolormesh(X,Y,Z)

# PLOT COLORBAR
divider = make_axes_locatable(axes[6])
cax = divider.append_axes("left", size="15%", pad=0.0)
fig.colorbar(pcm, cax=cax, label=r"Colorbar label")

MWE

我可以在完整的子图上绘制颜色条,在这种情况下高度是正确的,但它的宽度要吸引人。

有没有人有一个“强大”的解决方案,即没有手动摆弄持有颜色条的子图的尺寸?

提前致谢!

编辑:增加颜色条的宽度以强调它的高度变小。

标签: pythonmatplotlib

解决方案


如果唯一的目的是让颜色条的高度与其水平邻居正确对齐,那么这个答案的最后一个解决方案会有所帮助。

但是,如果您还希望颜色条与其顶部的图左对齐,则解决方案可能更复杂。

您可以使用回调来明确设置颜色条的位置,如下所示:

from matplotlib import pyplot as plt
from matplotlib.transforms import Bbox
import numpy as np

mean = [0, 0]
cov = [[1, 0.5],
       [0.5, 4]]
n_samples = 10000
hrange = [[-5,5],[-5,5]]
bins = 20

# RANDOM DATA
Z_random = np.random.multivariate_normal(mean, cov, size=n_samples)
Z, xedges, yedges = np.histogram2d(Z_random[:,0], Z_random[:,1], bins=bins, range=hrange, normed=True)
X, Y = np.meshgrid(xedges, yedges)

# PLOT PCOLORMESHS
fig, axes = plt.subplots(2,3, subplot_kw=dict(aspect="equal"))

for i,ax in enumerate(axes.flat):
    if i==5:
        break
    pcm = ax.pcolormesh(X,Y,Z)

# PLOT COLORBAR
cax = fig.add_axes([0.6,0.01,0.1,0.4])
fig.colorbar(pcm, cax=cax, label=r"Colorbar label")

def align_cbar(cax, hax, vax):
    hpos = hax.get_position()
    vpos = vax.get_position()
    bb = Bbox.from_extents(vpos.x0, hpos.y0, vpos.x0+vpos.width*.05,hpos.y1)
    if cax.get_position() != bb:
        cax.set_position(bb)
        fig.canvas.draw_idle()

align_cbar(cax, axes[1,1], axes[0,2])    
fig.canvas.mpl_connect("draw_event", lambda x: align_cbar(cax, axes[1,1], axes[0,2]))

plt.show()

在此处输入图像描述


推荐阅读