pixelplotlib 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,77 @@
1
+ """A `Textual <https://github.com/Textualize/textual>`_ widget that shows a figure.
2
+
3
+ The widget re-renders its figure at exactly the widget's size (one pixel per cell
4
+ column, two per cell row), so plots stay crisp as the terminal is resized::
5
+
6
+ from textual.app import App
7
+ from pixelplotlib.textual import PixelPlot
8
+
9
+ class PlotApp(App):
10
+ def compose(self):
11
+ fig, ax = ppl.subplots(style="pico8")
12
+ ax.plot([1, 3, 2, 4])
13
+ yield PixelPlot(fig)
14
+
15
+ Assign a new figure to :attr:`PixelPlot.figure` to replace the plot, or call
16
+ :meth:`~textual.widget.Widget.refresh` after changing the current figure in place.
17
+
18
+ Requires the ``textual`` extra: ``pip install "pixelplotlib[textual]"``.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ from rich.console import RenderableType
24
+ from textual.geometry import Size
25
+ from textual.reactive import reactive
26
+ from textual.widget import Widget
27
+
28
+ from .figure import Figure
29
+ from .rich import Plot
30
+ from .styles import Style
31
+
32
+ __all__ = ["PixelPlot"]
33
+
34
+
35
+ class PixelPlot(Widget):
36
+ """Display a :class:`~pixelplotlib.Figure`, filling the widget.
37
+
38
+ Parameters
39
+ ----------
40
+ figure:
41
+ The figure to show. Defaults to a new empty figure in ``style``; draw into it
42
+ through ``widget.figure`` and call ``widget.refresh()``.
43
+ style:
44
+ Style for the default figure (ignored when ``figure`` is given).
45
+
46
+ With ``width: auto`` / ``height: auto`` in CSS the widget takes the figure's native
47
+ width (one cell per pixel) and the matching height for its aspect ratio.
48
+ """
49
+
50
+ DEFAULT_CSS = """
51
+ PixelPlot {
52
+ width: 1fr;
53
+ height: 1fr;
54
+ }
55
+ """
56
+
57
+ figure: reactive[Figure] = reactive(Figure, layout=True, always_update=True)
58
+ """The figure being displayed; assigning a figure (even the same one) redraws it."""
59
+
60
+ def __init__(self, figure: Figure | None = None, *, style: str | Style | None = None,
61
+ name: str | None = None, id: str | None = None, classes: str | None = None,
62
+ disabled: bool = False):
63
+ super().__init__(name=name, id=id, classes=classes, disabled=disabled)
64
+ self.set_reactive(PixelPlot.figure, figure if figure is not None else Figure(style=style))
65
+
66
+ def render(self) -> RenderableType:
67
+ width, height = self.content_size
68
+ if width <= 0 or height <= 0:
69
+ return ""
70
+ return Plot(self.figure, width=width, height=height)
71
+
72
+ def get_content_width(self, container: Size, viewport: Size) -> int:
73
+ return self.figure.width
74
+
75
+ def get_content_height(self, container: Size, viewport: Size, width: int) -> int:
76
+ _, px_h = Plot(self.figure, width=width).pixel_size(max(width, 1))
77
+ return (px_h + 1) // 2
pixelplotlib/ticks.py ADDED
@@ -0,0 +1,90 @@
1
+ """Tick location and label formatting."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+
7
+ import numpy as np
8
+
9
+
10
+ def nice_ticks(lo: float, hi: float, max_ticks: int = 6) -> tuple[np.ndarray, float]:
11
+ """Return "nice" tick values (multiples of 1, 2, 2.5 or 5 x 10^k) within ``[lo, hi]``."""
12
+ if hi < lo:
13
+ lo, hi = hi, lo
14
+ span = hi - lo
15
+ if not np.isfinite(span):
16
+ return np.array([]), 1.0
17
+ if span == 0:
18
+ span = abs(lo) or 1.0
19
+ max_ticks = max(int(max_ticks), 2)
20
+ # smallest nice step whose ticks *inside* [lo, hi] number at most max_ticks
21
+ k = math.floor(math.log10(span / max_ticks)) - 1
22
+ step = 10.0 ** (k + 3)
23
+ for mag in 10.0 ** np.arange(k, k + 3):
24
+ for m in (1.0, 2.0, 2.5, 5.0):
25
+ cand = m * mag
26
+ count = math.floor(hi / cand + 1e-9) - math.ceil(lo / cand - 1e-9) + 1
27
+ if count <= max_ticks:
28
+ step = cand
29
+ break
30
+ else:
31
+ continue
32
+ break
33
+ eps = step * 1e-9
34
+ start = math.ceil((lo - eps) / step) * step
35
+ ticks = np.arange(start, hi + eps, step)
36
+ ticks = np.where(np.abs(ticks) < eps, 0.0, ticks)
37
+ return ticks, step
38
+
39
+
40
+ def log_ticks(lo: float, hi: float, max_ticks: int = 6) -> np.ndarray:
41
+ """Powers of ten within ``[lo, hi]`` (both must be positive)."""
42
+ if hi < lo:
43
+ lo, hi = hi, lo
44
+ e0 = math.ceil(math.log10(lo) - 1e-9)
45
+ e1 = math.floor(math.log10(hi) + 1e-9)
46
+ if e1 < e0:
47
+ ticks, _ = nice_ticks(lo, hi, max_ticks)
48
+ return ticks[ticks > 0]
49
+ exps = np.arange(e0, e1 + 1)
50
+ stride = max(1, math.ceil(len(exps) / max(max_ticks, 2)))
51
+ exps = exps[exps % stride == 0] if stride > 1 else exps
52
+ return 10.0 ** exps
53
+
54
+
55
+ def _sci(v: float, digits: int) -> str:
56
+ mant, exp = f"{v:.{digits}e}".split("e")
57
+ if "." in mant:
58
+ mant = mant.rstrip("0").rstrip(".")
59
+ return f"{mant}E{int(exp)}"
60
+
61
+
62
+ def format_ticks(values, log: bool = False) -> list[str]:
63
+ """Format tick values compactly with a consistent number of decimals."""
64
+ values = np.asarray(values, dtype=np.float64)
65
+ if values.size == 0:
66
+ return []
67
+ if log:
68
+ pos = values[values > 0]
69
+ exps = np.log10(pos)
70
+ decades = np.allclose(exps, np.round(exps), atol=1e-9)
71
+ if decades and pos.size and (exps.min() < -3 or exps.max() > 4):
72
+ # use E-notation for every label so the axis reads consistently
73
+ return [f"1E{int(round(math.log10(v)))}" if v > 0 else "0" for v in values]
74
+ return [format_ticks([v])[0] for v in values]
75
+ big = np.nanmax(np.abs(values))
76
+ nonzero = np.abs(values[values != 0])
77
+ small = nonzero.min() if nonzero.size else 0.0
78
+ if big >= 1e5 or (0 < small < 1e-3):
79
+ for digits in range(0, 6):
80
+ labels = [_sci(v, digits) for v in values]
81
+ if np.allclose([float(lb.replace("E", "e")) for lb in labels], values,
82
+ rtol=1e-6, atol=0):
83
+ break
84
+ return [("0" if v == 0 else lb) for v, lb in zip(values, labels)]
85
+ for decimals in range(0, 7):
86
+ scaled = values * 10**decimals
87
+ if np.allclose(scaled, np.round(scaled), atol=1e-6 * max(1.0, big * 10**decimals)):
88
+ break
89
+ labels = [f"{v:.{decimals}f}" for v in values]
90
+ return ["0" if float(lb) == 0 else lb for lb in labels]