How to Make a Comparative Bar Graph PDF using Python and ReportLab

Note: this how-to comes from the same vein as “Generating CSS-Only Sparklines in Python“.

So.

Let’s say that you have 2 sets of data where each data point in each set corresponds to the same 1 parameter… and you want to make a printable bar graph of it all.

For example, you might want to compare your store’s history-averaged daily sales to recent daily sales for some specific dates of the year. Or… it could be the high temperature for your town… or, it could be your weight versus percent body fat. It doesn’t really matter; as long as you need to compare 2 “variables” against the same 1 “constant”.

If you’re familiar with graphing, then you’ll immediately realize that the dates will work on one axis (in this post, that’s the x-axis), and that the things you’re comparing will work on the other (here, the y-axis).

Without going into the advantages of print-resolution vectors over screen-resolution rasters…

I’ve written a Python module (with a ton of kickass notation by way of comments) that will generate a PDF file featuring this type of bar graph for you. Of course, it’s easily customizable.

Before you can use my code, however, you need to have Python and ReportLab installed on your system. I’ll leave the details of that up to you (it’s easy). RTFMs; they won’t steer you wrong.

As with the sparkline how-to, this module will squish-down all the data so that the graph fits on one (US standard “letter” size) page, in “landscape” (wide) orientation. The range of the data and the number of data points don’t matter; it’ll all fit.

For the time being there is no graph legend, no headers for the axes, and no labels for the x-axis. The y-axis, however, does have labels based on the lower- and upper-limits of the data.

With all of that (unnecessary?) exposition aside, I give you:

  • The code (remember to change the .txt to a .py), and
  • A sample PDF (which you can generate from the code’s default state).

If you have any questions or comments, please feel free to leave ’em here on the site.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s