'Saving multiple plots to one pdf file
I am trying to save multiple plots in one pdf file.
can anyone help with the following code?
what is wrong with this code:
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
import random as rand
pdfFile = PdfPages("output.pdf")
for i in range(10):
xVals = [x for x in range(20)]
yVals = [rand.randint(50,100) for x in xVals]
plt.figure(figsize=(20,10))
fig = plt.plot(xVals , yVals)
plt.xlabel('Data point')
plt.ylabel('Strain [us]')
plt.title(i)
#plt.show()
pdfFile.savefig(fig)
print(i)
pdfFile.close()
Solution 1:[1]
plot returns as list of Line2Ds (in your case just one). From this line you need to get the figure using get_figure:
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
import random as rand
pdfFile = PdfPages("output.pdf")
for i in range(10):
xVals = [x for x in range(20)]
yVals = [rand.randint(50,100) for x in xVals]
plt.figure(figsize=(20,10))
line, = plt.plot(xVals , yVals)
plt.xlabel('Data point')
plt.ylabel('Strain [us]')
plt.title(i)
#plt.show()
pdfFile.savefig(line.get_figure())
print(i)
pdfFile.close()
When no figure is specified in savefig the current figure is saved, so you could also simply write:
plt.plot(xVals , yVals)
pdfFile.savefig()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
