Centering the plot axes in matplotlib

matplotlib_center_axes

Skill - Centering the plot axes in matplotlib

Table of Contents

Skills Required

Please make sure to have all the skills mentioned above to understand and execute the code mentioned below. Go through the above skills if necessary for reference or revision


Matplotlib is a plotting library tn the scipy ecosystem of libraries.

Please make sure that you covered the post on basics


Sometimes we may require to have the main axis lines to be intersecting at (0,0) of the subplot. We will control the positioning of spines to achieve this.

import matplotlib.pyplot as plt
x = [-5, -4, 5, 8]
y = [-6, 5, 8,-10]

# create a plotting area and get the figure, axes handle in return
fig, ax = plt.subplots()

# plot data on the axes handle
ax.plot(x, y)

# Move left y-axis and bottim x-axis to centre by setting position as 'center'
ax.spines['left'].set_position('zero')
ax.spines['bottom'].set_position('zero')

# Eliminate top and right axes by setting spline color as 'none'
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

# print the plot
plt.show()

matplotlib_center_axes_demo

As shown above the spines/axis lines of an axes handle ax can be controlled by ax.spines

If we want the axis lines to be intersecting at center of the subplot instead of (0,0).

In such case we can use the following

ax.spines['left'].set_position('center')
ax.spines['bottom'].set_position('center')

The output would be like the image below
matplotlib_center_axes_demo

Video

You can the video on this post here


Online Interpreter

Although we recommend to practice the above examples in Visual Studio Code, you can run these examples online at https://pynative.com/online-python-code-editor-to-execute-python-code/

References


Table of Contents

Comments