Plots in matplotlib pylab

When trying to explain something to someone it is usually much better to actually present it in a graphical form. For this, I’m usually using Python and its module Matplotlib. It is highly customizable package with lots and lots different display techniques both for 2D and 3D images. Great feature is that one can also create animations to include in presentations.

One of the classes in Matplotlib is called PyLab. It is meant to have the same functionality as Matlab’s plotting functions. For my everyday activity that’s typical more than enough. I’m not going to discuss package in details. I just want to mention few nice options when displaying and saving plot to a file.

As a default, pylab leaves lots of whitespace for axis, titles and borders. On one hand this is good, because it makes everything look really nice, but on the other, we are losing some space for actual graphs. If you are going to discuss the plot while presenting, sometimes you can remove “unnecessary” content.

Supposedly one imports pylab with

import pylab as py  # including pylab lib

To remove ticks from axis:

frame = py.gca()  # returns (gets) current axis
frame.axes.get_xaxis().set_ticks([]) # removes all x axis ticks
frame.axes.get_yaxis().set_ticks([]) # removes all y axis ticks

To change the distance between subplots and margins:

py.subplots_adjust(left=leftMargine, bottom=bottomMargine,
                    right=rightMargine, top=topMargine,
                    wspace=widthSpace, hspace=highSpace)

Parameters left, right, bottom and top refer to location of the grid corners. Wspace and hspace are respectively horizontal and vertical spaces between subplots. Pylab can actually do it by itself, but the result is not always the best possible. Command to do it automatically is


On top of that, one can also remove unnecessary white space in output when saving to file

py.savefig(filename, bbox_inches='tight')

where the ‘tight’ indicates cropping margins.

Here is a short snippet where those functions are applied:

import pylab as py
import numpy as np

N = 500
t = np.linspace(0, 1, N)
s1 = np.random.random(N)
s2 = np.random.random(N)
s3 = np.random.random(N)

py.plot(t, s1)

py.plot(t, s2)

py.plot(t, s3)

py.savefig('output', dpi=150, bbox_inches='tight')



Leave a Reply

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

You are commenting using your 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