matplotlib 如何绘制2D图像并将其投影与轴对齐,使绘图尺寸与图像相比保持较小?

cunj1qz1  于 2023-11-22  发布在  其他
关注(0)|答案(1)|浏览(124)

我正在努力寻找一种方法来保持图像的投影与图像完全对齐(如下图所示),但同时减少它们的维度,以便图像占据大部分的图形空间。

import matplotlib.pyplot as plt
    import matplotlib.gridspec as gridspec
    import matplotlib.image as mpimg
    import numpy as np
    from skimage import data
    img = data.coins()
    h,w = img.shape
    ratio = h/w
    fig = plt.figure(figsize=(8, 8))
    gs = gridspec.GridSpec(2, 2, width_ratios=[1*ratio, 1], height_ratios=[1/ratio, 1])
    ax_center = plt.subplot(gs[1, 1])
    ax_center.imshow(img)
    ax_left = plt.subplot(gs[1, 0])
    ax_left.set_title('Left Plot')
    ax_left.plot(-img.mean(axis=1),range(img.shape[0]))
    ax_top = plt.subplot(gs[0, 1])
    ax_top.plot(img.mean(axis=0))
    ax_top.set_title('Top Plot')
    plt.tight_layout()
    plt.show()

字符串


的数据
基本上,我希望顶部的情节有一个smalle高度和左上角有一个较小的宽度保持他们完美的图像对齐。

zte4gxcn

zte4gxcn1#

您可以执行以下操作(通过设置aspect="auto",图像可能会失真,因此在下面的示例中,我已经适当调整了图形大小以解决此问题):

from matplotlib import pyplot as plt
from skimage import data
import numpy as np

img = np.flipud(data.coins())

shape = img.shape
fwidth = 8  # set figure width
fheight = fwidth * (shape[0] / shape[1])  # set figure height

fig, ax = plt.subplots(
    2,
    2,
    sharex="col",
    sharey="row",
    width_ratios=[0.2, 1],  # set left subplot to be 20% width of image
    height_ratios=[0.2, 1],  # set top subplot to be 20% height of image
    figsize=[fwidth + 0.2 * fheight, fheight + 0.2 * fwidth],
)

# you need aspect="auto" to make sure axes align (although this will distort the image!)
ax[1, 1].imshow(img, aspect="auto")

ax[1, 0].plot(-img.mean(axis=1), range(img.shape[0]))
ax[1, 0].set_title('Left Plot')

ax[0, 1].plot(img.mean(axis=0))
ax[0, 1].set_title('Top Plot')

ax[1, 1].set_xlim([0, img.shape[1] - 1])
ax[1, 1].set_ylim([0, img.shape[0] - 1])

ax[0, 0].axis("off")

fig.tight_layout()
plt.show()

字符串
这产生:


的数据

相关问题