Create Multipage PDF in matplotlib without drawing figure on desktop - python

In the following example code...
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
with PdfPages('multipage_pdf.pdf') as pdf:
for i in range(10):
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter([0, 1, 2], [0, 1, 2])
pdf.savefig()
plt.close()
... every single plot pops up a windows with the actual canvas. Is there an elegant solution to skip the actual drawing of the canvas on the screen and draw the plot directly into a multipage pdf?
PS: Problem only caused when running code within spyder, so related to spyder and not to anything else. Running code directly using python does not cause this popping up of windows.

I think what you are looking for is to clear the figure.
first_page = plt.figure(figsize=(11.69, 8.27))
first_page.clf()
Check out the documentation:
https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.clf.html
Some examples:
https://www.programcreek.com/python/example/102298/matplotlib.pyplot.clf

The problem did not arise from matplotlib or anything similar, but just running the code from within Spyder caused this problem. Running the code using python directly does not cause the issues I had before.

Related

I've got some problems of iteration with my animation function (matplotlib.animation/Python)

I'm trying to create an animated histogram for work, using matplotlib.animation, but animation.FuncAnimation is not functioning properly : when using this code, that i found on the official documentation,
"""
A simple example of an animated plot
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig, ax = plt.subplots()
x = np.arange(0, 2*np.pi, 0.01)
line, = ax.plot(x, np.sin(x))
def animate(i):
print(i)
line.set_ydata(np.sin(x + i/10.0)) # update the data
return line,
# Init only required for blitting to give a clean slate.
def init():
line.set_ydata(np.ma.array(x, mask=True))
return line,
ani = animation.FuncAnimation(fig, animate, np.arange(1, 200),init_func=init,interval=25, blit=True)
plt.show()
I get as final result the graph created by init() function (an empty graph also), but no animate iterations. Furthermore, I tested other codes, which practically gave me the same result : i get the initialization, or the first frame, but not more. matplotlib and matplotlib.animation are installed, everything seems to be ok, except it doesn't work. Have someone an idea how to fix it ? (Thank you in advance :) !)
I had the same issue working with Jupyter notebook and I solved it by inserting the line
%matplotlib notebook
in the code.
It may be that IPython inside your Spyder is configured to automatically use the inline backend. This would show your plots inside the console as png images. Of course png images cannot be animated.
I would suggest not to use IPython but execute the script in a dedicated Python console. In Spyder, go to Run/Configure.. and set the option to new dedicated Python console.

How can I use the display() function in Microsoft Azure Notebook

I am unable to display the .png file created by pyplot. I created the file in Microsoft Azure Jupyter Notebook. os.listdir() returns xx.png, so I know that the file was created. Yet, display(Image("xx.png")) does not show the image. I have read about ten related posts on stackoverflow and tried numerous variations of the command, but nothing works.
When I reproduce the problem on my local computer it works fine.
This question is a re-write of a previous question that was marked as duplicate and left to die. I hope that this post will make the question easier to understand.
Following is the code used to create the file:
from IPython.display import display
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import os
y = [2,4,6,8,10,12,14,16,18,20]
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(x, y, label='$y = numbers')
plt.title('Legend inside')
ax.legend()
fig.savefig('xx.png')
There are two ways given the code you have to show the image.
1) You can call %matplotlib inline at the top of the notebook. This will inline graphics and you will see the image by calling fig
2) You can from IPython.display import Image and Image('xx.png') and the image should be displayed.
It appears you are missing an import statement, try :
from Ipython.display import Image
display(Image("xx.png"))

How to show matplotlib plot from a figure object

My code contains the following lines:
from matplotlib.figure import Figure
figure = Figure(figsize=(10, 5), dpi=dpi)
How can I get matplotlib to show this figure? I also show it embedded in tkinter, which workes fine. However I would also be able to show it in the standard matplotlib window. But I can't for the life of me get it to work.
According to AttributeError while trying to load the pickled matplotlib figure, a simple workaround is:
fig = plt.Figure(...)
......
managed_fig = plt.figure(...)
canvas_manager = managed_fig.canvas.manager
canvas_manager.canvas.figure = fig
fig.set_canvas(canvas_manager.canvas)
Note that I encountered "'Figure' object has no attribute '_original_dpi'" in my environment. Not sure if it's some compatibility issue between my PyPlot and the PyQt5. Just did a hack:
fig._original_dpi = 60
to get around this. Not sure if there are any better solutions.
I usually use matplotlib's pyplot for immediate generation (or produce images in jupyter notebooks). This would look like the following:
import matplotlib.pyplot as plt
figure = plt.figure(figsize=(10, 5), dpi=dpi)
plt.show()
This shows the (blank) figure as desired.

Close pyplot figure using the keyboard on Mac OS X

Is there a way to close a pyplot figure in OS X using the keyboard (as far as I can see you can only close it by clicking the window close button)?
I tried many key combinations like command-Q, command-W, and similar, but none of them appear to work on my system.
I also tried this code posted here:
#!/usr/bin/env python
import matplotlib.pyplot as plt
plt.plot(range(10))
def quit_figure(event):
if event.key == 'q':
plt.close(event.canvas.figure)
cid = plt.gcf().canvas.mpl_connect('key_press_event', quit_figure)
plt.show()
However, the above doesn't work on OS X either. I tried adding print statements to quit_figure, but it seems like it's never called.
I'm trying this on the latest public OS X, matplotlib version 1.1.1, and the standard Python that comes with OS X (2.7.3). Any ideas on how to fix this? It's very annoying to have to reach for the mouse every time.
This is definitely a bug in the default OS X backend used by pyplot. Adding the following two lines at the top of the file switches to a different backend that works for me, if this helps anyone else.
import matplotlib
matplotlib.use('TKAgg')
I got around this by replacing
plt.show()
with
plt.show(block=False)
input("Hit Enter To Close")
plt.close()
A hack at its best, but I hope that helps someone
use interactive mode:
import matplotlib.pyplot as plt
# Enable interactive mode:
plt.ion()
# Make your plot: No need to call plt.show() in interactive mode
plt.plot(range(10))
# Close the active plot:
plt.close()
# Plots can also be closed via plt.close('all') to close all open plots or
# plt.close(figure_name) for named figures.
Checkout the "What is interactive mode?" section in this documentation
Interactive mode can be turned off at any point with plt.ioff()
When you have focus in the matplotlib window, the official keyboard shortcut is ctrl-W by this:
http://matplotlib.org/1.2.1/users/navigation_toolbar.html
As this is a very un-Mac way to do things, it is actually cmd-W. Not so easy to guess, is it?
If you are using an interactive shell, you can also close the window programmatically. See:
When to use cla(), clf() or close() for clearing a plot in matplotlib?
So, if you use pylab or equivalent (everything in the same namespace), it is just close(fig). If you are loading the libraries manually, you need to take close from the right namespace, for example:
import matplotlib.pyplot as plt
fig = plt.figure()
plt.plot([0,1,2],[0,1,0],'r')
fig.show()
plt.close(fig)
The only catch here is that there is no such thing as fig.close even though one would expect. On the other hand, you can use plt.close('all') to regain your desktop.

Matplotlib figures not changing interactively - Canopy Ipython

I am trying to use the ipython in canopy with matplotlib to prepare graphs (backend set to qt). I wrote the following code line by line int the terminal
import matplotlib.pyplot as plt
fig = plt.figure()
s = fig.add_subplot(1,1,1)
after the second line I can see the figure being made. However after the third line I do not see the sub plot being created. However If I print fig, the sub-plot is can be seen both inline and in the figure window created. This sub-plot also magically appears if I try to zoom. Similar thing happens every time i plot something on the figure. The old version is displayed till I either print the figure or if i try to modify the view using the GUI tools. This is really annoying. It would be great if someone could tell me where the problem is.
Edit: Tried using fig.show() which does not work. Also when I use the plt.plot() directly, there seems to be no problem. The problem comes only when i use fig or any of its subplots
type:
fig.show() when you need to update it.
you should try using fig.canvas.draw() instead of using fig.show() when it comes to interactive plots.
import matplotlib.pyplot as plt
fig = plt.figure()
fig.show()
## should show an empty figure ##
s = fig.add_subplot(1,1,1)
fig.show()
## things stay unchanged ##
fig.canvas.draw()
## things should be OK now ##

Categories