matplotlib:在Jupyter笔记本中未显示figimage [英] matplotlib: figimage not showing in Jupyter notebook
问题描述
我正在尝试以真实尺寸(而不是缩放或拉伸)渲染图像,而使用matplotlib做到这一点的最简单方法似乎是figimage
.
I'm trying to render an image at its true dimensions (not scaled or stretched) and the easiest way to do this with matplotlib seems to be figimage
.
但是,当我尝试在Jupyter笔记本中使用它时,该图没有显示.其他图显示很好,这似乎只影响figimage
:
However, when I try to use it in a Jupyter notebook, the figure doesn't show. Other plots show fine, this only seems to affect figimage
:
如您所见,第一幅图显示得很好,而第二幅图则没有.我在做什么错了?
As you can see, this first plot shows fine, but the second one does not. What am I doing wrong?
当我在IPython shell中运行以下代码时,该图将按预期显示,那么也许是我的Jupyter设置存在问题?
When I run the following code in an IPython shell , the figure shows up as expected, so maybe it's a problem with my Jupyter setup?
import matplotlib
from matplotlib import pyplot as plt
import numpy as np
x = np.linspace(0, 2*np.pi, 500)
plt.plot(x, np.sin(x))
plt.show()
data = np.random.random((500,500))
plt.figimage(data)
plt.show()
推荐答案
figimage
仅向当前图形添加背景.如果您还没有现有的图形,该命令将不会渲染任何内容.以下代码段将在IPython Notebook的内部和外部均适用:
figimage
only adds a background to the current figure. If you don't have an already existing figure, the command wont render anything. The following snippet will work both inside and outside 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
和dpi
进行操作,就像其他人以前尝试 [2] [ 3] [4] :
However, it doesn't do what you want/expect. In order to render an image in its true dimensions you would have to play with figsize
and dpi
, as others have attempted previously [1] [2] [3] [4]:
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()
这篇关于matplotlib:在Jupyter笔记本中未显示figimage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!