I have a pandas dataframe and I am using the useful .plot() method.
The dataframe looks like
col1 col2 col3
1 2 3
7 0 3
1 2 2
I therefore use df.plot()
to get the chart I want.
Problem is, I would like to export the chart to a pdf. Ideally, I could also generate other charts (based on this dataframe) and add them to the pdf.
It is possible to do so ? Thanks!
The following should do:
plot = df.plot()
plot.get_figure().savefig('output.pdf', format='pdf')
It actually depends in whether or not your backend supports pdf output (most do). Check with:
'pdf' in plot.get_figure().canvas.get_supported_filetypes()
To output a single figure as a pdf, you can use plt.savefig('myfile.pdf')
:
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame([[1,2,3],[7,0,3],[1,2,2]],columns=['col1','col2','col3'])
df.plot()
plt.savefig('myfile.pdf')
To output multiple images to one pdf, you can use PdfPages
, as shown in the example here.
A minimal example:
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.backends.backend_pdf import PdfPages
df = pd.DataFrame([[1,2,3],[7,0,3],[1,2,2]],columns=['col1','col2','col3'])
with PdfPages('multipage_pdf.pdf') as pdf:
df.plot()
pdf.savefig()
plt.close()
df.plot(kind='bar')
pdf.savefig()
plt.close()
The following code creates a pdf with 2 pages (one plot on each page):
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
df = pd.DataFrame({'col1': [1, 3, 7], 'col2': [1, 4, 5], 'col3': [2, 7, 1]})
with PdfPages('foo.pdf') as pdf:
fig=df.plot(x='col1', y='col2').get_figure()
pdf.savefig(fig)
fig=df.plot(x='col1', y='col3').get_figure()
pdf.savefig(fig)
You can add as many plots as you want by repeating the last two lines.
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