I am working in Jupyter Notebook and I have a function that generates multiple plots upon being called. I want to directly save all plots from this function call under one pdf. Is there ways to do that?
Any help will be much appreciated!
Alison
You can use PDFPages to save all of your plots into a pdf. You can try the following example and implement it similarly in your code:
You can create a plotGraph function:
def plotGraph(X,Y):
fig = plt.figure()
### Plotting code ###
return fig
Then use that to get your and place them in your pdf.
from matplotlib.backends.backend_pdf import PdfPages
plot1 = plotGraph(graph1, label1)
plot2 = plotGraph(graph2, label2)
plot3 = plotGraph(graph3, label3)
pp = PdfPages('foo.pdf')
pp.savefig(plot1)
pp.savefig(plot2)
pp.savefig(plot3)
pp.close()
If you are okay with saving it as a PNG file with all the plots you can try the following:
from matplotlib import pyplot as plt
fig = plt.figure()
axis1 = fig.add_subplot(211)
axis1.plot(range(10))
axis2 = fig.add_subplot(212)
axis2.plot(range(10,20))
fig.savefig('allplots.png')
This basically creates subplots and saves all your plots in 1 png file.
Related
I have a function that creates matplotlib figure
def make_figure(some_input):`
fig,ax = plt.subplots(figsize=(10,10))
....
....
return fig,ax
I then make some figures
for x in input:
fig,ax = make_figure(x)
fig.savefig(f'name{number}.png')
How can I save those figures in a movie file?
I wanted to do animation with Matplotlib, but I cannot get it working with my "make_figure" function.
thx!
I want to save 2 figures created at different parts of a script into a PDF using PdfPages, is it possible to append them to the pdf?
Example:
fig = plt.figure()
ax = fig_zoom.add_subplot(111)
ax.plot(range(10), range(10), 'b')
with PdfPages(pdffilepath) as pdf:
pdf.savefig(fig)
fig1 = plt.figure()
ax = fig_zoom.add_subplot(111)
ax.plot(range(10), range(2, 12), 'r')
with PdfPages(pdffilepath) as pdf:
pdf.savefig(fig1)
Sorry, that's a lame question. We just shouldn't use the with statement.
fig = plt.figure()
ax = fig_zoom.add_subplot(111)
ax.plot(range(10), range(10), 'b')
# create a PdfPages object
pdf = PdfPages(pdffilepath)
# save plot using savefig() method of pdf object
pdf.savefig(fig)
fig1 = plt.figure()
ax = fig_zoom.add_subplot(111)
ax.plot(range(10), range(2, 12), 'r')
pdf.savefig(fig1)
# remember to close the object to ensure writing multiple plots
pdf.close()
I think that Prashanth's answer can be generalized a bit better, for instance by incorporating it in a for loop, and avoiding the creation of multiple figures, which can generate memory leaks.
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
# create a PdfPages object
pdf = PdfPages('out.pdf')
# define here the dimension of your figure
fig = plt.figure()
for color in ['blue', 'red']:
plt.plot(range(10), range(10), color)
# save the current figure
pdf.savefig(fig)
# destroy the current figure
# saves memory as opposed to create a new figure
plt.clf()
# remember to close the object to ensure writing multiple plots
pdf.close()
None of these options append if the file is already closed (e.g. the file gets created in one execution of your program and you run the program again). In that use case, they all overwrite the file.
I think appending isn't currently supported. Looking at the code of backend_pdf.py, I see:
class PdfFile(object)
...
def __init__(self, filename):
...
fh = open(filename, 'wb')
Therefore, the function is always writing, never appending.
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
# Use plt to draw whatever you want
pp = PdfPages('multipage.pdf')
plt.savefig(pp, format='pdf')
pp.savefig()
# Finally, after inserting all the pages, the multipage pdf object has to be closed.
pp.close()
You can directly do like this if your data is in data frame
#
with PdfPages(r"C:\Users\ddadi\Documents\multipage_pdf1.pdf","a") as pdf:
#insert first image
dataframe1.plot(kind='barh'); plt.axhline(0, color='k')
plt.title("first page")
pdf.savefig()
plt.close()
#insert second image
dataframe2.plot(kind='barh'); plt.axhline(0, color='k')
plt.title("second page")
pdf.savefig()
plt.close()
I'm trying to get my figures in just one pdf page, but I don't know how to do this. I found out that it's possible to save multiple figures in a pdf file with 'matplotlib.backends.backend_pdf', but it doesn't work for just one page.
Has anyone any ideas ? Convert the figures to just one figure ?
You can use matplotlib gridspec to have multiple plots in 1 window
http://matplotlib.org/users/gridspec.html
from matplotlib.gridspec import GridSpec
import random
import numpy
from matplotlib import pyplot as pl
fig = pl.figure(figsize=(12, 16))
G = GridSpec(2,2)
axes_1 = pl.subplot(G[0, :])
x = [random.gauss(3,1) for _ in range(400)]
bins = numpy.linspace(-10, 10, 100)
axes_1.hist(x, bins, alpha=0.5, label='x')
axes_2 = pl.subplot(G[1, :])
axes_2.plot(x)
pl.tight_layout()
pl.show()
You can change the rows and column values and can subdivide the sections.
The PDF backend makes one page per figure. Use subplots to get multiple plots into one figure and they'll all show up together on one page of the PDF.
Here is a solution provided by matplotlib:
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
with PdfPages('foo.pdf') as pdf:
#As many times as you like, create a figure fig and save it:
fig = plt.figure()
pdf.savefig(fig)
....
fig = plt.figure()
pdf.savefig(fig)
VoilĂ
Find a full example here: multipage pdf matplotlib
And by the way, for one figure, you don't need matplotlib.backends.backend_pdf just add pdf extension like so:
plt.savefig("foo.pdf")
I like to use matplotlib to create a PDF and then I will often go in and tweak things with Adobe Illustrator or Inkscape. Unfortunately, when matplotlib saves the figure as a PDF, it combines multiple images into a single object.
For example, the following code
import matplotlib.pyplot as plt
import numpy as np
im = np.random.rand(10, 10) * 255.0
fig = plt.figure()
ax = fig.add_axes([0.1,0.1,0.8,0.8])
ax.imshow(im, extent = [0,10,0,10])
ax.imshow(im, extent = [12,22,0,10])
ax.set_xlim(-2,24)
fig.savefig('images_get_combined.pdf')
creates the following PDF (after I manually converted to a PNG, so I could post it here)
When I open images_get_combined.pdf in Adobe Illustrator, both images are combined into a single image. I cannot move one image relative to the other.
I tried to get around this problem using BboxImage, but as shown in this bug report, BboxImage doesn't play nice with the PDF backend. Perhaps the PDF backend with BboxImage bug will get resolved, but I wondered if there is another way to make the PDF backend save each image separately.
You can try to save as multiple pages PDF:
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
im = np.random.rand(10, 10) * 255.0
with PdfPages('images_get_combined.pdf') as pdf:
fig = plt.figure()
ax = fig.add_axes([0.1,0.1,0.8,0.8])
ax.imshow(im, extent = [0,10,0,10])
pdf.savefig()
plt.close()
fig = plt.figure()
ax = fig.add_axes([0.1,0.1,0.8,0.8])
ax.imshow(im, extent = [12,22,0,10])
pdf.savefig()
plt.close()
See also Multipage PDF example from the matplotlib doc.
I have a loop to generate millions of histograms in python and i need to store them all in one folder in my laptop is there a way to save them all without the need of pressing save button each time a histogram generated?
Thanks
If you're using matplotlib, then what you are looking for is plt.savefig(). The documentation is here: http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.savefig
For example:
import matplotlib.pyplot as plt
import numpy as np
# Some random data:
x = np.random.rand(100)
fig = plt.figure(1) # create a figure instance
ax = fig.add_subplot(111) # and axes
ax.hist(x) # plot the histogram
# plt.show() # this would show the plot, but you can leave it out
# Save the figure to the current path
fig.savefig('test_image.png')