In matplotlib how to hide given tick, but keep displaying tick label?
2/2
Sep 15, 4:51pm
In Matplotlib, ticks and tick labels are typically linked—hiding a tick usually hides its label as well. However, if you want to hide a specific tick line (the small mark on the axis) while keeping its label visible, you can achieve this by manually setting the tick properties.
Here’s how you can do it:
Steps:
Get the current axis using plt.gca() or ax = plt.subplot().
Set the tick positions explicitly using ax.set_xticks() or ax.set_yticks().
Hide the tick lines by setting their length to 0 using ax.tick_params() or by modifying the tick properties directly.
Example:
Suppose you want to hide the tick at x=2 but keep its label:
python
import matplotlib.pyplot as plt
# Sample data
x = [1, 2, 3, 4]
y = [10, 20, 15, 25]
fig, ax = plt.subplots()
ax.plot(x, y)
# Set ticks explicitly
ax.set_xticks([1, 2, 3, 4])
# Hide the tick at x=2 but keep its label
for tick in ax.xaxis.get_major_ticks():
if tick.get_loc() == 2:
tick.tick1line.set_visible(False) # Hide the tick line
tick.tick2line.set_visible(False) # Hide the tick line (for top axis if applicable)
plt.show()
Explanation:
tick.tick1line.set_visible(False) hides the bottom tick line (for the x-axis).
tick.tick2line.set_visible(False) hides the top tick line (if applicable).
The label remains visible because we only modified the tick line properties.
Alternative Approach:
If you want to hide all ticks but keep all labels, you can use:
python
ax.tick_params(axis='x', length=0) # Hide all x-axis ticks but keep labels
This will hide all tick lines while preserving the labels. If you only want to hide specific ticks, use the first method.
Sep 15, 4:51pm
This is a shared conversation and may include unverified content that doesn't reflect Mistral AI's views. Login to resume chatting.