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
Selected Reading
How to turn off the upper/right axis tick marks in Matplotlib?
In Matplotlib, by default, tick marks appear on all four sides of the plot. To create cleaner visualizations, you can selectively turn off the upper (top) and right axis tick marks using the tick_params() method.
Using tick_params() Method
The most straightforward approach is to use tick_params() with specific parameters to control tick visibility ?
import numpy as np
import matplotlib.pyplot as plt
# Create sample data
x = np.linspace(-2, 2, 10)
y = np.sin(x)
# Create the plot
plt.figure(figsize=(8, 4))
plt.plot(x, y, marker='o')
# Turn off top and right ticks
plt.tick_params(axis="both", which="both", top=False, right=False)
plt.title("Plot with Top and Right Ticks Disabled")
plt.show()
Using a Custom Dictionary
You can also create a dictionary to store tick visibility settings for better code organization ?
import numpy as np
import matplotlib.pyplot as plt
# Create sample data
x = np.linspace(-2, 2, 10)
y = np.sin(x)
# Create the plot
plt.figure(figsize=(8, 4))
plt.plot(x, y, marker='o', color='blue')
# Define tick visibility settings
visible_ticks = {
"top": False,
"right": False
}
# Apply the settings
plt.tick_params(axis="both", which="both", **visible_ticks)
plt.title("Using Dictionary for Tick Control")
plt.xlabel("X values")
plt.ylabel("Y values")
plt.show()
Advanced Tick Control
For more granular control, you can specify different settings for major and minor ticks ?
import numpy as np
import matplotlib.pyplot as plt
# Create sample data
x = np.linspace(0, 10, 50)
y = np.cos(x)
plt.figure(figsize=(8, 4))
plt.plot(x, y, linewidth=2)
# Control major ticks only
plt.tick_params(axis="x", which="major", top=False)
plt.tick_params(axis="y", which="major", right=False)
# Add grid for better visualization
plt.grid(True, alpha=0.3)
plt.title("Advanced Tick Control")
plt.show()
Parameters
| Parameter | Description | Values |
|---|---|---|
axis |
Which axis to apply changes | 'x', 'y', 'both' |
which |
Which ticks to modify | 'major', 'minor', 'both' |
top |
Show/hide top ticks | True, False |
right |
Show/hide right ticks | True, False |
Conclusion
Use plt.tick_params() with top=False and right=False to hide upper and right tick marks. This creates cleaner plots by removing unnecessary visual elements while maintaining readability.
Advertisements
