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 set axis ticks in multiples of pi in Python Matplotlib?
To set axis ticks in multiples of pi in Python Matplotlib, we can use the xticks() method to customize both the tick positions and their labels. This is particularly useful when plotting trigonometric functions where pi-based intervals provide better context.
Steps to Set Pi-based Ticks
Initialize a pi variable and create theta and y data points using NumPy.
Plot theta and y using plot() method.
Get or set the current tick locations and labels of the X-axis using xticks() method.
Use margins() method to set autoscaling margins for better visualization.
Display the figure using show() method.
Example
Here's how to create a sine wave plot with X-axis ticks labeled in multiples of pi ?
import numpy as np from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True pi = np.pi theta = np.arange(-2 * pi, 2 * pi + pi/2, step=(pi / 2)) y = np.sin(theta) plt.plot(theta, y) plt.xticks(theta, ['-2?', '-3?/2', '-?', '-?/2', '0', '?/2', '?', '3?/2', '2?']) plt.margins(x=0) plt.show()
How It Works
The xticks() method takes two arguments:
First argument: Array of tick positions (in radians)
Second argument: Array of corresponding labels (using ? symbols)
Alternative Approach Using Multiple Subplot
You can also create more complex visualizations with multiple functions ?
import numpy as np
import matplotlib.pyplot as plt
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 6))
pi = np.pi
x = np.linspace(-2*pi, 2*pi, 100)
tick_positions = np.arange(-2*pi, 2*pi + pi/4, pi/2)
tick_labels = ['-2?', '-3?/2', '-?', '-?/2', '0', '?/2', '?', '3?/2', '2?']
# Sine plot
ax1.plot(x, np.sin(x), 'b-', label='sin(x)')
ax1.set_xticks(tick_positions)
ax1.set_xticklabels(tick_labels)
ax1.set_title('Sine Function')
ax1.grid(True, alpha=0.3)
# Cosine plot
ax2.plot(x, np.cos(x), 'r-', label='cos(x)')
ax2.set_xticks(tick_positions)
ax2.set_xticklabels(tick_labels)
ax2.set_title('Cosine Function')
ax2.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
Key Parameters
np.arange(-2*pi, 2*pi+pi/2, step=pi/2)creates tick positions at every ?/2 intervalmargins(x=0)removes extra whitespace on the X-axisCustom labels use Unicode ? symbol for better readability
Conclusion
Setting axis ticks in multiples of pi enhances the readability of trigonometric plots. Use xticks() with custom positions and labels to display meaningful ?-based intervals instead of decimal values.
