Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 6 additions & 8 deletions oilpriceapi/visualization.py
Original file line number Diff line number Diff line change
Expand Up @@ -452,21 +452,19 @@ def create_small_multiples(
fig, axes = plt.subplots(
rows, cols,
figsize=(12, 3 * rows),
dpi=100
dpi=100,
# Always a 2-D grid, so axes[row][col] works for one row or one
# column too (#158).
squeeze=False
)

if rows == 1:
axes = [axes]
if cols == 1:
axes = [[ax] for ax in axes]

end_date = datetime.now()
start_date = end_date - timedelta(days=days)

for idx, commodity in enumerate(commodities):
row = idx // cols
col = idx % cols
ax = axes[row][col] if rows > 1 else axes[col]
ax = axes[row][col]

# Fetch data
history = self.client.historical.get(
Expand Down Expand Up @@ -508,7 +506,7 @@ def create_small_multiples(
for idx in range(n, rows * cols):
row = idx // cols
col = idx % cols
ax = axes[row][col] if rows > 1 else axes[col]
ax = axes[row][col]
ax.axis('off')

# Add overall title and source
Expand Down
39 changes: 39 additions & 0 deletions tests/unit/test_small_multiples.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
"""#158: create_small_multiples crashed whenever every commodity fit in one row."""
from datetime import datetime, timedelta
from types import SimpleNamespace
from unittest.mock import MagicMock

import pytest

pytest.importorskip("matplotlib")
import matplotlib # noqa: E402

matplotlib.use("Agg")
import matplotlib.pyplot as plt # noqa: E402

from oilpriceapi.visualization import PriceVisualizer # noqa: E402


def _client():
start = datetime(2026, 9, 1)
points = [
SimpleNamespace(date=start + timedelta(days=i), value=70.0 + i * 0.1)
for i in range(60)
]
client = MagicMock()
client.historical.get.return_value = SimpleNamespace(data=points)
return client


@pytest.mark.parametrize(
"n,cols",
[(1, 3), (2, 3), (3, 3), (4, 3), (6, 3), (2, 1), (1, 1), (5, 2)],
)
def test_small_multiples_any_shape(n, cols):
codes = [f"C{i}" for i in range(n)]
fig = PriceVisualizer(_client()).create_small_multiples(codes, cols=cols)
try:
titled = [ax.get_title() for ax in fig.axes if ax.get_title()]
assert titled == codes
finally:
plt.close(fig)
Loading