Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a title page for a PDF document created using matplotlib

I have a report to be submitted automatically and I am using matplotlib to do that. But I am not able to figure out how to create a blank page in the begining with Title in the middle on the type of analysis which is performed

with PdfPages('review_count.pdf') as pdf:
    for cat in self.cat_vars.keys():
        if len(self.cat_vars[cat]) > 1:
            plt.figure()
            self.cat_vars[cat].plot(kind='bar')
            plt.title(cat)
            # saves the current figure into a pdf page
            pdf.savefig()
            plt.close()
like image 565
Bharath Kumar Avatar asked Sep 02 '15 08:09

Bharath Kumar


People also ask

How do I add a title to a PDF file?

Copy the Heading 1 of your document to use as your title. (Optional) Go to File > Info > Properties > Title. Click “Add a title” and paste your Heading 1 into the textbox. Or, type in an easy-to-read title for your document. For Example, “ENGR 101 Fall 2021 Syllabus.” Save your changes.

Why is my Matplotlib plot not saving as a PDF?

The issue is that when a user plots a graph in matplotlib and tries to save it as a PDF file in their local system they get an empty file. In the above example, we firstly import matplotlib.pyplot library.

What happens if a PDF does not have a title?

If a PDF does not have a title, the filename appears in the results list instead. A file’s title is not necessarily the same as its filename. The Advanced area shows the PDF version, the page size, number of pages, whether the document is tagged, and if it’s enabled for Fast Web View.

How to save a plot as a PDF in Python?

Create a pLot: By using plot (), scatter (), bar (), method you can create a plot or you can use any other method which ever you like. Save as pdf: By using savefig () method you can save a file into your system. Set extension of the file to “pdf” as your main aim is to save as pdf.


1 Answers

You should just be able to create a figure before your for loop with the title on. You also need to turn the axis frame off (plt.axis('off')).

with PdfPages('review_count.pdf') as pdf:
    plt.figure() 
    plt.axis('off')
    plt.text(0.5,0.5,"my title",ha='center',va='center')
    pdf.savefig()
    plt.close() 
    for cat in self.cat_vars.keys():
        if len(self.cat_vars[cat]) > 1:
            plt.figure()
            self.cat_vars[cat].plot(kind='bar')
            plt.title(cat)
            # saves the current figure into a pdf page
            pdf.savefig()
            plt.close()
like image 122
tmdavison Avatar answered Sep 27 '22 22:09

tmdavison