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 remove the first and last ticks label of each Y-axis subplot in Matplotlib?
When creating multiple subplots in Matplotlib, you might want to remove the first and last tick labels from the Y-axis to create cleaner visualizations. This can be achieved by iterating through the axes and setting specific tick labels to invisible.
Method: Using setp() to Hide Tick Labels
The most effective approach is to use plt.setp() to modify the visibility of specific tick labels ?
import matplotlib.pyplot as plt
import numpy as np
# Set figure size and layout
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create subplots with sample data
fig, ax = plt.subplots(2, sharex=True)
# Add sample data to make the example complete
x = np.linspace(0, 10, 100)
ax[0].plot(x, np.sin(x))
ax[1].plot(x, np.cos(x))
# Remove first and last Y-axis tick labels for each subplot
for a in ax:
plt.setp(a.get_yticklabels()[0], visible=False)
plt.setp(a.get_yticklabels()[-1], visible=False)
plt.show()
How It Works
The code follows these key steps ?
get_yticklabels()returns a list of all Y-axis tick label objects[0]and[-1]select the first and last tick labels respectivelyplt.setp()sets thevisibleproperty toFalseThe loop applies this to all subplots in the axes array
Alternative Method: Using set_visible()
You can also directly call the set_visible() method on tick labels ?
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(2, sharex=True, figsize=(7.5, 3.5))
# Add sample data
x = np.linspace(0, 10, 100)
ax[0].plot(x, np.sin(x), label='sin(x)')
ax[1].plot(x, np.cos(x), label='cos(x)')
# Alternative method: direct set_visible()
for a in ax:
yticks = a.get_yticklabels()
if len(yticks) > 0:
yticks[0].set_visible(False)
yticks[-1].set_visible(False)
plt.tight_layout()
plt.show()
Key Points
Safety check: Always verify that tick labels exist before accessing them
Timing: Apply tick label modifications after plotting data
Layout: Use
tight_layout()orautolayout=Truefor better spacing
Conclusion
Use plt.setp() with get_yticklabels()[0] and get_yticklabels()[-1] to hide first and last Y-axis tick labels. This technique works across all subplots when applied in a loop, creating cleaner subplot visualizations.
