15/02: control axes frame

For a lot of plots, like histograms, it doesn't look as good to have all four edges of the frame visible. The set_frame_on() method will remove the default frame, but the custom frame has to be built by hand, and the tick position and visibility set accordingly. This function will take care of all this for you. It can't really be called more than once because it doesn't have any means of removing the lines of the custom frame. Also note that the lines are drawn on the axes, which means that any interactive manipulation of the viewport will move the lines around, but you probably only want to use this in scripts to generate production figures anyway.


def setframe(ax, lines=1100):
"""
Set which borders of the axis are visible. Note that subsequent calls
to plot usually change these settings.

lines - either a list of 4 values or a number with 4 digits. The values
set which lines are visible: [left bottom right top]

Example: setaxislines(ax, 1100) sets only the bottom and top axes visible
"""
from matplotlib.lines import Line2D

if isinstance(lines, int):
lines = '%04d' % lines
if isinstance(lines, str):
lines = [int(x) for x in lines]

ax.set_frame_on(0)
# Specify a line in axes coords to represent the left and bottom axes.
val = 0
if lines[0]:
ax.add_line(Line2D([val, val], [0, 1], transform=ax.transAxes, c='k'))
ax.yaxis.set_ticks_position('left')
if lines[1]:
ax.add_line(Line2D([0, 1], [val, val], transform=ax.transAxes, c='k'))
ax.xaxis.set_ticks_position('bottom')
if lines[2]:
ax.add_line(Line2D([0, 1], [1-val, 1-val], transform=ax.transAxes, c='k'))
ax.yaxis.set_ticks_position('right')
if lines[3]:
ax.add_line(Line2D([1-val, 1-val], [1, 0], transform=ax.transAxes, c='k'))
ax.xaxis.set_ticks_position('top')

if lines[0] and lines[2]:
ax.yaxis.set_ticks_position('both')
ax.yaxis.set_visible(lines[0] or lines[2])
if lines[1] and lines[3]:
ax.yaxis.set_ticks_position('both')
ax.xaxis.set_visible(lines[1] or lines[3])

Comments