6

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.

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:

figimage not showing

As you can see, this first plot shows fine, but the second one does not. What am I doing wrong?

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

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

2 Comments

Oh, I see. figimage is primarily for rendering backgrounds then? Your suggestion works a charm (although I don't fully understand the need for the subplots), thanks!
@nfelger Exactly, the short answer is that figimage is just for backgrounds. As for the subplots, there are not completely necessary, you could replace all those commands with plt.xticks([]) (and similar for other commands), but I like coding with fig and axes as I think it makes the code more clear, particularly when you have multiple subplots. If you replace the first command with plt.figure(.......) it does exactly the same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.