How to draw axis lines inside a plot in Matplotlib?

In Matplotlib, you can draw axis lines inside a plot by positioning the spines at zero and hiding unnecessary borders. This creates a coordinate system where the x and y axes pass through the origin.

Understanding Spines

Spines are the lines connecting the axis tick marks that form the boundaries of the data area. By default, Matplotlib shows all four spines (top, bottom, left, right) around the plot area.

Drawing Axis Lines Inside the Plot

Here's how to position the axis lines at the center of the plot ?

import numpy as np
import matplotlib.pyplot as plt

# Set figure size
plt.rcParams["figure.figsize"] = [8.00, 6.00]
plt.rcParams["figure.autolayout"] = True

# Create figure and data
fig = plt.figure()
x = np.linspace(-5, 5, 100)
y = x**2

# Add subplot
ax = fig.add_subplot(111)
ax.plot(x, y, 'b-', linewidth=2, label='y = x²')

# Position spines at zero (center)
ax.spines['left'].set_position('zero')
ax.spines['bottom'].set_position('zero')

# Hide top and right spines
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

# Add labels and title
ax.set_xlabel('X-axis', loc='right')
ax.set_ylabel('Y-axis', loc='top', rotation=0)
ax.set_title('Parabola with Centered Axes')

plt.grid(True, alpha=0.3)
plt.show()

Customizing Axis Line Appearance

You can further customize the axis lines with different colors and styles ?

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(8, 6))

# Create data
x = np.linspace(-3, 3, 100)
y = np.sin(x)

# Plot the function
ax.plot(x, y, 'r-', linewidth=2, label='y = sin(x)')

# Position and style the spines
ax.spines['left'].set_position('zero')
ax.spines['left'].set_color('black')
ax.spines['left'].set_linewidth(1.5)

ax.spines['bottom'].set_position('zero')
ax.spines['bottom'].set_color('black')
ax.spines['bottom'].set_linewidth(1.5)

# Hide top and right spines
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)

# Add arrow heads to axes
ax.annotate('', xy=(3.2, 0), xytext=(3, 0),
            arrowprops=dict(arrowstyle='<-', color='black'))
ax.annotate('', xy=(0, 1.2), xytext=(0, 1),
            arrowprops=dict(arrowstyle='<-', color='black'))

plt.grid(True, alpha=0.3)
plt.legend()
plt.show()

Key Methods

Method Purpose Common Values
set_position() Position spine location 'zero', 'center', ('data', value)
set_color() Set spine color 'none', 'black', 'red', etc.
set_visible() Show/hide spine True, False

Conclusion

Use set_position('zero') to move axis lines to the plot center and set_color('none') to hide unwanted spines. This creates clean mathematical plots with axes passing through the origin.

Updated on: 2026-03-26T02:29:00+05:30

647 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements