Course contentsShow
← Data Science
Lesson 1261 of 2,14532. Visualization with Matplotlib and SeabornFree lesson

Controlling Axes Limits and Scales

Setting xlim() and ylim(), using log scales, and controlling tick positions for better data display.

Controlling Axes Limits and Scales

You'll learn how to frame your data perfectly by adjusting axis boundaries, switching to logarithmic scales, and placing ticks exactly where you need them.

Think of your plot's axes like the frame and zoom of a camera—sometimes you need to zoom in on a specific range, and other times you need to change the entire perspective to reveal patterns hidden in your data.

Setting Axis Limits

By default, Matplotlib automatically fits your axes to your data, but you often want manual control. Use xlim() and ylim() to set the visible range:

import matplotlib.pyplot as plt

plt.plot([1, 2, 3, 4], [10, 20, 25, 30])
plt.xlim(0, 5)      # Set x-axis from 0 to 5
plt.ylim(0, 40)     # Set y-axis from 0 to 40
plt.show()

This is crucial when comparing multiple plots—keeping consistent limits makes visual comparison meaningful.

Using Logarithmic Scales

When data spans several orders of magnitude (like 1, 10, 100, 1000), a logarithmic scale compresses large values and expands small ones, revealing relationships that would otherwise be invisible:

plt.plot([1, 10, 100, 1000], [2, 4, 6, 8])
plt.yscale('log')   # Switch y-axis to logarithmic scale
plt.show()

Controlling Tick Positions

Ticks are the markers on your axes. You can place them strategically using xticks() and yticks():

plt.plot([1, 2, 3, 4], [10, 20, 25, 30])
plt.xticks([1, 2, 3, 4])           # Specify exact tick positions
plt.yticks([10, 20, 30])           # Show only these y values
plt.show()

This helps highlight specific data points or create cleaner, more readable axes.

Key Takeaway: Mastering xlim(), ylim(), logarithmic scales, and tick positioning gives you precise control over how your data appears, making patterns clearer and comparisons fairer.