Matplotlib savefig method saves empty image [duplicate] - python

This question already has answers here:
Saving a figure after invoking pyplot.show() results in an empty file
(4 answers)
Closed 2 years ago.
I'm following an example from a textbook covering Matplotlib. The following code saves a graph when run through command-line Python, but when ran through Jupyter it saves an empty image. Why is that happening?
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
fig = plt.figure()
plt.plot(x, np.sin(x), '-')
plt.plot(x, np.cos(x), '--')
fig.savefig('image.png')

I've tried running the same code in Jupyter but without your first line:
#%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
fig = plt.figure()
plt.plot(x, np.sin(x), '-')
plt.plot(x, np.cos(x), '--')
fig.savefig(r'C:\Users\new_folder\image.png')
Make sure you specify a correct path for the output image. This way is working for me just fine and I get the .png image

Related

Why doesn't the show() function in matplotlib.pyplot work more than once for the same Axes object?

Out of pure curiosity, I would love to know why the final plt.show() does not display both plots on ax. Only the first plt.show() seems to do anything, because only the plot of y = sin(x) shows up. Here is the code sample:
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
x = np.linspace(1, 100, 10)
ax.plot(x, np.sin(x))
plt.show()
ax.plot(x, x)
plt.show()
Appreciate any help on this, because it bugs me to not understand why this is the case, even after a lot of searches. PS: I know that the code is useless and dumb, but I would still like to know for future use.
Your code
## load libraries
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
x = np.linspace(1, 100, 10)
## assign first plot
ax.plot(x, np.sin(x))
#plt.show()
## assign second plot
ax.plot(x, x)
## render the plots
plt.show()
One reason why plt.show() didn't 'show' more than once.
You are using subplots.
Your plots are on the same axes
plt.show() display all open figures. Your ax.plot(x, np.sin(x)) will be shown and the figure closed. The second is on the same ax and will not be shown anymore.
Documentation: matplotlib.pyplot.show()
[Alternate]
If however you call plt.plot() separately, (without subplots axes), you would get two plots; each with its own dimensions.
PS: below works in Jupyter (mybinder)
## load libraries
import matplotlib.pyplot as plt1
import numpy as np
x = np.linspace(1, 100, 10)
## first plot
plt1.plot(x, np.sin(x))
## render first plot
plt1.show()
Followed by
## second plot
plt1.plot(x, x)
## render the plot
plt1.show()
Clarity from the documentation: matplotlib.pyplot is a state-based interface to matplotlib
[Updated]
#JohanC lumping up the explanatory code and the alternate code.
The explanation 1, 2, and 3 remains.
The alternate code remain. or
OP can put the two plots on their own ax, and have plt.show each.
I didn't intend including this before. However, for completeness:
## load libraries
import matplotlib.pyplot as plt
import numpy as np
## tuple of desired two axes
## unpack AxesSubplot on two rows
fig, (ax1, ax2), = plt.subplots(nrows=2)
## assign variable
x = np.linspace(1, 100, 10)
## assign first plot
ax1.plot(x, np.sin(x))
#plt.show()
## assign second plot
ax2.plot(x, x)
## render the plots
## Rendering might not be 'smooth' in Jupyter
plt.show()

Generate more plots separate in figure in one script in python

First of all, I apologies if this question was already asked and answered, I haven't found anything really specific about this so if you did, please share and I will delete this post.
What I would like to do is simply generate more separate plots after one another in separate figure in python, because I have an exercise sheet and the a) is to plot a poisson distribution and the b) is to plot a binomial distribution and so ever with c) and d), and I would like that the plots are gathered together in the same script but in separate figure.
I tried as simple as create a sin(x) and a cos(x) plot after one another but it didn't work, the sin and cos were displaying in the same plot.. My code was:
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = plt.plot(np.sin(x))
ax2 = plt.plot(np.cos(x))
ax1.set_xlabel('Time (s)')
ax1.set_title('sin')
ax1.legend()
ax2.set_xlabel('Time (s)')
ax2.set_title('cos')
ax2.legend()
plt.show()
Could anyone help me ?
How about this?
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 100)
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212, sharex=ax1)
ax1.plot(np.sin(x))
ax2.plot(np.cos(x))
plt.show()
I suggest you should read a simple tutorial about subplots.
EDIT:
To create separate figures:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 100)
plt.figure()
plt.plot(np.sin(x))
plt.figure()
plt.plot(np.cos(x))
plt.show()

