Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Matplotlib Cyclers are Great

2i2c
Project Jupyter

Every now and then I come across a nifty feature in Matplotlib that I wish I’d known about earlier. The MPL documentation can be a beast to get through, and as a result you miss some cool stuff sometimes.

This is a quick demo of one such feature: the cycler.

Have you ever had to loop through a number of plotting parameters in matplotlib? Say you have two datasets and you’d like to compare them to one another. Maybe something like this:

Setting up low-pass filter at 3 Hz

FIR filter parameters
---------------------
Designing a one-pass, zero-phase, non-causal lowpass filter:
- Windowed time-domain design (firwin) method
- Hamming window with 0.0194 passband ripple and 53 dB stopband attenuation
- Upper passband edge: 3.00 Hz
- Upper transition bandwidth: 2.00 Hz (-6 dB cutoff frequency: 4.00 Hz)
- Filter length: 165 samples (1.650 sec)

<Figure size 432x288 with 1 Axes>

There’s really a lot of unnecessary code going on above. We’re defining objects that share the same name as the kwarg that they represent. We can’t store them as dictionaries, because then we’d have to do some python-fu in order to get them to iterate properly. This is where cycler is handy:

<Figure size 432x288 with 1 Axes>

You can even cycle through more complex properties like colormaps. Let’s create one that cycles through several colormaps for a plot:

(((cycler('s', [200.0, 125.0, 50.0]) + cycler('cmap', ['viridis', 'magma', 'coolwarm'])) + cycler('alpha', [0.25, 0.5, 0.75])) + cycler('lw', [0, 0.1, 0.5]))
Loading...
<Figure size 432x288 with 1 Axes>

So there you have it - cyclers are pretty neat. Give them a shot, and buy a matplotlib dev a beer next time you see them for making such an awesome and often under-appreciated package!