Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to put the Origin at the center of the cos curve in a figure in Python Matplotlib?
To put the Origin at the center of the cos curve in a figure, we can manipulate the spine positions in Matplotlib. This creates a mathematical coordinate system where both x and y axes intersect at the origin (0, 0).
Steps to Center the Origin
Set the figure size and adjust the padding between and around the subplots.
Create x and y data points using numpy.
Set the position of the axes using spines, top, left, right and bottom.
Plot x and y data points using plot() method.
Set the title of the plot.
To display the figure, use show() method.
Example
Here's how to center the origin for a cosine curve ?
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-5, 5, 100)
y = np.cos(x)
ax = plt.gca()
ax.spines['top'].set_color('none')
ax.spines['left'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position('zero')
plt.plot(x, y)
plt.title("$\bf{y=cos(x)}$")
plt.show()
How It Works
The key is manipulating the spine positions:
ax.spines['left'].set_position('zero')− Moves the y-axis to x=0ax.spines['bottom'].set_position('zero')− Moves the x-axis to y=0ax.spines['top'].set_color('none')− Hides the top borderax.spines['right'].set_color('none')− Hides the right border
Alternative Method with Grid
You can also add a grid to make the coordinate system more visible ?
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [8.00, 4.00]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-2*np.pi, 2*np.pi, 100)
y = np.cos(x)
fig, ax = plt.subplots()
# Center the spines
ax.spines['left'].set_position('zero')
ax.spines['bottom'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
# Add grid
ax.grid(True, alpha=0.3)
plt.plot(x, y, 'b-', linewidth=2, label='cos(x)')
plt.title("Cosine Curve with Centered Origin")
plt.xlabel('x')
plt.ylabel('y')
plt.show()
Conclusion
Use set_position('zero') on the left and bottom spines to center the origin. Hide unnecessary spines with set_color('none') for a clean mathematical plot appearance.