matplotlib plot points look fuzzy in Python, sharp in IPython

I'm really confused here; the same code in Python and in IPython Notebook produces two different PNG files with savefig:
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(5,4))
ax = fig.add_subplot(1,1,1)
abc = np.random.uniform(size=(50000,3))
print abc.shape
x = (2*abc[:,0]-abc[:,1]-abc[:,2])/3.0
y = (abc[:,1]-abc[:,2])/np.sqrt(3)
ax.plot(x,y,'.',markersize=0.25)
ax.set_aspect('equal')
ax.set_xlabel('x')
ax.set_ylabel('y')
with open('/tmp/screenshots/foo.png','wb') as f:
fig.savefig(f, format='png')
IPython Notebook:
Python:
It's the same PC with the same version of Python in both cases. Is there a way to get the image formatting in IPython using both methods? The Python version produces fuzzy dots and looks poor.
Argh -- I figured it out, the dpi parameter gets chosen somehow differently in the two cases, and if I force it to dpi=72 then it looks nice:
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(5,4))
ax = fig.add_subplot(1,1,1)
abc = np.random.uniform(size=(50000,3))
print abc.shape
x = (2*abc[:,0]-abc[:,1]-abc[:,2])/3.0
y = (abc[:,1]-abc[:,2])/np.sqrt(3)
ax.plot(x,y,'.',markersize=0.25)
ax.set_aspect('equal')
ax.set_xlabel('x')
ax.set_ylabel('y')
with open('/tmp/screenshots/foo.png','wb') as f:
fig.savefig(f, format='png', dpi=72)

Shading behind the plot in org-mode babel and matplotlib

Consider the following python code block in org-mode with babel:
#+begin_src python :results none
import numpy as np
import matplotlib as mpl
from matplotlib import pyplot as plt
graylevel = 0.75
mpl.rc('figure', facecolor = (graylevel, graylevel, graylevel), edgecolor ='r')
X = np.linspace(0, 7, 1024)
plt.plot(X, np.sin(X))
plt.plot(X, np.cos(X))
plt.draw()
plt.show()
#+end_src]
In a pop-up window, this produces a plot with a gray background
but, when putting the plot in a file, again in org-mode (only the last couple of lines are different)
#+begin_src python :results file
import numpy as np
import matplotlib as mpl
from matplotlib import pyplot as plt
graylevel = 0.75
mpl.rc('figure', facecolor = (graylevel, graylevel, graylevel), edgecolor ='r')
X = np.linspace(0, 7, 1024)
plt.plot(X, np.sin(X))
plt.plot(X, np.cos(X))
plt.draw()
plt.savefig('test.png')
return 'test.png'
#+end_src
#+RESULTS:
[[file:test.png]]
The gray background is gone
I do need the gray backgrounds for exporting my plots from org-mode because I need the plots set off from the surrounding document.
I don't know if this is an issue with matplotlib, with org-mode, with python, with my machine, or with me. I hope someone can repro this example or perhaps just knows the answer.
I don't think this is an issue with org-mode, but is the same issue discussed here.
This is the solution to your troubles:
plt.savefig('test.png', facecolor=(graylevel, graylevel, graylevel))

how to fix Blank graphs when using figure module in PyDev?

I have a problem when making graphs using matplotlib,
for some simple graphs the library works fine, for example:
import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.show()
but when I use figure module, i get blank figures, like this
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
x = np.linspace(0, 10, 200)
y = np.sin(x)
ax.plot(x, y, 'r-', linewidth=2, label=r'$y=\sin(x)$', alpha=0.6)
ax.legend(loc='upper center')
plt.show()
I've tried the same code in a a different python editor or using the shell and it woks fine. I'm using :
Windows,
PyDev v4.2,
python v2.7.10

Categories