Minor Ticks in Matplotlib

Minor Ticks in Matplotlib

  1. Activate Minor Ticks in Matplotlib
  2. Style Minor Ticks in Matplotlib

This tutorial teaches you how to use and format minor Ticks in Matplotlib. Matplotlib is a Python data visualization plotting library.

Before working with plots, we need to set up our script to work with the library. We start by importing Matplotlib, and we load the randrange function from the random module to quickly generate some data.

Keep in mind that the output will look different for you.

Code Sample:

import matplotlib.pyplot as plt
from random import randrange

data_1 = [randrange(0, 10) for _ in range(0, 10)]
data_2 = [randrange(0, 10) for _ in range(0, 10)]

Activate Minor Ticks in Matplotlib

Activating minor ticks in Matplotlib is as easy as calling the pyplot.minorticks_on() method.

Code Sample:

plt.plot(data_1)
plt.minorticks_on()

Remember that your Plot will look different because of the randomly generated numbers. As you see, there are no small ticks in between the larger numbered one.

Output:

Activate Minor Ticks

Style Minor Ticks in Matplotlib

We can also style the Minor/Major ticks to look more to our liking. We do this with the pyplot.tick_params() method.

In the following example, I applied some styling options.

Code Sample:

# For the X Axis
plt.tick_params(
        axis="x",
    which="minor",
    length=10,
    color="r")

# For the Y Axis
plt.tick_params(
        axis="y",
    which="major",
    length=10,
    color="g",
    labelrotation=45.0)

plt.show()

The function takes the axis argument, which determines which axis the following styles are applied to, and the which argument determines if it is applied to major or minor ticks. Now there are many options to style your ticks.

Output:

Style Minor Ticks

The Minor ticks at the bottom are now red and longer in the output above. Ticks on the side are green, and their label is rotated by 45 degrees.

Now you know how to enable and style minor ticks in Matplotlib.

Complete Code:

import matplotlib.pyplot as plt
from random import randrange

data_1 = [randrange(0, 10) for _ in range(0, 10)]

plt.plot(data_1)
plt.minorticks_on()

# For the X Axis
plt.tick_params(
    axis="x",
    which="minor",
    length=10,
    color="r")

# For the Y Axis
plt.tick_params(
    axis="y",
    which="major",
    length=10,
    color="g",
    labelrotation=45.0)

plt.show()
Author: Maxim Maeder
Maxim Maeder avatar Maxim Maeder avatar

Hi, my name is Maxim Maeder, I am a young programming enthusiast looking to have fun coding and teaching you some things about programming.

GitHub