Professional PDF Reports with Matplotlib in Python

NeuralNine · Beginner ·⚡ Algorithms & Data Structures ·2mo ago

Key Takeaways

This video demonstrates how to create professional PDF reports using Matplotlib in Python, covering the basics of Matplotlib and its application in generating reports.

Full Transcript

Today, we're going to learn how to create professional PDF reports using Matplotlib. These can be financial reports, medical reports, or just data set exploration reports. Whatever you want to put in there, you can basically turn Matplotlib plots and figures into documents, into professional documents, and today we're going to learn how to do that. If you like this video, let me know by hitting a like button and subscribing, and now let us get right into it. >> [music] >> All right, so we're going to jump right into it. Open your favorite code editor and navigate to a directory of your choice. In my case, I'm going to be working in the tutorial directory, and the only thing you need for this video to follow along is Matplotlib on your system. So, the easiest way to do that is to use pip to install it. So, pip or pip3, depending on your operating system, install, and then matplotlib. This adds it to your global Python installation. If you want a virtual environment, you can do that with venv, with virtualenv, or in my case, I'm going to go If you don't know what uv is, you don't have to concern yourself with that, so just use the pip install method. I'm just going to say uv init and uv at matplotlib basically accomplishes the same thing, just locally in this directory. So, it's an isolated environment, but pip install is fine. Now, what I'm also going to install here is pandas, just because we need some data source. So, you can use a CSV file, a database connection, hard-coded data in your Python script. I'm going to just craft an artificial pandas data frame with some sample data that we can visualize, and because of that, I need to say uv at uh pandas. And in your case, if you want to do the same thing, you can also say pip install pandas, too. So, pip install pandas will install it globally to your Python installation. So, I'm also going to say now source venv bin activate, just so I have the auto-completion. If you're not using a virtual environment, you can also skip that. And now, let's get into the code. We're going to open up a file called main.py, or you can call it whatever you want. We're going to start from scratch, so I'm going to remove this default code here, and what we want to do now is we want to start with a very basic hello world like example of exporting something to a PDF document using Matplotlib. So, we're going to start with the imports. We're going to say import pandas as pd so we can have some sample data. We're going to say import matplotlib.pyplot as plt. This is the ordinary matplotlib import. And now, this is probably new from matplotlib.backends we're going to import the PDF backend. So, backends backend_pdf, we're going to import PDF pages, which is a class. And if you know how to work with Matplotlib, I can tell you this right away. If you know how to work with figures, how to design stuff in Matplotlib, and I have a crash course on that if you don't know how to do that, but basically all you have to do is you have to wrap PDF pages around it, and that's it. You can just export your PDF figure or your Matplotlib figures into a PDF document. That's all you need to do. So, the tutorial here is more like an example of how to do that, but the magic, if you know Matplotlib already, is just wrapping PDF pages around it. That's it. So, let us now start with generating the sample data. I'm just going to say df is equal to pandas data frame. We're going to have a dictionary here, so we're going to hardcode the data, and it's going to be very simple. We have months. Months is going to be a list of month names, so January and so on, like this, January to December. Then we're going to say sales. Sales is going to be just the sales numbers or sales prices, whatever. I'm going to fill that up in a second here. We're going to have costs, and then we're going to have profit as well, but we're not going to hardcode it. We're going to say later on that the profit is obviously just the sales minus the costs. And with pandas data frames, we can easily do that. Sales minus cost, that is just the setup now, so this is nothing related to PDF export. I'm just setting up some data. There you go. Like this, we have some numbers here for every month. Let's maybe call this cost. I think that's grammatically more correct. And this now is our sample data. So, we can visualize this data in ordinary matplotlib plots. So, how do we actually take this now and visualize something that we can then export into a PDF document? Very simple, we can add a width statement with PDF pages, and everything that happens then in there just needs to be saved to a PDF document, and that's it. So, we're going to say with PDF pages and then the name, let's call this report.pdf as PDF. And in here, we can just do the ordinary matplotlib stuff. So, I can define a figure. I can say plt.figure. I can provide a figure size. Now, you can use some standardized format like A4. Let me just look up the values again. 8.27 and 11.69. That's the standardized A4 page. Probably for Americans not that interesting. But that would be now the figure size. That's the size of the page. A figure is a page, basically. Then we can say figure.suptitle, so subtitle but with a P, not with a B. So, sub as supertitle. We're going to call this sales report. Let's call this annual sales report. Sounds more professional. Font size for this is going to be 16, and the weight is going to be bold. Now, then we can basically do a bunch of stuff in here, and at the end, what we do is we say PDF.savefig. So, savefig like this. And we pass the figure, and we close the plt. So, plt.figure or plt.close the figure. That is the whole setup. So, if we run this now, uv run main.py, or in your case, you would do python or python3 main.py. We can see this generates a report. I can open this report, and we can see an empty figure. It just has annual sales report. That is the most basic way to export something. Everything else we do, everything we add to the figure, is basically just Matplotlib stuff. So, it's not really anything fancy. If you know how to work with Matplotlib, you can end the video right here. You know already what to do. That is the setup you have with PDF pages. You have a figure. You design the figure or the size of the figure. You save it. You close it. That's it. However, of course, there is some more interesting stuff that we can do. For example, we can define a grid. I can say GS is equal to figure.add_grid spec. And then I can say I want to have three rows and two columns with the height ratios being equal to 1 to 2. What does that basically mean? It means that the first row has a size of one compared to the second and third row that have proportionally a size of two and two. So, that's that's the idea that these two rows are larger than this one, twice as large as this one. Then we can also say H space is equal to 0.4 and uh W space is equal to 0.3. There you go. So, that is now our grid spec. And this means that we have different rows and columns that we can fill now with axes, with plots, basically. So, now let's say in the first smaller row here, I want to add a table. So, I'm going to define a table with the data. I just want to have the data as a table. And below it, I want to have a 2 by 2 grid with some plots. So, first of all, we're going to start by defining an axis for the table. Let me actually go full screen here. And that is going to be figure.add_subplot. And here we're now going to say that this is our grid spec and zero and everything. So, this basically means it fills the entire first row. That is the axis for our table. We're going to say axis table axis is going to be off because that's not a plot. So, we only want to have the table there. Then we can just create the table by saying table is equal to axis table.table. Then the cell text of the individual cells is going to be the DF values. And the column names or column labels is what they're called here is going to be DF columns and the location of this should be center. Then we can also say table set font size and let's go and set this to eight. So let's see if this already works. I can do UV run main.py again. We can take a look at this and there you go. We have a table now in our plot so or in our PDF. Now of course what you can do is you can go title case here for the columns. You can also define a list with the column names. You can also add some styling like a background color here and bold text and whatnot. I don't want to spend too much time doing matplotlib stuff here because the focus is on generating the report. So from now on I'm also going to do more copy pasting just to show you how you do stuff in general. If you want to learn matplotlib designing in general, I have a crash course on that. You can watch this one. But here we're not going to spend too much time talking about individual matplotlib stuff that we can do. So yeah, for the two by two grid with the plots, I'm going to do one manually here. We're going to type one out ourselves and then we're going to just copy paste the remaining three because the concept is the same. So we're going to define an axis here. Axis one is equal to figure at subplot. And of course what do we need to do here? We have our grid spec. Now we're in row one and so row one is actually row two. Um and we want to have the first column which is column zero. And then we're going to say axis one dot plot and what do we want to plot? On the x-axis we want to have the months and on the y-axis the sales. So I'm going to say DF months, DF sales. Then we can do stuff like marker is equal to something. Then we can say color is equal to red for example. Then to be able to see the months properly, we're going to say axis one tick underscore params because we want to rotate the x labels or the x ticks actually. So I'm going to say axis is the one with the months so that's the x-axis and the rotation here is going to be 45 degrees. So they're displayed in a better way. Then finally axis one set title and we're going to just say sales. And then of course for the other three plots it's basically the same idea. We do the same thing but we adjust the grid spec location so we have one one, two zero, two one and because of that because it's basically the same I'm just going to copy paste this here now and we have axis two, three, four. We have here months versus cost, month versus profit, sales versus cost. Same idea as here just we visualize the different columns. So I'm going to write this now and we're going to run main.py and see if this generates a nice report. What we get here is a PDF document A4 format with four different plots and a table at the top. Now you might be saying though that of course when you generate a report you usually want to have more than one page. How do we add multiple pages to the same document? That is also super super simple. Let's go back into main.py. Let's go full screen again. The only thing you have to do is you have to repeat the whole process. So we can copy this at the top. Just create a new figure. We can paste it down below this save figure and plt.close statement. We can copy these two here as well. And that's basically it. We can now say here we can just change this to be something else. Additional analysis for example. And this is now a new page. This will be created as a second page in the same document. If I go uvi run main.py and if I take a look at the report now you can see we still have the same thing as before and now we have a separate page additional analysis. So that is as easy as it gets and now you can repeat the same process. You can add more stuff here and that's basically the idea. Now to keep it simple and save time let me just copy paste some snippet here so we have some content. The same idea as before nothing new here. We just have add grid spec this time three rows and one column same height ratios. Here we just add some text. Again this is just matplotlib. Here we have a plot for cumulative profit and here we have sales versus cost. That is basically it. This is everything we do. Let me just fix typo here. We have months not month. And now I can just run main.py and this will fill up this second page with stuff. So, this is what it then looks like. We have more plots on the second page. And you can keep going like this. We you just have to type matplotlib code and it generates PDF pages. If I may for a second, I would like to plug myself in as a sponsor of my own video. If you go to my website neuralnine.com, you will find a tab services and a tab tutoring. Here you can hire me for all sorts of stuff like data science, machine learning, web development. If you need help with something in a project, here you can book me for one-on-one tutoring if you want me to teach you personally something that you don't understand. If you like my teaching style, on both pages at the bottom you can contact me via mail and also via LinkedIn. Just wanted to let you know about this. Now, finally just as a motivation, I want to show you what's possible. Here I have a script which is completely AI generated. So, this is not code that I've written myself. Uh it's also quite comprehensive. So, I'm not going to teach or I'm not going to analyze exactly what's happening here, but essentially all we're using here is matplotlib the back end with PDF pages and then some design stuff in matplotlib. This is what the code looks like. Again, we're not going to explore it too much, but it's the same idea. We have the same idea of wrapping PDF pages in the beginning, doing the same stuff with figure, save figure, close. That's everything we're doing here and basic matplotlib stuff. And with this, we can build stuff like that. So, I can run fancy.py and this will produce a fancy report. So, I can open this fancy report and this looks like this. So, we have an executive summary. We have KPIs. We have nice looking plots. We have revenue breakdown. We have analytics, different chart types. We have a heat map or whatever this this plot type is called. We have a plot like this. So, this looks very professional. Again, we're not teaching this here. I'm not going to show you how to do that because mostly you saw the code. It's It's mostly just matplotlib design stuff. The idea is the same. Figure, save figure. Figure, save figure. That's all you need to do to create professional reports using matplotlib. So, that's it for this video today. I hope you enjoyed it and hope you learned something. If so, let me know by hitting a like button and leaving a comment in the comment section down below. Also, in case you're interested on my website you'll find a services tab and a tutoring tab. There you can contact me if you need help with a project, if you need a freelancer, consultant, you can contact me at the bottom of these pages using LinkedIn or email. Besides that, don't forget to subscribe to this channel and hit the notification bell to not miss a single future video for free. Other than that, thank you very much for watching. See you in the next video and bye.

