How to custom x or y axis in a matplotlib figure ?

Published: April 19, 2023

Tags: Python; Matplotlib;

DMCA.com Protection Status

Customizing the x or y axis of a matplotlib figure can be easily done with few steps:

Plot a basic figure

Let's start by creating a basic figure using matplotlib, without modifying the axes.

import matplotlib.pyplot as plt

ax = plt.subplot(111)

x = [1,2,3,4,5]
y = [4,1,3,6,1]

plt.scatter(x,y)

plt.grid()

plt.title('How to custom x or y axis in a matplotlib figure ?')

plt.savefig('custom_axes_in_matplotlib_01.png')

plt.show()

How to custom x or y axis in a matplotlib figure ?
How to custom x or y axis in a matplotlib figure ?

Specify minimum and maximum values for the axes using xlim() and ylim()

plt.xlim(0,6)

How to custom x or y axis in a matplotlib figure ?
How to custom x or y axis in a matplotlib figure ?

Specify x and y axes labels

ax.set_xlabel('X AXIS LABEL')
ax.set_ylabel('Y AXIS LABEL')

How to custom x or y axis in a matplotlib figure ?
How to custom x or y axis in a matplotlib figure ?

Changing ticks position

xticks_pos = [i/2.0 for i in range(12)]
plt.xticks(xticks_pos)

How to custom x or y axis in a matplotlib figure ?
How to custom x or y axis in a matplotlib figure ?

Changing ticks labels

xticks_pos = [i/2.0 for i in range(12)]
xticks_labels = [l for l in 'abcdefghijkl' ]
plt.xticks(xticks_pos,xticks_labels)

How to custom x or y axis in a matplotlib figure ?
How to custom x or y axis in a matplotlib figure ?

Changing x-axis ticks color

ax.tick_params(axis='x', colors='red')

How to custom x or y axis in a matplotlib figure ?
How to custom x or y axis in a matplotlib figure ?

Changing x-axis label color

ax.xaxis.label.set_color('red')

How to custom x or y axis in a matplotlib figure ?
How to custom x or y axis in a matplotlib figure ?

Customizing Y-axis

import matplotlib.pyplot as plt

ax = plt.subplot(111)

x = [1,2,3,4,5]
y = [4,1,3,6,1]

plt.scatter(x,y)

plt.xlim(0,6)
plt.ylim(0,6)

ax.set_xlabel('X AXIS LABEL')
ax.set_ylabel('Y AXIS LABEL')

yticks_pos = [i/2.0 for i in range(12)]

plt.yticks(yticks_pos)
plt.grid()

ax.tick_params(axis='y', colors='red')

ax.yaxis.label.set_color('red')

plt.title('How to custom x or y axis in a matplotlib figure ?')

plt.savefig('custom_axes_in_matplotlib_08.png')

plt.show()

How to custom x or y axis in a matplotlib figure ?
How to custom x or y axis in a matplotlib figure ?

References

Links Site
xlim() matplotlib.org
set_xlabel() matplotlib.org
xticks() matplotlib.org
tick_params() matplotlib.org
Image

of