Mathew K Analytics

Lesson 21 · Data visualisation in python

Master Customizing Axes in Python: Ticks, Scales & Logarithmic Transformations

Welcome! In this lesson, you will learn how to fine-tune visualizations using custom tick marks and scales, including logarithmic transformations. These…

⬇ Download notebookOpen in Colab ↗

What you'll learn

Data

No separate download needed — the notebook creates or downloads everything it uses.

📓 Full notebook

Download .ipynb

Custom Ticks, Scales, and Log Transformations: A Beginner's Guide#

Welcome! In this lesson, you will learn how to fine-tune visualizations using custom tick marks and scales, including logarithmic transformations.

These skills are useful for making data easier to read and for revealing hidden patterns.

We will use real-world data and hands-on examples. Let us get started!

import warnings
warnings.filterwarnings("ignore")

# Standard imports for this lesson
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

What Are Custom Ticks and Scales?#

When you plot data, Python automatically picks where the axis marks (called ticks) go.

But sometimes, you may want to control the numbers and labels that appear on your plot.

You can also change the scale of your graph, for example, to zoom in on small changes or to spread out big numbers.

A log scale is very useful for seeing patterns in data that grows quickly or covers a wide range.

# Data setup: Load airline passengers dataset
url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/airline-passengers.csv"
df = pd.read_csv(url, parse_dates=["Month"])
print("Data shape:", df.shape)
df.head()
Data shape: (144, 2)
Month Passengers
0 1949-01-01 112
1 1949-02-01 118
2 1949-03-01 132
3 1949-04-01 129
4 1949-05-01 121
# Simple line chart: monthly passengers
plt.figure(figsize=(8,4))
plt.plot(df['Month'], df['Passengers'])
plt.title('Monthly Airline Passengers (Thousands)')
plt.xlabel('Date')
plt.ylabel('Passengers')
plt.show()
No description has been provided for this image

Why Customize Ticks?#

Sometimes, the default ticks are not clear, overlap, or miss important points.

Custom ticks help highlight facts, dates, or unusual values.

For example, we may want to show a tick mark for each new year.

# Customize x-axis to show ticks for each January
plt.figure(figsize=(8,4))
plt.plot(df['Month'], df['Passengers'])
plt.title('Monthly Airline Passengers (Thousands)')
plt.xlabel('Date')
plt.ylabel('Passengers')

jan_ticks = df[df['Month'].dt.month == 1]['Month']
plt.xticks(jan_ticks, [dt.strftime('%Y') for dt in jan_ticks], rotation=45)

plt.show()
No description has been provided for this image
# Custom y-ticks: Evenly spaced numbers every 100
plt.figure(figsize=(8,4))
plt.plot(df['Month'], df['Passengers'])
plt.title('Monthly Airline Passengers (Thousands)')
plt.xlabel('Date')
plt.ylabel('Passengers')

plt.yticks(np.arange(100, 700, 100))
plt.show()
No description has been provided for this image

Setting Custom Labels#

You can also replace numbers on the axis with your own labels.

This helps when you want to show special events or call out important values.

# Replace y-axis numbers with text labels
plt.figure(figsize=(8,4))
plt.plot(df['Month'], df['Passengers'])
plt.title('Monthly Airline Passengers (Thousands)')

labels = ['Low','Below Avg','Avg','Above Avg','High','Very High']
positions = np.arange(100, 700, 100)
plt.yticks(positions, labels)

plt.xlabel('Date')
plt.ylabel('Passengers')
plt.show()
No description has been provided for this image

Changing the Scale: Linear and Logarithmic#

A linear scale means each step on the axis adds the same amount.

A logarithmic (log) scale means each step multiplies instead.

Log scales are great when data grows or shrinks very quickly.

# Plot passengers using a log scale for y-axis
plt.figure(figsize=(8,4))
plt.plot(df['Month'], df['Passengers'])
plt.title('Log Scale: Monthly Airline Passengers')
plt.xlabel('Date')
plt.ylabel('Passengers')
plt.yscale('log')
plt.show()
No description has been provided for this image
# What happens if your data includes zeros?
df2 = df.copy()
df2.loc[df2.index[0], 'Passengers'] = 0
try:
    plt.figure(figsize=(8,4))
    plt.plot(df2['Month'], df2['Passengers'])
    plt.yscale('log')
    plt.show()
except Exception as e:
    print("Error:", e)
    
No description has been provided for this image
# Fix zeros for log plots: add a small value
df_fixed = df2.copy()
df_fixed['Passengers_fixed'] = df_fixed['Passengers'].replace(0, 1)
plt.figure(figsize=(8,4))
plt.plot(df_fixed['Month'], df_fixed['Passengers_fixed'])
plt.title('Log Scale (Zero Fixed)')
plt.yscale('log')
plt.xlabel('Date')
plt.ylabel('Passengers')
plt.show()
No description has been provided for this image

