diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index cb2a59860783f..a63bd2fe749f5 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -32,6 +32,7 @@ Other enhancements - Add support for assigning values to ``by`` argument in :meth:`DataFrame.plot.hist` and :meth:`DataFrame.plot.box` (:issue:`15079`) - :meth:`Series.sample`, :meth:`DataFrame.sample`, and :meth:`.GroupBy.sample` now accept a ``np.random.Generator`` as input to ``random_state``. A generator will be more performant, especially with ``replace=False`` (:issue:`38100`) - Additional options added to :meth:`.Styler.bar` to control alignment and display, with keyword only arguments (:issue:`26070`, :issue:`36419`) +- :meth:`Styler.bar` now validates the input argument ``width`` and ``height`` (:issue:`42511`) - :meth:`Series.ewm`, :meth:`DataFrame.ewm`, now support a ``method`` argument with a ``'table'`` option that performs the windowing operation over an entire :class:`DataFrame`. See :ref:`Window Overview ` for performance and functional benefits (:issue:`42273`) - diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index 0e89f21fe2431..cb56ea33acad8 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -2129,6 +2129,11 @@ def bar( "(eg: color=['#d65f5f', '#5fba7d'])" ) + if not (0 <= width <= 100): + raise ValueError(f"`width` must be a value in [0, 100], got {width}") + elif not (0 <= height <= 100): + raise ValueError(f"`height` must be a value in [0, 100], got {height}") + if subset is None: subset = self.data.select_dtypes(include=np.number).columns diff --git a/pandas/tests/io/formats/style/test_bar.py b/pandas/tests/io/formats/style/test_bar.py index aa115624ec2f1..19884aaac86a7 100644 --- a/pandas/tests/io/formats/style/test_bar.py +++ b/pandas/tests/io/formats/style/test_bar.py @@ -291,8 +291,17 @@ def test_bar_align_height(): assert result == expected -def test_bar_bad_align_raises(): +def test_bar_value_error_raises(): df = DataFrame({"A": [-100, -60, -30, -20]}) + msg = "`align` should be in {'left', 'right', 'mid', 'mean', 'zero'} or" with pytest.raises(ValueError, match=msg): - df.style.bar(align="poorly", color=["#d65f5f", "#5fba7d"]).render() + df.style.bar(align="poorly", color=["#d65f5f", "#5fba7d"]).to_html() + + msg = r"`width` must be a value in \[0, 100\]" + with pytest.raises(ValueError, match=msg): + df.style.bar(width=200).to_html() + + msg = r"`height` must be a value in \[0, 100\]" + with pytest.raises(ValueError, match=msg): + df.style.bar(height=200).to_html()