python - 在子图中裁剪 matplotlib 图片

标签 python matplotlib

使用 python 和 matplotlib 裁剪图片似乎很容易(请参阅 this SO question )。然而,当在带有子图的图中裁剪一个图形时,图片的整体大小会发生变化。我正在粘贴一个示例和不需要的结果:

import matplotlib.pyplot as plt
import matplotlib.image as mpimg

img = mpimg.imread('http://res.freestockphotos.biz/pictures/15/15912-illustration-of-a-banana-pv.png')
fig=plt.figure(figsize=(18, 4))

for i in range(1, 4):
    fig.add_subplot(rows, columns, i)
    plt.imshow(img)
    if i > 2:
        plt.imshow(img[:img.shape[0],:int(img.shape[1]/2)])

这是丑陋的结果。

enter image description here

如何让所有图片具有相同的垂直尺寸?

最佳答案

您发布的代码不适合我。 未定义。我跑了:

import matplotlib.pyplot as plt
import matplotlib.image as mpimg

img = mpimg.imread('http://res.freestockphotos.biz/pictures/15/15912-illustration-of-a-banana-pv.png')
fig = plt.figure(figsize=(18, 4))

rows = 1 # I added this
columns = 3 # and this
for i in range(1, 4):
    fig.add_subplot(rows, columns, i)
    plt.imshow(img)
    if i > 2:
        plt.imshow(img[:img.shape[0], :int(img.shape[1] / 2)])

plt.show() # and this

结果:

output

所以我无法重现这个问题(并假设其他人也不能)。也许这段代码解决了您的问题?祝你好运!

更新

在 @ImportanceOfBeingErnest 评论的列应该是 6 之后,我摆弄了它,也许您正在寻找 extent 设置?我跑了

import matplotlib.pyplot as plt
import matplotlib.image as mpimg

img = mpimg.imread('http://res.freestockphotos.biz/pictures/15/15912-illustration-of-a-banana-pv.png')
fig = plt.figure(figsize=(18, 4))

rows = 1
columns = 6
for i in range(1, 4):
    fig.add_subplot(rows, columns, i)
    if i > 2:
        plt.imshow(img[:img.shape[0], :int(img.shape[1] / 2)], extent=(0, 50, 0, 50))
    else:
        plt.imshow(img, extent=(0, 50, 0, 50))
plt.tight_layout()
plt.show()

产量:

new output

它基本上只是拉伸(stretch)图像以适应您指定的范围范围,我相信这本质上只是纵横比。这是否是扭曲您的图像以适应与其他图像相同的尺寸的理想效果?

关于python - 在子图中裁剪 matplotlib 图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55503322/

相关文章:

python - 使用pylab同时显示两个png图像

Python:将打印引号、破折号等替换为对应的 ascii 字符

python - 如何将用户输入转换为 python 2.7 中的函数

python - 根据其他列 pandas 填充缺失值

python - 如何在 Python/Jupyter 笔记本中省略 matplotlib 打印输出?

python - 如何将图形(3x3 子图)插入 matplotlib python 的子图中

python - Matplotlib:将不同的散点标记分组在同一个图例下

python - Pygame (A bit racey) 游戏错误

python - 当我将多个数据帧存储在数据帧列表中并且我记忆起其中一个时,有没有办法格式化输出的列标题?

python - 如何将样本的 x 位置与 matplotlib.pyplot 中的表列对齐?