I have a code that creates about 50 graphs based on groupby
. The code looks like this:
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
with PdfPages('foo.pdf') as pdf:
for i, group in df.groupby('station_id'):
plt.figure()
fig=group.plot(x='year', y='Value',title=str(i)).get_figure()
pdf.savefig(fig)
This is saving only one figure, (the last one in my series) when I would like all of my figures to be stored into one pdf. Any help would be appreciated.
To save the file in PDF format, use savefig() method where the image name is myImagePDF. pdf, format = ”pdf”. To show the image, use the plt. show() method.
Create a user-defind function, save_multi_image, and call it to save all the open matplotlib figures in one file at once. Create a new PdfPages object, pp. Get the number of open figures. Iterate the opened figures and save them into a file.
To draw multiple plots using the subplot() function from the pyplot module, you need to perform two steps: First, you need to call the subplot() function with three parameters: (1) the number of rows for your grid, (2) the number of columns for your grid, and (3) the location or axis for plotting.
There is an indentation error in your code. Since your plotting command was not in the loop, it will only create the last plot.
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
with PdfPages('foo.pdf') as pdf:
for i, group in df.groupby('station_id'):
plt.figure()
fig=group.plot(x='year', y='Value',title=str(i)).get_figure()
pdf.savefig(fig)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With