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
32 changes: 32 additions & 0 deletions termgraph/chart.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,38 @@ def __init__(self, data: Data, args: Args | None = None) -> None:
"""
super().__init__(data, args)

def _normalize(self) -> list[list[float]]:
"""Normalize the data so that the longest stacked bar fits the width."""
normal_data = super()._normalize()
if self.args.get_arg("scale") is not None:
return normal_data

width = self.args.get_arg("width")
if not isinstance(width, int):
width = 50 # Default width

# Data.normalize() fits the largest single value to the width, but a
# stacked bar is as long as the sum of its segments.
max_total = max((sum(row) for row in normal_data), default=0)
if max_total <= 0:
return normal_data
factor = width / max_total

# Round the running total rather than each segment, so that a bar's
# length follows its total instead of losing a block per segment.
scaled_data = []
for row in normal_data:
scaled_row = []
previous = 0
running_total = 0.0
for value in row:
running_total += value * factor
current = round(running_total)
scaled_row.append(float(current - previous))
previous = current
scaled_data.append(scaled_row)
return scaled_data

def draw(self) -> None:
"""Draws the stacked chart"""
self._print_header()
Expand Down
37 changes: 36 additions & 1 deletion tests/test_charts.py
Original file line number Diff line number Diff line change
Expand Up @@ -278,4 +278,39 @@ def test(ChartType):
assert "10" not in output
assert "20" not in output

run_for_all_charts(test)
run_for_all_charts(test)

def _stacked_bar_lengths(data_values, width):
import io
import re
from contextlib import redirect_stdout

labels = [f"row{i}" for i in range(len(data_values))]
chart = StackedChart(
Data(data_values, labels),
Args(width=width, custom_tick="X", no_values=True),
)
f = io.StringIO()
with redirect_stdout(f):
chart.draw()
lines = re.sub(r"\x1b\[[0-9;]*m", "", f.getvalue()).splitlines()
return [line.count("X") for line in lines if line.startswith("row")]


def test_stackedchart_longest_bar_fits_width():
# The full stacked bar, not its largest segment, is scaled to the width.
data_values = [
[10, 20, 40, 40, 40],
[10, 20, 40, 40, 10],
[10, 10, 10, 10, 10],
]

lengths = _stacked_bar_lengths(data_values, width=10)

assert max(lengths) == 10
assert all(length <= 10 for length in lengths)


def test_stackedchart_bar_lengths_follow_totals():
assert _stacked_bar_lengths([[1, 1], [2, 2]], width=20) == [10, 20]
assert _stacked_bar_lengths([[30, 10], [10, 30]], width=8) == [8, 8]
Loading