【问题标题】:matplotlib: Stretch image to cover the whole figurematplotlib:拉伸图像以覆盖整个图形
【发布时间】:2012-03-27 09:01:18
【问题描述】:

我已经习惯了使用 matlab 并且现在尝试转换 matplotlib 和 numpy。 matplotlib 中有没有办法让您绘制的图像占据整个图形窗口。

import numpy as np
import matplotlib.pyplot as plt

# get image im as nparray
# ........

plt.figure()
plt.imshow(im)
plt.set_cmap('hot')

plt.savefig("frame.png")

我希望图像保持其纵横比并缩放到图形的大小......所以当我执行 savefig 时,它的大小与输入图形的大小完全相同,并且完全被图像覆盖。

谢谢。

【问题讨论】:

标签: matplotlib figure


【解决方案1】:

这是一个最小的面向对象的解决方案:

fig = plt.figure(figsize=(8, 8))
ax = fig.add_axes([0, 0, 1, 1], frameon=False, xticks=[], yticks=[])

测试一下

ax.imshow([[0]])
fig.savefig('test.png')

保存一个统一的紫色块。

编辑:正如@duhaime 在下面指出的那样,这要求图形与轴具有相同的方面。

如果您希望轴调整为图形大小,请将aspect='auto' 添加到imshow

如果您希望图形调整大小以调整到轴的大小,请添加

from matplotlib import tight_bbox
bbox = fig.get_tightbbox(fig.canvas.get_renderer())
tight_bbox.adjust_bbox(fig, bbox, fig.canvas.fixed_dpi) 

imshow 调用之后。这是 matplotlib's tight_layout functionality 的重要部分,它被 Jupyter 的渲染器等隐式调用。

【讨论】:

  • 这仅适用于方形图像。试试figsize=(2, 8)
  • 为此添加了修复程序。
【解决方案2】:

我使用以下 sn-p 进行了此操作。

#!/usr/bin/env python
import numpy as np
import matplotlib.cm as cm
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
from pylab import *

delta = 0.025
x = y = np.arange(-3.0, 3.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
Z = Z2-Z1  # difference of Gaussians
ax = Axes(plt.gcf(),[0,0,1,1],yticks=[],xticks=[],frame_on=False)
plt.gcf().delaxes(plt.gca())
plt.gcf().add_axes(ax)
im = plt.imshow(Z, cmap=cm.gray)

plt.show()

请注意,两侧的灰色边框与轴的纵横比有关,可通过设置 aspect='equal'aspect='auto' 或您的比率来更改。

正如珍亚在cmets中提到的Similar StackOverflow Question 提到savefig的参数bbox_inches='tight'pad_inches=-1或pad_inches=0

【讨论】:

  • 加一个 bbox_inches = 'tight' 真正回答了这个问题。
【解决方案3】:

您可以使用如下功能。 它会根据您想要的分辨率(以 dpi 为单位)计算所需的图形尺寸(以英寸为单位)。

import numpy as np
import matplotlib.pyplot as plt

def plot_im(image, dpi=80):
    px,py = im.shape # depending of your matplotlib.rc you may 
                              have to use py,px instead
    #px,py = im[:,:,0].shape # if image has a (x,y,z) shape 
    size = (py/np.float(dpi), px/np.float(dpi)) # note the np.float()

    fig = plt.figure(figsize=size, dpi=dpi)
    ax = fig.add_axes([0, 0, 1, 1])
    # Customize the axis
    # remove top and right spines
    ax.spines['right'].set_color('none')
    ax.spines['left'].set_color('none')
    ax.spines['top'].set_color('none')
    ax.spines['bottom'].set_color('none')
    # turn off ticks
    ax.xaxis.set_ticks_position('none')
    ax.yaxis.set_ticks_position('none')
    ax.xaxis.set_ticklabels([])
    ax.yaxis.set_ticklabels([])

    ax.imshow(im)
    plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-20
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-01
    • 1970-01-01
    • 2013-08-22
    相关资源
    最近更新 更多