Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to export to pdf a graph based on a pandas dataframe?

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!

like image 998
ℕʘʘḆḽḘ Avatar asked Feb 18 '16 14:02

ℕʘʘḆḽḘ


3 Answers

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()
like image 96
fernandezcuesta Avatar answered Oct 09 '22 19:10

fernandezcuesta


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()
like image 33
tmdavison Avatar answered Oct 09 '22 17:10

tmdavison


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.

like image 36
Julien Spronck Avatar answered Oct 09 '22 18:10

Julien Spronck