brokenaxes icon indicating copy to clipboard operation
brokenaxes copied to clipboard

Fix IndexError when axis has only a single tick

Open Copilot opened this issue 7 months ago • 0 comments

The standardize_ticks() method in BrokenAxes would raise an IndexError when an axis had only a single tick location. This occurred because the code assumed at least 2 tick locations when calculating tick spacing.

Problem

The issue manifested when:

import matplotlib.pyplot as plt
from brokenaxes import brokenaxes

# Create a scenario that results in single ticks
bax = brokenaxes(xlims=((0, 1),), ylims=((0, 1),))

# Force single ticks to trigger the issue
for ax in bax.axs:
    ax.set_xticks([0.5])  # Only one tick
    ax.set_yticks([0.5])  # Only one tick

# This would raise: IndexError: index 1 is out of bounds for axis 0 with size 1
bax.standardize_ticks()

Root Cause

Lines 291, 297, 304, and 310 in standardize_ticks() attempted to access get_ticklocs()[1] without checking if the array had at least 2 elements:

# This fails when get_ticklocs() returns only [single_value]
ax.xaxis.get_ticklocs()[1] - ax.xaxis.get_ticklocs()[0]  # IndexError!

Solution

Added robust handling for single tick scenarios:

  1. Check tick count: Verify len(ticklocs) >= 2 before accessing the second element
  2. Intelligent fallbacks: When insufficient ticks are available:
    • Linear scale: Use (axis_range) / 5 as reasonable tick spacing
    • Log scale: Use base 10 as default logarithmic base
  3. Preserve existing behavior: Multiple tick scenarios work exactly as before

Changes

  • Fixed standardize_ticks() method in brokenaxes.py (lines 288-319)
  • Added comprehensive test test_single_tick_handling() in test.py

Testing

✅ All existing tests pass (19/19)
✅ New test validates single tick scenarios
✅ Edge cases tested: zero ticks, negative values, large values, log scale
✅ Visual verification confirms functionality

The fix is minimal and maintains full backward compatibility while robustly handling the edge case of single-tick axes.

Fixes #128.


💬 Share your feedback on Copilot coding agent for the chance to win a $200 gift card! Click here to start the survey.

Copilot avatar Jul 21 '25 11:07 Copilot