How to change the color of an axis with matplotlib ?

Published: April 18, 2023

Tags: Python; Matplotlib;

DMCA.com Protection Status

Changing the axis color in matplotlib is a straight-forward process. Examples

Using set_color()

To change the color of the axes, you can use the 'spines.set_color()' method. This method takes one argument, which is the desired axis color. It can be specified as any valid Matplotlib color string or an HEX color code. For example, to change the x-axis color to blue, you would use this syntax:

ax.spines['bottom'].set_color('red')

Example:

import matplotlib.pyplot as plt

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

ax = plt.subplot(111)

plt.scatter(x,y)

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

ax.spines['bottom'].set_color('red')
ax.spines['top'].set_color('blue') 
ax.spines['right'].set_color('green')
ax.spines['left'].set_color('black')

plt.title('How to change axis color with matplotlib ?')

plt.savefig('matplotlib_color_axis_01.png')

plt.show()

Output

How to change the color of an axis with matplotlib ?
How to change the color of an axis with matplotlib ?

Additional features

Change color of axis ticks

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

How to change the color of an axis with matplotlib ?
How to change the color of an axis with matplotlib ?

Change color of axis title

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

How to change the color of an axis with matplotlib ?
How to change the color of an axis with matplotlib ?

References

Links Site
set_color(c) matplotlib.org
Image

of