Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

seaborn.objects: Add formatting string argument to Text mark #3427

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
22 changes: 22 additions & 0 deletions doc/_docstrings/objects.Text.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -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": []
}
],
Expand Down
3 changes: 2 additions & 1 deletion seaborn/_marks/text.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):

Expand All @@ -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,
Expand Down
6 changes: 6 additions & 0 deletions tests/_marks/test_text.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Loading