在子图之外放置多个颜色条(matplotlib)

问题描述 投票:0回答:2

我有一个包含多个子图行的图形,它们都共享一个 x 轴。 有些行需要颜色条,但其他行不需要。 如果我只使用颜色条功能,子图将会错位。 如何将颜色条放置在子图之外,以便所有行仍然对齐?

python matplotlib subplot colorbar imshow
2个回答
3
投票

我做了一个可能有帮助的功能:

import numpy as np
from matplotlib import pyplot as plt

#function to add colorbar for imshow data and axis
def add_colorbar_outside(im,ax):
    fig = ax.get_figure()
    bbox = ax.get_position() #bbox contains the [x0 (left), y0 (bottom), x1 (right), y1 (top)] of the axis.
    width = 0.01
    eps = 0.01 #margin between plot and colorbar
    # [left most position, bottom position, width, height] of color bar.
    cax = fig.add_axes([bbox.x1 + eps, bbox.y0, width, bbox.height])
    cbar = fig.colorbar(im, cax=cax)

#Example code:
x = np.random.random((10, 100))
fig, axes = plt.subplots(5,1, sharex = True)
im = axes[0].imshow(x, cmap = "Reds", aspect="auto", origin="lower")
add_colorbar_outside(im, axes[0])
im2 = axes[2].imshow(x, cmap = "coolwarm", aspect="auto", origin="lower")
add_colorbar_outside(im2, axes[2])
plt.show()


0
投票

sharex=True
参数应该足以解决您的问题。 即
fig, axes = plt.subplots(3,1, sharex = True)
在你的情况下。

Matplotlib 现在有关于如何排列颜色条的良好文档:https://matplotlib.org/stable/users/explain/axes/colorbar_placement.html

© www.soinside.com 2019 - 2024. All rights reserved.