From c428433ed0f927647150e37de44508a6a2edfba3 Mon Sep 17 00:00:00 2001 From: Roman Claudiu Date: Sun, 8 Nov 2026 19:15:49 +0200 Subject: [PATCH] Fit stacked bars to the requested width Data.normalize() scales the largest single value to the width, so a stacked bar, which is the sum of its segments, could be several times wider than --width. Scale stacked charts by the largest row total and round the running total so that each bar's length follows its total. --- termgraph/chart.py | 32 ++++++++++++++++++++++++++++++++ tests/test_charts.py | 37 ++++++++++++++++++++++++++++++++++++- 2 files changed, 68 insertions(+), 1 deletion(-) diff --git a/termgraph/chart.py b/termgraph/chart.py index 0c02d5e..7622b44 100644 --- a/termgraph/chart.py +++ b/termgraph/chart.py @@ -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() diff --git a/tests/test_charts.py b/tests/test_charts.py index 983e08f..f6ccd5b 100644 --- a/tests/test_charts.py +++ b/tests/test_charts.py @@ -278,4 +278,39 @@ def test(ChartType): assert "10" not in output assert "20" not in output - run_for_all_charts(test) \ No newline at end of file + 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]