Blank image when saving an imshow matplotlib figure in iPython notebook - python

I'm using iPython notebook w/ matplotlib to display a bunch of images inline, but now it's come time to save a number of these images (think for-loop, i.e. not a small number of images to save). My issue seems to be something to do with how I'm using iPython since I could do this alright when my script was a standalone.
%matplotlib inline
import matplotlib.pyplot as plt
....
grid_z2 = griddata(....)
fig = plt.figure()
ax = fig.add_axes([1,1,1,1])
plt.imshow(grid_z2.transpose(),origin='Lower')
plt.colorbar()
plt.draw()
fig.savefig('slicemap.png')
I have also tried plt.savefig(), fig1 = plt.gcf() before plt.imshow then trying to save fig1... always every single time a blank file.
Any suggestions?

Related

How to show specific axes in a figure

I created a figure which has 2 axes, how can I plot specific axes(eg,ax[0]) rather than plot both axes? When I input fig in the end both axes will appear together. What code should I write if I just want ax[0] be displayed for example?
fig,ax=plt.subplots(2)
x=np.linspace(1,10,100)
ax[0].plot(x,np.sin(x))
ax[1].plot(x,np.cos(x))
fig
I interprete that you are using Jupyter notebook. You may then use the fact that invisble axes parts of a figure will be cropped with the matplotlib inline backend.
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
fig,ax=plt.subplots(2);
x=np.linspace(1,10,100)
ax[0].plot(x,np.sin(x))
ax[1].plot(x,np.cos(x))
Now to only show the second subplot, you can set the first invisible,
ax[0].set_visible(False)
fig
If you then want to only show the first subplot, you need to set it visible again and the second one invisible
ax[0].set_visible(True)
ax[1].set_visible(False)
fig

Matplotlib figsize not respected [duplicate]

This question already has answers here:
Matplotlib and Ipython-notebook: Displaying exactly the figure that will be saved
(2 answers)
Closed 4 years ago.
I want to make a square plot with matplotlib. That is, I want the whole figure to be square. When I use the following code, the width of the resulting image is still a bit larger than the height. Why is matplotlib not respecting the figsize I provide?
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(10, 10))
# When inspecting in browser, reveals 611x580 px image
ax.plot([1,2,3], [1,2,3])
Edit: I display the image inline in a Jupyter notebook, and just use the Chrome developer tools to inspect the image.
That is a problem of jupyter notebook. The figure it shows is a "saved" version, which uses the bbox_inches="tight" option and hence changes the size of the shown image.
One option you have is to save the figure manually to png,
fig.savefig("output.png")
As #EvgenyPogrebnyak commented, the other option is to deactivate the "tight" option in the notebook as
%matplotlib inline
%config InlineBackend.print_figure_kwargs = {'bbox_inches':None}
fig, ax = plt.subplots(figsize=(10, 10))
# When inspecting in browser,
ax.plot([1,2,3], [1,2,3]) # now reveals 720 x 720 px image
as seen in this answer.

mplleaflet in Jupyter - avoid whitespace with notebook mode?

mplleaflet works great with '%matplotlib inline' mode in the Jupyter Notebook, but when enabling '%matplotilib notebook' mode, there's a big chunk of whitespace between the cell and the map. Can this be avoided?
Code:
import matplotlib.pyplot as plt
import mplleaflet
%matplotlib notebook
#some latitudes bracketing seattle
lats = [47.5062,47.7062]
#longitude
lons = [-122.3321]*len(lats)
fig,ax=plt.subplots(figsize=(8,8))
ax.scatter(lons, lats, alpha=0) #invisible data points, just to scale the map
mplleaflet.display(fig=fig)
The output looks like this:
The problem is that there is a figure created which is supposed to be shown in the notebook. However, you do not want to show the mplleaflet figure as an interactive figure with the %matplotlib notebook backend.
One idea is to not use the %matplotlib notebook such that the area where the figure mplleaflet figure would be placed is not filled with the unused figure.
Alternatively use %%capture in order to suppress the output when using %matplotlib notebook. Then call mplleaflet.display in a new non-captured cell:

Reading matplotlib graphs from file

Is it possible to read (say) 4 .jpeg graphs produced by matplotlib into matplotlib again so that they can be replotted as subplots? If so, how would I do it?
If you really want to do it by reading jpeg files of existing plots (noting the comments), one way might be to read in the graphs in with scipy.misc.imread. I've set the axis labels off assuming you saved the original graphs with labels and everything.
import matplotlib.pyplot as plt
from scipy.misc import imread
# Create a figure with 2x2 arranged subplots
fig, ax = plt.subplots(2,2)
# Plot images one by one here
# (Just using the same jpeg file in this example...)
im1 = imread("graph1.jpg")
ax[0,0].imshow(im1)
ax[0,0].axis('off')
ax[0,1].imshow(im1)
ax[0,1].axis('off')
ax[1,0].imshow(im1)
ax[1,0].axis('off')
ax[1,1].imshow(im1)
ax[1,1].axis('off')
fig.show()

How to save Matplotlib.pyplot.loglog to file?

I am trying to generate the log-log plot of a vector, and save the generated plot to file.
This is what I have tried so far:
import matplotlib.pyplot as plt
...
plt.loglog(deg_distribution,'b-',marker='o')
plt.savefig('LogLog.png')
I am using Jupyter Notebook, in which I get the generated graph as output after statement 2 in the above code, but the saved file is blank.
Notice that pyplot has the concept of the current figure and the current axes. All plotting commands apply to the current axes. So, make sure you plot in the right axes. Here is a WME.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.loglog(range(100), 'b-',marker='o')
plt.savefig('test.png') # apply to the axes `ax`

Categories

Resources