Axis Properties and Scales

Back

Loading concept...

🎨 Matplotlib Axis Configuration: Becoming the Master of Your Canvas

Imagine you’re an artist with a magical canvas. This canvas can stretch, flip, zoom, and transform in any way you want. That’s exactly what Matplotlib axes are—your playground for data visualization!


🌟 The Big Picture

Think of a graph like a window looking into your data world. The axes are the frame of that window. You decide:

  • How big the frame is
  • Which direction it faces
  • What scale it uses
  • Whether it has borders or not

Let’s learn to control this magical frame!


📏 Setting Axis Limits

What’s This About?

Imagine looking through a window. You can only see what’s inside the frame. Axis limits decide what part of your data world you can see.

The Simple Way

import matplotlib.pyplot as plt

plt.plot([1, 2, 3, 4], [1, 4, 9, 16])

# Set what we can see
plt.xlim(0, 5)    # X: from 0 to 5
plt.ylim(0, 20)   # Y: from 0 to 20

plt.show()

The Object Way

fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [1, 4, 9, 16])

ax.set_xlim(0, 5)
ax.set_ylim(0, 20)

plt.show()

🎯 Pro Tip: Get Current Limits

x_min, x_max = ax.get_xlim()
y_min, y_max = ax.get_ylim()

🤖 Axis Auto-scaling

What’s This About?

Sometimes you want Matplotlib to be smart and figure out the best limits automatically. Like a camera that auto-focuses!

Let Matplotlib Decide

fig, ax = plt.subplots()
ax.plot([1, 2, 3], [10, 20, 30])

# Auto-scale both axes
ax.autoscale()

# Or just one axis
ax.autoscale(axis='x')
ax.autoscale(axis='y')

Adding Breathing Room

# Add 10% padding around your data
ax.margins(0.1)

# Different padding for x and y
ax.margins(x=0.05, y=0.1)

Turn Auto-scaling On/Off

# Turn it off
ax.autoscale(enable=False)

# Turn it back on
ax.autoscale(enable=True)

⚖️ Aspect Ratio Control

What’s This About?

Should a square in your data look like a square on screen? Or can it be stretched into a rectangle? Aspect ratio controls this!

Making Things Equal

fig, ax = plt.subplots()
ax.plot([0, 1, 1, 0, 0], [0, 0, 1, 1, 0])

# Circle looks like a circle!
ax.set_aspect('equal')

plt.show()

Different Options

# Equal: 1 unit on X = 1 unit on Y
ax.set_aspect('equal')

# Auto: Matplotlib decides (default)
ax.set_aspect('auto')

# Custom ratio: 2 units X = 1 unit Y
ax.set_aspect(2)

🎯 Real Example: Drawing a Circle

import numpy as np

theta = np.linspace(0, 2*np.pi, 100)
x = np.cos(theta)
y = np.sin(theta)

fig, (ax1, ax2) = plt.subplots(1, 2)

ax1.plot(x, y)
ax1.set_title('Auto: Oval!')

ax2.plot(x, y)
ax2.set_aspect('equal')
ax2.set_title('Equal: Circle!')

plt.show()

🔄 Inverted Axes

What’s This About?

Normally, numbers go up and right. But sometimes you want them to go backwards! Like reading from right to left, or showing depth going down.

Flip the X-Axis

fig, ax = plt.subplots()
ax.plot([1, 2, 3], [10, 20, 30])

# Numbers go right to left
ax.invert_xaxis()

plt.show()

Flip the Y-Axis

# Numbers go top to bottom
ax.invert_yaxis()

🎯 Real Use: Image Display

# Images have (0,0) at top-left
# So we often invert Y
ax.imshow(my_image)
# Y is already inverted for images!

Check If Inverted

if ax.xaxis_inverted():
    print("X is flipped!")

if ax.yaxis_inverted():
    print("Y is flipped!")

📊 Linear and Log Scales

What’s This About?

Think of a ruler. Normal rulers have equal spacing (1, 2, 3, 4…). That’s linear.

But what if the numbers grow super fast? (1, 10, 100, 1000…). Then logarithmic scale helps!

Linear Scale (Default)

fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [10, 100, 1000, 10000])

ax.set_yscale('linear')  # Default
plt.show()

Logarithmic Scale

fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [10, 100, 1000, 10000])

ax.set_yscale('log')  # Magic!
plt.show()

🎯 When to Use Log Scale?

  • Data spans many orders of magnitude
  • Exponential growth (bacteria, money)
  • Scientific measurements
  • Audio/sound levels
graph TD A["Your Data"] --> B{Spans many<br>magnitudes?} B -->|Yes| C["Use Log Scale"] B -->|No| D["Use Linear Scale"] C --> E["10, 100, 1000&lt;br&gt;look evenly spaced"] D --> F["1, 2, 3&lt;br&gt;look evenly spaced"]

📈 Semilog and Symlog Scales

Semilog: Half Linear, Half Log

Sometimes only one axis needs the log treatment!

fig, (ax1, ax2) = plt.subplots(1, 2)

data = [1, 10, 100, 1000, 10000]

# Log on Y only
ax1.semilogy([1, 2, 3, 4, 5], data)
ax1.set_title('semilogy')

# Log on X only
ax2.semilogx(data, [1, 2, 3, 4, 5])
ax2.set_title('semilogx')

