Explain Codes LogoExplain Codes Logo

Hiding axis text in matplotlib plots

python
matplotlib
axis-hiding
plot-customization
Anton ShumikhinbyAnton Shumikhin·Aug 21, 2024
TLDR

If you're in a rush, here's your quick fix. To hide axis labels in a Matplotlib plot, simply use the set_ticklabels([]) method on your axis object. Let's look at a small chunk of code that demonstrates how to hide x-axis labels:

import matplotlib.pyplot as plt # Insert your plot code here. Cooking a plot, aren't we? # Erase x-axis text plt.gca().xaxis.set_ticklabels([]) plt.show()

Notice, only labels disappear; the axis and ticks will remain.

The no-nonsense guide to hiding axis text elegantly

Hide and seek with axis

Be it x-axis or y-axis, to make the labels invisible use these:

ax.xaxis.set_visible(False) # x-axis decided to play hide and seek. ax.yaxis.set_visible(False) # y-axis joined the game.

Voila, your x-axis and y-axis labels have vanished!

Tick marks - show or no-show?

Dealing with stubborn tick marks? Just do:

ax.xaxis.set_ticks([]) # x-axis tick marks decided to stay home today. ax.yaxis.set_ticks([]) # y-axis tick marks just followed the lead.

And your pesky tick marks are gone.

Grid lines - the silent spectators

Want to maintain the grid lines while hiding the text? Easy peasy:

ax.xaxis.set_ticklabels([]) # x-axis labels left us, but the grid lines decided to stay. ax.yaxis.set_ticklabels([]) # y-axis labels and grid lines aren't attached at the hip, clearly.

So, the labels are gone, but the grid lines aren't! Party continues.

Are labels important? Ask plt.xlabel and plt.ylabel

After all the changes, if you want to add a meaningful context, go ahead and add customized labels:

plt.xlabel('My Custom X-axis Label') # Nice to see you again, X! plt.ylabel('My Custom Y-axis Label') # Y, you are always welcome.

There, we invited the labels back but with a fresh attire!

The subplot structure

Do you have more than one plot? Keep cleanliness across all your subplots:

fig, axs = plt.subplots(4, 4) # Inviting 16 friends over for ax in axs.flatten(): # Flatten them like a pancake! Just kidding ax.set_xticklabels([]) # Y'all need to leave ax.set_yticklabels([]) # You as well ax.set_xticks([]) # Can't have tick marks crashing the party ax.set_yticks([]) # Nope, none at all

Overboarding the minimalism cruise

Forget minimal, let's go all out. Remove it all:

plt.axis('off') # Plot's got nothing on. At all! It's okay, it's decent!

This code shuts off all axes, grid lines, labels, leaving your plot in its birthday suit.