Skip to content

Commit

Permalink
Fix direct mapping to sequences with one item
Browse files Browse the repository at this point in the history
fixes #733
  • Loading branch information
has2k1 committed Jan 4, 2024
1 parent 346e10d commit c4dc225
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 6 deletions.
7 changes: 6 additions & 1 deletion plotnine/guides/guide_legend.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,12 @@ def train(self, scale, aesthetic=None):
# create a hash of the important information in the guide
labels = " ".join(str(x) for x in self.key["label"])
info = "\n".join(
[self.title, labels, str(self.direction), self.__class__.__name__]
[
str(self.title),
labels,
str(self.direction),
self.__class__.__name__,
]
)
self.hash = hashlib.sha256(info.encode("utf-8")).hexdigest()
return self
Expand Down
13 changes: 8 additions & 5 deletions plotnine/mapping/aes.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import re
import typing
from collections.abc import Iterable
from collections.abc import Iterable, Sequence
from contextlib import suppress
from copy import deepcopy
from dataclasses import fields
Expand All @@ -14,7 +14,7 @@
from .evaluation import after_stat, stage

if typing.TYPE_CHECKING:
from typing import Sequence, TypeVar
from typing import TypeVar

THasAesNames = TypeVar("THasAesNames", bound=list[str] | dict[str, Any])

Expand Down Expand Up @@ -503,10 +503,14 @@ def make_labels(mapping: dict[str, Any] | aes) -> labels_view:
"""

def _nice_label(value: Any) -> str | None:
if isinstance(value, pd.Series):
if isinstance(value, str):
return value
elif isinstance(value, pd.Series):
return value.name # pyright: ignore
elif not isinstance(value, Iterable) or isinstance(value, str):
elif not isinstance(value, Iterable):
return str(value)
elif isinstance(value, Sequence) and len(value) == 1:
return str(value[0])
else:
return None

Expand All @@ -519,7 +523,6 @@ def _make_label(ae: str, value: Any) -> str | None:
elif value.after_scale is not None:
return value.after_scale
else:
# return ''
raise ValueError("Unknown mapping")
else:
if value.after_stat is not None:
Expand Down
11 changes: 11 additions & 0 deletions tests/test_aes.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
stat_ecdf,
stat_function,
)
from plotnine.mapping.aes import make_labels

data = pd.DataFrame(
{
Expand Down Expand Up @@ -93,3 +94,13 @@ def test_geom_crossbar(self):
+ scale_y_log10()
)
assert p == "geom_crossbar"


def test_make_labels():
mapping = {"y": "y", "color": ["Treatment"]}
labels = make_labels(mapping)
assert labels.color == "Treatment"

mapping = {"y": "y", "color": ["Treatment", "Control"]}
labels = make_labels(mapping)
assert labels.color is None

0 comments on commit c4dc225

Please sign in to comment.