【问题标题】:Cropping matplotlib picture in subplot在子图中裁剪 matplotlib 图片
【发布时间】:2019-04-03 19:56:43
【问题描述】:

使用 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)])

这是丑陋的结果。

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

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

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

    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
    

    结果:

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

    更新

    @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()
    

    产量:

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

    【讨论】:

    • 复制选择rows=1; columns = 6
    • 好的我很想结束我自己的问题,因为它是以前的变量留在内存(行、列)中的结果,但我不能。但是有一个问题悬而未决——为什么第三根香蕉有偏移量?我猜matplotlib子图格式是根据图片的中心,而不是最左边的部分?
    • 我想要的行为是通过将图锚定在最西端 ax = fig.add_subplot(1, 3,i); ax.set_anchor('W')。所以我的问题的重点是我的旧值列在内存中(玩 jupyter notebook,经典错误)。我建议你们关闭我的问题,因为我不能
    • 您的问题收到了一个被赞成和接受的答案。问题本身也被赞成。您不能删除得分为正的问题或答案得分为正的问题。版主可以删除它们,但他们通常不会这样做,因为至少有一个人认为此问答很有价值。
    猜你喜欢
    • 2012-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-02
    • 1970-01-01
    • 2016-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多