The Python Oracle

matplotlib: figimage not showing in Jupyter notebook

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Drifting Through My Dreams

--

Chapters
00:00 Question
01:16 Accepted answer (Score 6)
02:19 Thank you

--

Full question
https://stackoverflow.com/questions/4627...

Question links:
[image]: https://i.stack.imgur.com/dTRMU.png

Accepted answer links:
[[1]]: https://stackoverflow.com/questions/1371...
[[2]]: https://stackoverflow.com/questions/3288...
[[3]]: https://stackoverflow.com/questions/3542...
[[4]]: https://stackoverflow.com/questions/1183...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #matplotlib #jupyter

#avk47



ACCEPTED ANSWER

Score 6


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

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