Change tick labels font size in matplotlib

This tutorial will look into different methods of changing the font size for tick labels in matplotlib. Matplotlib is an excellent library used for the visualization of 2D plots. It provides various functions for plots, charts, maps, and many others. Tick labels are the data points on axes. We can change the size of them using specific functions. Let’s see how……

The three methods to change the font size are:

  • plt.xticks()/plt.yticks()
  • ax.set_xticklabels()/ax.set_yticklabels()
  • ax.tick_params()

plt.xticks() / plt.yticks()

Syntax:

matplotlib.pyplot.xticks(ticks=None, labels=None, **kwargs)

Example:

import matplotlib.pyplot as plt
x = [2,4,16]
y = [11,13,18]
plt.plot(x, y)
plt.xticks(fontsize=18)
plt.show()

Output:

matplotlib plot

ax.set_xticklabels() / ax.set_yticklabels()

Syntax:

Axes.set_xticklabels(labels, *, fontdict=None, minor=False, **kwargs)

Note: It should be used after fixing the tick positions using Axes.set_xticks().

Example:

import matplotlib.pyplot as plt
import numpy as np
x = [2,4,6,8,10,12,14,16,18,20]
y = np.log(x)
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_xticks(x)
ax.set_xticklabels(x, fontsize=20)
plt.show()

Output:

 Change tick labels font size in matplotlib

ax.tick_params()

Syntax:

matplotlib.pyplot.tick_params(axis='both', **kwargs)

Example:

import matplotlib.pyplot as plt
x = list(range(1, 11, 1))
y = [s*s for s in x]
fig, ax = plt.subplots()
ax.plot(x, y)
ax.tick_params(axis='y', labelsize=20)
plt.show()

Output:

ax.tick_params()

You may also learn,

Leave a Reply

Your email address will not be published.