Original Description

💻️ Need some help with a project or some consulting? Contact me here: https://www.neuralnine.com/services Code: https://github.com/NeuralNine/youtube-tutorials/tree/main/Matplotlib%20PDF%20Reports 🐍 The Python Bible Book: https://www.neuralnine.com/books/ 💻 The Algorithm Bible Book: https://www.neuralnine.com/books/
Sign in to unlock AI tutor explanation · ⚡30

This video teaches how to use Matplotlib to create professional PDF reports in Python, covering the basics of data visualization and report generation. By following this tutorial, viewers can learn how to generate reports using Matplotlib and apply algorithms for data analysis.

Key Takeaways
  1. Install Matplotlib library
  2. Import Matplotlib in Python
  3. Create a sample dataset
  4. Use Matplotlib to generate a plot
  5. Save the plot as a PDF report
💡 Matplotlib is a powerful library for creating professional PDF reports in Python, allowing for customized data visualization and report generation.

Related Reads

📰
Common Methods to Find GCD
Learn 3 simple methods to find the Greatest Common Divisor (GCD) and improve your programming skills
Medium · Programming
📰
Recursion vs Iteration: Choosing Your Path Like Neo in *The Matrix*
Learn when to use recursion vs iteration in coding, and how to choose the best approach for your problem, just like Neo choosing his path in The Matrix
Dev.to · Timevolt
📰
You Don’t Need to Solve 500 LeetCode Problems. You Need to Recognize 12 Patterns.
Recognize 12 common patterns to improve coding skills, rather than solving a large number of LeetCode problems
Medium · Programming
📰
Google Interview Question #2
Learn to solve a Google interview question about finding the minimum initial energy required to cross a river with varying wind speeds
Medium · JavaScript
Up next
Webhooks & Callbacks For Beginners in Python
NeuralNine
Watch →