figimage
只为当前图形添加背景。如果您没有现有的图形,该命令将不会渲染任何内容。以下代码片段在 IPython Notebook 内部和外部都适用:
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
plt.figure()
x = np.linspace(0, 2 * np.pi, 500)
plt.plot(x, np.sin(x))
data = np.random.randn(500, 500)
plt.figimage(data)
plt.show()
但是,它并没有达到您想要/期望的效果。为了以真实尺寸渲染图像,您必须使用figsize
and dpi
,正如其他人之前尝试过的那样[1] https://stackoverflow.com/questions/13714454/specifying-and-saving-a-figure-with-exact-size-in-pixels [2] https://stackoverflow.com/questions/32884796/matplotlib-padding-between-plot-and-axis [3] https://stackoverflow.com/questions/35429984/how-to-completely-remove-the-white-space-around-a-scatterplot [4] https://stackoverflow.com/questions/11837979/removing-white-space-around-a-saved-image-in-matplotlib:
data = np.random.randn(500, 500)
dpi = 80
shape = data.shape
fig, ax = plt.subplots(figsize=(shape[1]/float(dpi), shape[0]/float(dpi)), dpi=dpi, frameon=False)
ax.imshow(data, extent=(0,1,1,0))
ax.set_xticks([]) # remove xticks
ax.set_yticks([]) # remove yticks
ax.axis('off') # hide axis
fig.subplots_adjust(bottom=0, top=1, left=0, right=1, wspace=0, hspace=0) # streches the image and removes margins
fig.savefig('/tmp/random.png', dpi=dpi, pad_inches=0, transparent=True) # Optional: save figure
fig.show()