diff --git a/doc/_docstrings/objects.Text.ipynb b/doc/_docstrings/objects.Text.ipynb index 4d8f3204af..ba41807567 100644 --- a/doc/_docstrings/objects.Text.ipynb +++ b/doc/_docstrings/objects.Text.ipynb @@ -155,12 +155,34 @@ ")" ] }, + { + "cell_type": "markdown", + "id": "ee2597dc", + "metadata": {}, + "source": [ + "Use `fmt` to format the text before display:" + ] + }, { "cell_type": "code", "execution_count": null, "id": "95fb7aee-090a-4415-917c-b5258d2b298b", "metadata": {}, "outputs": [], + "source": [ + "(\n", + " so.Plot(glue, x=\"Average\", y=\"Model\", text=\"Average\")\n", + " .add(so.Bar())\n", + " .add(so.Text(color=\"w\", halign=\"right\", fmt=\"{:.0f}\"))\n", + ")\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "87db5959", + "metadata": {}, + "outputs": [], "source": [] } ], diff --git a/seaborn/_marks/text.py b/seaborn/_marks/text.py index 58d757c1ac..a247a006be 100644 --- a/seaborn/_marks/text.py +++ b/seaborn/_marks/text.py @@ -36,6 +36,7 @@ class Text(Mark): halign: MappableString = Mappable("center") valign: MappableString = Mappable("center_baseline") offset: MappableFloat = Mappable(4) + fmt: str = "{}" def _plot(self, split_gen, scales, orient): @@ -61,7 +62,7 @@ def _plot(self, split_gen, scales, orient): artist = mpl.text.Text( x=row["x"], y=row["y"], - text=str(row.get("text", vals["text"])), + text=self.fmt.format(row.get("text", vals["text"])), color=color, fontsize=fontsize, horizontalalignment=halign, diff --git a/tests/_marks/test_text.py b/tests/_marks/test_text.py index 241b1742e0..4e399441cd 100644 --- a/tests/_marks/test_text.py +++ b/tests/_marks/test_text.py @@ -127,3 +127,9 @@ def test_offset_halign(self): for text in self.get_texts(ax): shift_matrix = text.get_transform().get_matrix() - ax_trans assert_array_almost_equal(shift_matrix, expected_shift_matrix) + + def test_fmt(self): + m = Text(fmt="{:.2f}") + p = Plot(x=[0], y=[0], text=[1.234]).add(m).plot() + ax = p._figure.axes[0] + assert self.get_texts(ax)[0].get_text() == "1.23"