Python Matplotlib X-Axis Label Spacing and Removing Labels

As a Python developer with over seven years of experience working extensively with Matplotlib, I’ve encountered many scenarios where fine-tuning x-axis labels made a significant difference in the clarity and professionalism of my plots.

In this tutorial, I’ll share practical methods to adjust the spacing between x-axis labels and how to remove them when needed. These techniques help you create clean, readable, and visually appealing charts that communicate your insights effectively.

How to Adjust Matplotlib X-Axis Label Spacing in Python

Sometimes, the default spacing of x-axis labels in Matplotlib causes labels to overlap or clutter, especially when you have many data points or lengthy labels like city names or dates. I’ve found two reliable ways to manage label spacing in Python plots.

Method 1: Use plt.xticks() with Rotation and Padding

One simple way to improve label spacing is by rotating the labels and adding padding. Rotating labels reduces horizontal crowding, while padding moves labels slightly away from the axis.

Here’s an example using U.S. state abbreviations on the x-axis:

import matplotlib.pyplot as plt

states = ['CA', 'TX', 'NY', 'FL', 'IL', 'PA', 'OH', 'GA', 'NC', 'MI']
sales = [250, 200, 180, 160, 150, 140, 130, 120, 110, 100]

plt.figure(figsize=(10, 6))
plt.bar(states, sales, color='skyblue')

# Rotate x-axis labels and add padding
plt.xticks(rotation=45, ha='right', fontsize=12)
plt.tight_layout()  # Adjust layout to fit labels better

plt.title('Sales by State in the USA')
plt.xlabel('State')
plt.ylabel('Sales (in thousands)')
plt.show()

I executed the above example code and added the screenshot below.

Matplotlib X-Axis Label Spacing Labels

In this code, rotating the labels 45 degrees and aligning them to the right (ha=’right’) prevents overlap. Using plt.tight_layout() ensures the plot adjusts automatically to accommodate the rotated labels.

Method 2: Use MaxNLocator to Limit Number of Labels

When you have too many x-axis points, displaying every label is impractical. I use Matplotlib’s MaxNLocator to limit the number of ticks shown, which spaces out labels evenly.

import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator

months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
revenue = [1200, 1150, 1300, 1400, 1600, 1700, 1800, 1750, 1650, 1500, 1400, 1300]

plt.figure(figsize=(12, 6))
plt.plot(months, revenue, marker='o')

ax = plt.gca()
ax.xaxis.set_major_locator(MaxNLocator(nbins=6))  # Show max 6 labels evenly spaced

plt.title('Monthly Revenue for USA-based Company')
plt.xlabel('Month')
plt.ylabel('Revenue ($)')
plt.grid(True)
plt.show()

I executed the above example code and added the screenshot below.

Python Matplotlib X-Axis Label Spacing Labels

By setting nbins=6, the plot shows only six x-axis labels, spaced evenly to avoid clutter. This method is excellent for time series data with many points.

How to Remove Matplotlib X-Axis Labels in Python

There are situations where removing x-axis labels altogether improves the plot’s readability, especially when labels are redundant or the focus is on trends rather than specific categories. Here are two effective methods I use to remove x-axis labels.

Method 1: Use plt.xticks([]) to Remove All Labels

The simplest way to remove all x-axis labels is by passing an empty list to plt.xticks(). This hides the labels but keeps the ticks visible.

import matplotlib.pyplot as plt

years = [2015, 2016, 2017, 2018, 2019, 2020]
profits = [50000, 52000, 58000, 60000, 62000, 64000]

plt.figure(figsize=(8, 5))
plt.plot(years, profits, marker='s', color='green')

# Remove x-axis labels
plt.xticks([])

plt.title('Company Profit Over Years')
plt.ylabel('Profit ($)')
plt.show()

I executed the above example code and added the screenshot below.

Matplotlib X-Axis Label Removing Labels

This method is quick and useful when you want a minimalist look without x-axis text.

Method 2: Use ax.set_xticklabels([]) to Remove Labels but Keep Ticks

If you want to keep the tick marks but remove only the labels, you can use the set_xticklabels() method on the axis object.

import matplotlib.pyplot as plt

quarters = ['Q1', 'Q2', 'Q3', 'Q4']
growth = [5, 7, 6, 8]

fig, ax = plt.subplots(figsize=(7, 4))
ax.bar(quarters, growth, color='orange')

# Remove x-axis labels but keep ticks
ax.set_xticklabels([])

ax.set_title('Quarterly Growth Rate')
ax.set_ylabel('Growth (%)')
plt.show()

I executed the above example code and added the screenshot below.

Python Matplotlib X-Axis Label Removing Labels

This approach is helpful when you want to preserve the tick marks for reference without cluttering the axis with labels.

By mastering these Matplotlib x-axis label spacing and removal techniques in Python, you can greatly enhance your charts’ readability and professionalism. Whether you’re presenting sales data across U.S. states or tracking quarterly growth, controlling label appearance ensures your audience focuses on the insights, not on deciphering cramped or excessive text.

Experiment with these methods to find what works best for your specific datasets. Clean and clear visualization is key to effective communication in data science and analytics.

You may also read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.