Book Image

Interactive Applications using Matplotlib

Book Image

Interactive Applications using Matplotlib

Overview of this book

Table of Contents (12 chapters)

Scripted plotting


Python is known for more than just its interactive interpreters; it is also a fully fledged programming language that allows its users to easily create programs. Having a script to display plots from daily reports can greatly improve your productivity. Alternatively, you perhaps need a tool that can produce some simple plots of the data from whatever mystery data file you have come across on the network share. Here is a simple example of how to use Matplotlib's pyplot API and the argparse Python standard library tool to create a simple CSV plotting script called plotfile.py.

Code: chp1/plotfile.py

#!/usr/bin/env python

from argparse import ArgumentParser
import matplotlib.pyplot as plt

if __name__ == '__main__':
    parser = ArgumentParser(description="Plot a CSV file")
    parser.add_argument("datafile", help="The CSV File")
    # Require at least one column name
    parser.add_argument("columns", nargs='+',
                        help="Names of columns to plot")
    parser.add_argument("--save", help="Save the plot as...")
    parser.add_argument("--no-show", action="store_true",
                        help="Don't show the plot")
    args = parser.parse_args()

    plt.plotfile(args.datafile, args.columns)
    if args.save:
        plt.savefig(args.save)
    if not args.no_show:
        plt.show()

Note the two optional command-line arguments: --save and --no-show. With the --save option, the user can have the plot automatically saved (the graphics format is determined automatically from the filename extension). Also, the user can choose not to display the plot, which when coupled with the --save option might be desirable if the user is trying to plot several CSV files.

When calling this script to show a plot, the execution of the script will stop at the call to plt.show(). If the interactive plotting mode was on, then the execution of the script would continue past show(), terminating the script, thus automatically closing out any figures before the user has had a chance to view them. This is why the interactive plotting mode is turned off by default in Matplotlib.

Also note that the call to plt.savefig() is before the call to plt.show(). As mentioned before, when the figure window is closed, the plot is lost. You cannot save a plot after it has been closed.