Adding ticks to a Matplotlib line


LineTicks is a simple class that I put together to add tick marks and labels to a plotted line (not the axes, which Matplotlib already handles well with lots of methods for customization). The code is available on github.

The tick marks stick out perpendicular to the plotted line and move around when the plot is dragged, resized or its limits are changed.

It's a bit simple and requires the indexes of the data points on which to add tick marks. Labels should be given as a sequence of strings of the same length as the index list.

An example usage is given here.

import numpy as np
import matplotlib.pyplot as plt
from lineticks import LineTicks

# Acceleration due to gravity, m.s-2
g = 9.81
# Initial speed (m.s-1) and launch angle (deg)
v0, alpha_deg = 40, 45
alpha = np.radians(alpha_deg)

# Time of flight
tmax = 2 * v0 * np.sin(alpha) / g

# Grid of time points, and (x,y) coordinates of trajectory
n = 100
t = np.linspace(0, tmax, n)
x = v0 * t * np.cos(alpha)
y = - g * t**2 / 2 + v0 * t * np.sin(alpha)

fig, ax = plt.subplots(facecolor='w')
fig.suptitle('Trajectory of a projectile launched at {} m/s at an angle'
             ' of {}°'.format(v0, alpha_deg))
traj, = ax.plot(x, y, c='purple', lw=4)
ax.set_xlabel('Range /m')
ax.set_ylabel('Height /m')

# Add major ticks every 10th time point and minor ticks every 4th;
# label the major ticks with the corresponding time in secs.
major_ticks = LineTicks(traj, range(0, n, 10), 10, lw=2,
                        label=['{:.2f} s'.format(tt) for tt in t[::10]])
minor_ticks = LineTicks(traj, range(0,n), 4, lw=1)

A projectile trajectory as a ticked line

NB For resizing to work properly with an interactive chart using the MacOSX backend, you will need a recent version of Matplotlib which includes this patch which fixes a bug in the resize_event handler.

Current rating: 5


Comments are pre-moderated. Please be patient and your comment will appear soon.

There are currently no comments

New Comment


required (not published)