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

Updates in legend #58

Merged
merged 6 commits into from
Sep 7, 2024
Merged
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
8 changes: 4 additions & 4 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -72,11 +72,11 @@ testing = [

docs = [
"mkdocs",
"mkdocs-autorefs==0.5.0",
"mkdocs-material==9.5.2",
"mkdocs-autorefs==1.0.1",
"mkdocs-material==9.5.23",
"mkdocs-material-extensions==1.3.1",
"mkdocstrings==0.24.0",
"mkdocstrings-python==1.7.5",
"mkdocstrings==0.25.2",
"mkdocstrings-python==1.10.8",
"mkdocs-gen-files",
"matplotlib>=3.8.2",
"imageio>=2.9.0",
Expand Down
2 changes: 1 addition & 1 deletion tests/test_canvas.py
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ def test_legend(backend: str):
if backend == "vispy":
pytest.skip("vispy does not support legend")
canvas = new_canvas(backend=backend)
canvas.add_line([0, 1, 2], [0, 1, 2], name="line")
canvas.add_line([0, 1, 2], [0, 1, 2])
canvas.add_markers([0, 1, 2], [0, 1, 2], name="markers")
canvas.add_bars([0, 1, 2], [0, 1, 2], name="bars")
canvas.add_line([3, 4, 5], [1, 2, 1], name="plot").with_markers()
Expand Down
8 changes: 8 additions & 0 deletions tests/test_logics.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,14 @@
layer.band_width
layer.band_width = 0.5

def test_line_with_methods():
canvas = new_canvas(backend="mock")
line = canvas.add_line([1, 2], [4, 5])
with pytest.raises(TypeError):
line.with_xband([1, 1], alpha=[1, 2])
line.with_yfill([0, 1])

Check warning on line 53 in tests/test_logics.py

View check run for this annotation

Codecov / codecov/patch

tests/test_logics.py#L53

Added line #L53 was not covered by tests
line.with_yfill(0.1, alpha=[1, 2])

def test_hover_template():
canvas = new_canvas(backend="mock")
layer = canvas.add_markers([1, 2, 3], [4, 5, 6])
Expand Down
2 changes: 1 addition & 1 deletion whitecanvas/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
__version__ = "0.3.1"
__version__ = "0.3.2"

from whitecanvas import theme
from whitecanvas.canvas import link_axes
Expand Down
8 changes: 7 additions & 1 deletion whitecanvas/backend/matplotlib/canvas.py
Original file line number Diff line number Diff line change
Expand Up @@ -309,10 +309,16 @@ def _plt_make_legend(
if artists:
loc, bbox_to_anchor = _LEGEND_LOC_MAP[anchor]
font_size = self._plt_get_xticks()._plt_get_size()
self._axes.legend(
leg = self._axes.legend(
artists, names, loc=loc, bbox_to_anchor=bbox_to_anchor,
prop={"size": font_size},
) # fmt: skip
for item, text in zip(leg.legend_handles, leg.texts):
if isinstance(item, plt.Rectangle):
extent = item.get_window_extent(leg.figure.canvas.get_renderer())
width = extent.width
text.set_fontweight("bold")
text.set_position((-1.5 * width, 0))
if anchor.is_side:
self._axes.figure.tight_layout()

Expand Down
2 changes: 1 addition & 1 deletion whitecanvas/backend/pyqtgraph/_labels.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ def _plt_set_text(self, text: str):
self._get_axis().setLabel(text, **self._css)

def _plt_get_color(self):
return np.array(Color(self._css["color"]))
return np.fromiter(Color(self._css["color"]), dtype=np.float32)

def _plt_set_color(self, color):
css = self._css.copy()
Expand Down
8 changes: 7 additions & 1 deletion whitecanvas/canvas/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
Symbol,
)
from whitecanvas.utils.normalize import as_array_1d, normalize_xy
from whitecanvas.utils.predicate import not_starts_with_underscore
from whitecanvas.utils.type_check import is_real_number

if TYPE_CHECKING:
Expand Down Expand Up @@ -99,7 +100,7 @@ def _draw_canvas(self):
self._canvas()._plt_draw()
self.events.drawn.emit()

def _coerce_name(self, name: str | None, default: str = "data") -> str:
def _coerce_name(self, name: str | None, default: str = "_data") -> str:
if name is None:
basename = default
name = f"{default}-0"
Expand Down Expand Up @@ -743,6 +744,7 @@ def add_legend(
*,
location: Location | LocationStr = "top_right",
title: str | None = None,
name_filter: Callable[[str], bool] = not_starts_with_underscore,
):
"""
Add legend items to the canvas.
Expand Down Expand Up @@ -779,6 +781,8 @@ def add_legend(
```
title : str, optional
If given, title label will be added as the first legend item.
name_filter : callable, default not_starts_with_underscore
A callable that returns True if the name should be included in the legend.
"""
if layers is None:
layers = list(self.layers)
Expand All @@ -791,6 +795,8 @@ def add_legend(
if isinstance(layer, str):
items.append((layer, _legend.TitleItem()))
elif isinstance(layer, _l.Layer):
if not name_filter(layer.name):
continue
items.append((layer.name, layer._as_legend_item()))
else:
raise TypeError(f"Expected a list of layer or str, got {type(layer)}.")
Expand Down
10 changes: 7 additions & 3 deletions whitecanvas/canvas/_joint.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from abc import ABC, abstractmethod
from typing import (
TYPE_CHECKING,
Callable,
Iterator,
Literal,
Sequence,
Expand Down Expand Up @@ -31,6 +32,7 @@
OrientationLike,
Symbol,
)
from whitecanvas.utils.predicate import not_starts_with_underscore

if TYPE_CHECKING:
from typing_extensions import Self
Expand Down Expand Up @@ -164,13 +166,15 @@ def _link_marginal_to_main(self, layer: _l.Layer, main: _l.Layer) -> None:
def add_legend(
self,
layers: Sequence[str | _l.Layer] | None = None,
location: Location | LocationStr = "top_right",
*,
location: Location | LocationStr = "top_right",
title: str | None = None,
name_filter: Callable[[str], bool] = not_starts_with_underscore,
):
"""Add legend to the main canvas."""
self.main_canvas.add_legend(layers, location=location, title=title)
return None
return self.main_canvas.add_legend(
layers, location=location, title=title, name_filter=name_filter
)

def add_markers(
self,
Expand Down
4 changes: 2 additions & 2 deletions whitecanvas/canvas/_namespaces.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ def color(self):

@color.setter
def color(self, color):
self._get_object()._plt_set_color(np.array(Color(color)))
self._get_object()._plt_set_color(np.fromiter(Color(color), dtype=np.float32))

@property
def size(self) -> float:
Expand Down Expand Up @@ -333,7 +333,7 @@ def color(self):

@color.setter
def color(self, color):
self._get_object()._plt_set_color(np.array(Color(color)))
self._get_object()._plt_set_color(np.fromiter(Color(color), dtype=np.float32))
self._draw_canvas()

@property
Expand Down
4 changes: 2 additions & 2 deletions whitecanvas/layers/_mixin.py
Original file line number Diff line number Diff line change
Expand Up @@ -722,7 +722,7 @@ def _make_sure_hatch_visible(self):
_is_no_width = self.edge.width == 0
if isinstance(self._edge_namespace, MultiEdge):
if np.any(_is_no_width):
ec = np.array(get_theme().foreground_color, dtype=np.float32)
ec = np.fromiter(get_theme().foreground_color, dtype=np.float32)
self.edge.width = np.where(_is_no_width, 1, self.edge.width)
ec_old = self.edge.color
ec_old[_is_no_width] = ec[np.newaxis]
Expand Down Expand Up @@ -848,7 +848,7 @@ def __init__(self):
def _make_sure_hatch_visible(self):
_is_no_width = self.edge.width == 0
if np.any(_is_no_width):
ec = np.array(get_theme().foreground_color, dtype=np.float32)
ec = np.fromiter(get_theme().foreground_color, dtype=np.float32)
self.edge.width = np.where(_is_no_width, 1, self.edge.width)
ec_old = self.edge.color
ec_old[_is_no_width] = ec[np.newaxis]
Expand Down
Loading
Loading