plt.show()

Symlog: Log That Handles Negatives!

Regular log can’t handle zero or negative numbers. Symlog can!

fig, ax = plt.subplots()

# Data with negatives and zero
data = [-1000, -100, -10, 0, 10, 100, 1000]
ax.plot(data)

# Symlog handles it all!
ax.set_yscale('symlog')

plt.show()

🎯 Symlog Settings

# linthresh: where linear region ends
ax.set_yscale('symlog', linthresh=10)

# linscale: how wide is linear region
ax.set_yscale('symlog', linscale=0.5)
graph TD A["Choose Scale"] --> B{Has negative<br>or zero values?} B -->|Yes| C["Use Symlog"] B -->|No| D{Need log<br>on both axes?} D -->|Both| E["Use loglog"] D -->|X only| F["Use semilogx"] D -->|Y only| G["Use semilogy"]

🖼️ Spine Customization

What’s This About?

Spines are the four borders of your plot—top, bottom, left, right. You can style them, move them, or hide them!

Hide Some Spines

fig, ax = plt.subplots()
ax.plot([1, 2, 3], [1, 4, 9])

# Hide top and right spines
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)

plt.show()

Move Spines to Center

fig, ax = plt.subplots()
ax.plot([-3, -2, -1, 0, 1, 2, 3],
        [9, 4, 1, 0, 1, 4, 9])

# Move bottom spine to y=0
ax.spines['bottom'].set_position('zero')

# Move left spine to x=0
ax.spines['left'].set_position('zero')

# Hide the others
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)

plt.show()

Style Your Spines

# Change color
ax.spines['bottom'].set_color('red')

# Change thickness
ax.spines['left'].set_linewidth(2)

# Make it dashed
ax.spines['bottom'].set_linestyle('--')

🎯 Position Options

# At a specific value
ax.spines['bottom'].set_position(('data', 0))

# At the center
ax.spines['left'].set_position('center')

# At the axes edge (default)
ax.spines['bottom'].set_position(('axes', 0))

🚫 Removing Axes and Frames

What’s This About?

Sometimes you just want to show the picture without any borders, ticks, or labels. Perfect for images or clean presentations!

Hide Everything

fig, ax = plt.subplots()
ax.plot([1, 2, 3], [1, 4, 9])

# Turn off the entire axis
ax.axis('off')

plt.show()

Hide Just Ticks

# Hide tick marks
ax.set_xticks([])
ax.set_yticks([])

# Or hide tick labels only
ax.set_xticklabels([])
ax.set_yticklabels([])

Hide Frame But Keep Labels

fig, ax = plt.subplots()
ax.plot([1, 2, 3], [1, 4, 9])

# Remove the box frame
ax.set_frame_on(False)

# Or hide all spines
for spine in ax.spines.values():
    spine.set_visible(False)

plt.show()

🎯 Quick Options

# Show normal axes
ax.axis('on')

# Hide everything
ax.axis('off')

# Equal aspect + tight limits
ax.axis('equal')

# Tight limits only
ax.axis('tight')

# Square plot
ax.axis('square')

🎮 Putting It All Together

Here’s a complete example using many concepts:

import matplotlib.pyplot as plt
import numpy as np

fig, axes = plt.subplots(2, 2, figsize=(8, 8))

# Plot 1: Custom limits
ax1 = axes[0, 0]
ax1.plot([1, 2, 3], [1, 4, 9])
ax1.set_xlim(0, 4)
ax1.set_ylim(0, 12)
ax1.set_title('Custom Limits')

# Plot 2: Log scale
ax2 = axes[0, 1]
ax2.plot([1, 2, 3, 4], [10, 100, 1000, 10000])
ax2.set_yscale('log')
ax2.set_title('Log Scale')

# Plot 3: Clean spines
ax3 = axes[1, 0]
ax3.plot([1, 2, 3], [1, 4, 9])
ax3.spines['top'].set_visible(False)
ax3.spines['right'].set_visible(False)
ax3.set_title('Clean Spines')

# Plot 4: Equal aspect
ax4 = axes[1, 1]
theta = np.linspace(0, 2*np.pi, 100)
ax4.plot(np.cos(theta), np.sin(theta))
ax4.set_aspect('equal')
ax4.set_title('Equal Aspect')

plt.tight_layout()
plt.show()

🏆 Quick Reference

Task Code
Set X limits ax.set_xlim(0, 10)
Set Y limits ax.set_ylim(0, 20)
Auto-scale ax.autoscale()
Add margins ax.margins(0.1)
Equal aspect ax.set_aspect('equal')
Invert X ax.invert_xaxis()
Invert Y ax.invert_yaxis()
Log scale ax.set_yscale('log')
Symlog scale ax.set_yscale('symlog')
Hide spine ax.spines['top'].set_visible(False)
Hide axis ax.axis('off')

🎉 You Did It!

You now have complete control over your Matplotlib canvas. You can:

  • ✅ Zoom in and out with axis limits
  • ✅ Let Python decide with auto-scaling
  • ✅ Keep shapes true with aspect ratio
  • ✅ Flip your view with inverted axes
  • ✅ Handle big numbers with log scales
  • ✅ Work with negatives using symlog
  • ✅ Style borders with spine customization
  • ✅ Go minimal by removing axes

Go create something beautiful! 🎨

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.