Adding Grid Lines: Make Trends Stand Out#

Grid lines help the eye compare data points.

You can add or remove grids and decide if you want them for x, y, or both axes.

# Draw grid lines just for y-axis
plt.figure(figsize=(8,4))
plt.plot(df['Month'], df['Passengers'])
plt.title('Grid Only On Y-Axis')
plt.xlabel('Date')
plt.ylabel('Passengers')

plt.grid(axis='y', linestyle='--', color='grey', alpha=0.7)
plt.show()
No description has been provided for this image
# Format large numbers: Scientific notation on y-axis
plt.figure(figsize=(8,4))
plt.plot(df['Month'], df['Passengers'])
plt.title('Scientific Format Y-Axis')
plt.xlabel('Date')
plt.ylabel('Passengers')

plt.ticklabel_format(axis='y', style='sci', scilimits=(2,3))
plt.show()
No description has been provided for this image
# Mini-project: Compare before and after using log scale and custom ticks
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10,8))

# Linear scale
ax1.plot(df['Month'], df['Passengers'])
ax1.set_title('Linear Scale')
ax1.set_ylabel('Passengers')
ax1.set_xticks(df[df['Month'].dt.month == 1]['Month'][::2])
ax1.set_xticklabels([dt.strftime('%Y') for dt in df[df['Month'].dt.month == 1]['Month'][::2]], rotation=45)

# Log scale
ax2.plot(df['Month'], df['Passengers'])
ax2.set_title('Log Scale')
ax2.set_ylabel('Passengers')
ax2.set_xlabel('Date')
ax2.set_yscale('log')
ax2.set_xticks(df[df['Month'].dt.month == 1]['Month'][::2])
ax2.set_xticklabels([dt.strftime('%Y') for dt in df[df['Month'].dt.month == 1]['Month'][::2]], rotation=45)

plt.tight_layout()
plt.show()
No description has been provided for this image
# Best practices: Always label your ticks clearly
#   - Too many ticks can clutter the plot
#   - Too few ticks may miss key patterns
#   - Use log scale with care if zeros or negatives are present

plt.figure(figsize=(8,4))
plt.plot(df['Month'], df['Passengers'])
plt.title('Clear Labels and Log Considerations')
plt.xlabel('Date')
plt.ylabel('Passengers')
plt.xticks(df[df['Month'].dt.month == 7]['Month'][::3], [dt.strftime('%Y') for dt in df[df['Month'].dt.month == 7]['Month'][::3]], rotation=30)
plt.yticks(np.arange(100, 700, 200))
plt.tight_layout()
plt.show()
No description has been provided for this image
# Troubleshooting: Tick labels do not appear or overlap?
#   - Use plt.tight_layout()
#   - Rotate labels
#   - Reduce number of ticks

plt.figure(figsize=(8,4))
plt.plot(df['Month'], df['Passengers'])
plt.title('Troubleshooting Tick Labels')
plt.xlabel('Date')
plt.ylabel('Passengers')
plt.xticks(df[df['Month'].dt.month == 1]['Month'][::4], [dt.strftime('%Y') for dt in df[df['Month'].dt.month == 1]['Month'][::4]], rotation=60)
plt.tight_layout()
plt.show()
No description has been provided for this image
# Extra tip: Minor ticks for more detail
plt.figure(figsize=(8,4))
plt.plot(df['Month'], df['Passengers'])
plt.title('With Minor Ticks')
plt.xlabel('Date')
plt.ylabel('Passengers')
plt.minorticks_on()
plt.grid(which='minor', linestyle=':', color='orange', alpha=0.3)
plt.grid(which='major', linestyle='-', color='grey', alpha=0.7)

plt.show()
No description has been provided for this image
# Challenge: Let the user set a custom y-tick value
user_step = int(input("Enter a step size for y-ticks (example: 50): "))

plt.figure(figsize=(8,4))
plt.plot(df['Month'], df['Passengers'])
plt.title('Y-Ticks With Your Step Size')
plt.xlabel('Date')
plt.ylabel('Passengers')
plt.yticks(np.arange(100, 700, user_step))
plt.tight_layout()
plt.show()
No description has been provided for this image

Lesson Recap#

You learned how to:

  • Add custom ticks and labels
  • Switch between linear and log scales
  • Fix tick overlap and use grids
  • Make your charts easier to read and present

Custom ticks and scales help your visualizations stand out, whether for a report, website, or a simple project.

Keep Practicing and Subscribe for More#

Try these tips on your own data. Can you make a plot with custom ticks for holidays or events?

If you found this lesson helpful, like and subscribe on YouTube to see more beginner-friendly Python tutorials!

Happy coding!

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.