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.
pixelplotlib/fonts.py ADDED
@@ -0,0 +1,358 @@
1
+ """Hand-drawn bitmap fonts.
2
+
3
+ Glyphs are written as space separated rows of ``#`` (ink) and ``.`` (paper).
4
+ Glyphs are proportional: their width is the length of their rows. Glyphs may
5
+ have ``ascent`` rows, or ``ascent + descent`` rows for letters with descenders.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from functools import lru_cache
11
+
12
+ import numpy as np
13
+
14
+ _GLYPHS_5X7: dict[str, str] = {
15
+ " ": "... ... ... ... ... ... ...",
16
+ "!": "# # # # # . #",
17
+ '"': "#.# #.# ... ... ... ... ...",
18
+ "#": ".#.#. .#.#. ##### .#.#. ##### .#.#. .#.#.",
19
+ "$": "..#.. .#### #.#.. .###. ..#.# ####. ..#..",
20
+ "%": "##... ##..# ...#. ..#.. .#... #..## ...##",
21
+ "&": ".##.. #..#. #.#.. .#... #.#.# #..#. .##.#",
22
+ "'": "# # . . . . .",
23
+ "(": "..# .#. #.. #.. #.. .#. ..#",
24
+ ")": "#.. .#. ..# ..# ..# .#. #..",
25
+ "*": "..... ..#.. #.#.# .###. #.#.# ..#.. .....",
26
+ "+": "..... ..#.. ..#.. ##### ..#.. ..#.. .....",
27
+ ",": ".. .. .. .. .. .. .# #. ..",
28
+ "-": ".... .... .... #### .... .... ....",
29
+ ".": ". . . . . . #",
30
+ "/": "....# ....# ...#. ..#.. .#... #.... #....",
31
+ "0": ".###. #...# #..## #.#.# ##..# #...# .###.",
32
+ "1": "..#.. .##.. ..#.. ..#.. ..#.. ..#.. .###.",
33
+ "2": ".###. #...# ....# ...#. ..#.. .#... #####",
34
+ "3": "##### ...#. ..#.. ...#. ....# #...# .###.",
35
+ "4": "...#. ..##. .#.#. #..#. ##### ...#. ...#.",
36
+ "5": "##### #.... ####. ....# ....# #...# .###.",
37
+ "6": "..##. .#... #.... ####. #...# #...# .###.",
38
+ "7": "##### ....# ...#. ..#.. .#... .#... .#...",
39
+ "8": ".###. #...# #...# .###. #...# #...# .###.",
40
+ "9": ".###. #...# #...# .#### ....# ...#. .##..",
41
+ ":": ". # . . . # .",
42
+ ";": ".. .# .. .. .. .# #.",
43
+ "<": "...# ..#. .#.. #... .#.. ..#. ...#",
44
+ "=": "..... ..... ##### ..... ##### ..... .....",
45
+ ">": "#... .#.. ..#. ...# ..#. .#.. #...",
46
+ "?": ".###. #...# ....# ...#. ..#.. ..... ..#..",
47
+ "@": ".###. #...# #.### #.#.# #.### #.... .####",
48
+ "A": ".###. #...# #...# ##### #...# #...# #...#",
49
+ "B": "####. #...# #...# ####. #...# #...# ####.",
50
+ "C": ".###. #...# #.... #.... #.... #...# .###.",
51
+ "D": "####. #...# #...# #...# #...# #...# ####.",
52
+ "E": "##### #.... #.... ####. #.... #.... #####",
53
+ "F": "##### #.... #.... ####. #.... #.... #....",
54
+ "G": ".###. #...# #.... #.### #...# #...# .####",
55
+ "H": "#...# #...# #...# ##### #...# #...# #...#",
56
+ "I": "### .#. .#. .#. .#. .#. ###",
57
+ "J": "..### ...#. ...#. ...#. ...#. #..#. .##..",
58
+ "K": "#...# #..#. #.#.. ##... #.#.. #..#. #...#",
59
+ "L": "#.... #.... #.... #.... #.... #.... #####",
60
+ "M": "#...# ##.## #.#.# #.#.# #...# #...# #...#",
61
+ "N": "#...# #...# ##..# #.#.# #..## #...# #...#",
62
+ "O": ".###. #...# #...# #...# #...# #...# .###.",
63
+ "P": "####. #...# #...# ####. #.... #.... #....",
64
+ "Q": ".###. #...# #...# #...# #.#.# #..#. .##.#",
65
+ "R": "####. #...# #...# ####. #.#.. #..#. #...#",
66
+ "S": ".#### #.... #.... .###. ....# ....# ####.",
67
+ "T": "##### ..#.. ..#.. ..#.. ..#.. ..#.. ..#..",
68
+ "U": "#...# #...# #...# #...# #...# #...# .###.",
69
+ "V": "#...# #...# #...# #...# #...# .#.#. ..#..",
70
+ "W": "#...# #...# #...# #.#.# #.#.# #.#.# .#.#.",
71
+ "X": "#...# #...# .#.#. ..#.. .#.#. #...# #...#",
72
+ "Y": "#...# #...# .#.#. ..#.. ..#.. ..#.. ..#..",
73
+ "Z": "##### ....# ...#. ..#.. .#... #.... #####",
74
+ "[": "### #.. #.. #.. #.. #.. ###",
75
+ "\\": "#.... #.... .#... ..#.. ...#. ....# ....#",
76
+ "]": "### ..# ..# ..# ..# ..# ###",
77
+ "^": "..#.. .#.#. #...# ..... ..... ..... .....",
78
+ "_": "..... ..... ..... ..... ..... ..... ..... ##### .....",
79
+ "`": "#. .# .. .. .. .. ..",
80
+ "a": "..... ..... .###. ....# .#### #...# .####",
81
+ "b": "#.... #.... #.##. ##..# #...# #...# ####.",
82
+ "c": "..... ..... .###. #.... #.... #...# .###.",
83
+ "d": "....# ....# .##.# #..## #...# #...# .####",
84
+ "e": "..... ..... .###. #...# ##### #.... .###.",
85
+ "f": "..## .#.. .#.. ###. .#.. .#.. .#..",
86
+ "g": "..... ..... .#### #...# #...# #...# .#### ....# .###.",
87
+ "h": "#.... #.... #.##. ##..# #...# #...# #...#",
88
+ "i": ".#. ... ##. .#. .#. .#. ###",
89
+ "j": "...# .... ..## ...# ...# ...# ...# #..# .##.",
90
+ "k": "#... #... #..# #.#. ##.. #.#. #..#",
91
+ "l": "##. .#. .#. .#. .#. .#. ###",
92
+ "m": "..... ..... ##.#. #.#.# #.#.# #.#.# #.#.#",
93
+ "n": "..... ..... #.##. ##..# #...# #...# #...#",
94
+ "o": "..... ..... .###. #...# #...# #...# .###.",
95
+ "p": "..... ..... ####. #...# #...# #...# ####. #.... #....",
96
+ "q": "..... ..... .#### #...# #...# #...# .#### ....# ....#",
97
+ "r": "..... ..... #.##. ##..# #.... #.... #....",
98
+ "s": "..... ..... .#### #.... .###. ....# ####.",
99
+ "t": ".#.. .#.. ###. .#.. .#.. .#.. ..##",
100
+ "u": "..... ..... #...# #...# #...# #..## .##.#",
101
+ "v": "..... ..... #...# #...# #...# .#.#. ..#..",
102
+ "w": "..... ..... #...# #...# #.#.# #.#.# .#.#.",
103
+ "x": "..... ..... #...# .#.#. ..#.. .#.#. #...#",
104
+ "y": "..... ..... #...# #...# #...# #...# .#### ....# .###.",
105
+ "z": "..... ..... ##### ...#. ..#.. .#... #####",
106
+ "{": "..# .#. .#. #.. .#. .#. ..#",
107
+ "|": "# # # # # # #",
108
+ "}": "#.. .#. .#. ..# .#. .#. #..",
109
+ "~": "..... ..... .#... #.#.# ...#. ..... .....",
110
+ # --- scientific extras ---
111
+ "°": ".#. #.# .#. ... ... ... ...",
112
+ "±": "..#.. ..#.. ##### ..#.. ..#.. ..... #####",
113
+ "×": "..... #...# .#.#. ..#.. .#.#. #...# .....",
114
+ "÷": "..... ..#.. ..... ##### ..... ..#.. .....",
115
+ "·": ". . . # . . .",
116
+ "²": "##. ..# .#. ### ... ... ...",
117
+ "³": "##. .## ..# ##. ... ... ...",
118
+ "μ": "..... ..... #...# #...# #...# #..## ###.# #.... #....",
119
+ "α": "..... ..... .##.# #..#. #..#. #..#. .##.#",
120
+ "β": ".##.. #..#. #.#.. #..#. #...# #...# ####. #.... #....",
121
+ "γ": "..... ..... #...# #...# .#.#. .#.#. ..#.. ..#.. ..#..",
122
+ "δ": ".###. #.... .##.. #..#. #...# #...# .###.",
123
+ "ε": ".... .... .### #... .##. #... .###",
124
+ "θ": ".###. #...# #...# ##### #...# #...# .###.",
125
+ "λ": "##... ..#.. ..#.. .#.#. .#.#. #...# #...#",
126
+ "π": "..... ..... ##### .#.#. .#.#. .#.#. .#..#",
127
+ "ρ": "..... ..... .###. #...# #...# #...# ####. #.... #....",
128
+ "σ": "..... ..... .#### #..#. #...# #...# .###.",
129
+ "τ": "..... ..... ##### ..#.. ..#.. ..#.. ...##",
130
+ "φ": "..#.. .###. #.#.# #.#.# #.#.# .###. ..#..",
131
+ "ψ": "..... ..... #.#.# #.#.# #.#.# .###. ..#..",
132
+ "ω": "..... ..... .#.#. #...# #.#.# #.#.# .#.#.",
133
+ "Γ": "##### #.... #.... #.... #.... #.... #....",
134
+ "Δ": "..#.. ..#.. .#.#. .#.#. #...# #...# #####",
135
+ "Σ": "##### #.... .#... ..#.. .#... #.... #####",
136
+ "Ω": ".###. #...# #...# #...# .#.#. .#.#. ##.##",
137
+ "√": "....# ...#. ...#. #.#.. #.#.. .#... .#...",
138
+ "∞": "..... ..... .#.#. #.#.# #.#.# .#.#. .....",
139
+ "≈": "..... .#... #.#.# ...#. .#... #.#.# ...#.",
140
+ "≤": "...#. ..#.. .#... ..#.. ...#. ..... #####",
141
+ "≥": ".#... ..#.. ...#. ..#.. .#... ..... #####",
142
+ "≠": "..... ...#. ##### ..#.. ##### .#... .....",
143
+ "∂": ".##.. ...#. ....# .#### #...# #...# .###.",
144
+ "∫": "..## .#.. .#.. .#.. .#.. .#.. ##..",
145
+ "→": "..... ..#.. ...#. ##### ...#. ..#.. .....",
146
+ "←": "..... ..#.. .#... ##### .#... ..#.. .....",
147
+ "↑": "..#.. .###. #.#.# ..#.. ..#.. ..#.. ..#..",
148
+ "↓": "..#.. ..#.. ..#.. ..#.. #.#.# .###. ..#..",
149
+ "♥": "..... .#.#. ##### ##### .###. ..#.. .....",
150
+ "★": "..#.. ..#.. ##### .###. .#.#. #...# .....",
151
+ "█": "##### ##### ##### ##### ##### ##### #####",
152
+ "…": "..... ..... ..... ..... ..... ..... #.#.#",
153
+ "\ufffd": "##### #...# #...# #...# #...# #...# #####",
154
+ }
155
+
156
+ _GLYPHS_3X5: dict[str, str] = {
157
+ " ": ".. .. .. .. ..",
158
+ "!": "# # # . #",
159
+ '"': "#.# #.# ... ... ...",
160
+ "#": "#.# ### #.# ### #.#",
161
+ "$": ".## ##. .#. .## ##.",
162
+ "%": "#.# ..# .#. #.. #.#",
163
+ "&": ".#. #.# .#. #.# .##",
164
+ "'": "# # . . .",
165
+ "(": ".# #. #. #. .#",
166
+ ")": "#. .# .# .# #.",
167
+ "*": "... #.# .#. #.# ...",
168
+ "+": "... .#. ### .#. ...",
169
+ ",": ".. .. .. .# #.",
170
+ "-": "... ... ### ... ...",
171
+ ".": ". . . . #",
172
+ "/": "..# ..# .#. #.. #..",
173
+ "0": "### #.# #.# #.# ###",
174
+ "1": ".#. ##. .#. .#. ###",
175
+ "2": "##. ..# .#. #.. ###",
176
+ "3": "##. ..# .#. ..# ##.",
177
+ "4": "#.# #.# ### ..# ..#",
178
+ "5": "### #.. ##. ..# ##.",
179
+ "6": ".## #.. ### #.# ###",
180
+ "7": "### ..# .#. .#. .#.",
181
+ "8": "### #.# ### #.# ###",
182
+ "9": "### #.# ### ..# ##.",
183
+ ":": ". # . # .",
184
+ ";": ".. .# .. .# #.",
185
+ "<": "..# .#. #.. .#. ..#",
186
+ "=": "... ### ... ### ...",
187
+ ">": "#.. .#. ..# .#. #..",
188
+ "?": "##. ..# .#. ... .#.",
189
+ "@": ".#. #.# ### #.. .##",
190
+ "A": ".#. #.# ### #.# #.#",
191
+ "B": "##. #.# ##. #.# ##.",
192
+ "C": ".## #.. #.. #.. .##",
193
+ "D": "##. #.# #.# #.# ##.",
194
+ "E": "### #.. ##. #.. ###",
195
+ "F": "### #.. ##. #.. #..",
196
+ "G": ".## #.. #.# #.# .##",
197
+ "H": "#.# #.# ### #.# #.#",
198
+ "I": "### .#. .#. .#. ###",
199
+ "J": "..# ..# ..# #.# .#.",
200
+ "K": "#.# #.# ##. #.# #.#",
201
+ "L": "#.. #.. #.. #.. ###",
202
+ "M": "#.# ### ### #.# #.#",
203
+ "N": "##. #.# #.# #.# #.#",
204
+ "O": ".#. #.# #.# #.# .#.",
205
+ "P": "##. #.# ##. #.. #..",
206
+ "Q": ".#. #.# #.# ##. .##",
207
+ "R": "##. #.# ##. #.# #.#",
208
+ "S": ".## #.. .#. ..# ##.",
209
+ "T": "### .#. .#. .#. .#.",
210
+ "U": "#.# #.# #.# #.# ###",
211
+ "V": "#.# #.# #.# #.# .#.",
212
+ "W": "#.# #.# ### ### #.#",
213
+ "X": "#.# #.# .#. #.# #.#",
214
+ "Y": "#.# #.# .#. .#. .#.",
215
+ "Z": "### ..# .#. #.. ###",
216
+ "[": "## #. #. #. ##",
217
+ "\\": "#.. #.. .#. ..# ..#",
218
+ "]": "## .# .# .# ##",
219
+ "^": ".#. #.# ... ... ...",
220
+ "_": "... ... ... ... ###",
221
+ "`": "#. .# .. .. ..",
222
+ "{": ".## .#. ##. .#. .##",
223
+ "|": "# # # # #",
224
+ "}": "##. .#. .## .#. ##.",
225
+ "~": "... .## ##. ... ...",
226
+ "°": ".#. #.# .#. ... ...",
227
+ "±": ".#. ### .#. ... ###",
228
+ "×": "... #.# .#. #.# ...",
229
+ "·": ". . # . .",
230
+ "μ": "... #.# #.# ##. #..",
231
+ "π": "... ### #.# #.# #.#",
232
+ "Δ": ".#. .#. #.# #.# ###",
233
+ "\ufffd": "### #.# #.# #.# ###",
234
+ }
235
+
236
+ _ALIASES = {
237
+ "\u2212": "-", # minus sign
238
+ "\u2013": "-",
239
+ "\u2014": "-",
240
+ "\u2018": "'",
241
+ "\u2019": "'",
242
+ "\u201c": '"',
243
+ "\u201d": '"',
244
+ "\u00b5": "μ", # micro sign -> greek mu
245
+ "\u2126": "Ω",
246
+ "\u2206": "Δ",
247
+ "\u2211": "Σ",
248
+ }
249
+
250
+
251
+ class BitmapFont:
252
+ """A proportional bitmap font.
253
+
254
+ Parameters
255
+ ----------
256
+ name:
257
+ Font name.
258
+ glyphs:
259
+ Mapping of characters to glyph specs (see module docstring).
260
+ ascent, descent:
261
+ Rows above (and including) the baseline and below it.
262
+ spacing:
263
+ Blank columns between glyphs.
264
+ line_gap:
265
+ Blank rows between lines of multi-line text.
266
+ uppercase:
267
+ Render lowercase letters with their uppercase glyphs.
268
+ """
269
+
270
+ def __init__(
271
+ self,
272
+ name: str,
273
+ glyphs: dict[str, str],
274
+ ascent: int,
275
+ descent: int = 0,
276
+ spacing: int = 1,
277
+ line_gap: int = 1,
278
+ uppercase: bool = False,
279
+ ):
280
+ self.name = name
281
+ self.ascent = ascent
282
+ self.descent = descent
283
+ self.spacing = spacing
284
+ self.line_gap = line_gap
285
+ self.uppercase = uppercase
286
+ self._glyphs: dict[str, np.ndarray] = {}
287
+ for ch, spec in glyphs.items():
288
+ rows = spec.split()
289
+ width = len(rows[0])
290
+ if any(len(r) != width for r in rows) or len(rows) not in (ascent, ascent + descent):
291
+ raise ValueError(f"malformed glyph {ch!r} in font {name!r}")
292
+ bitmap = np.zeros((ascent + descent, width), dtype=bool)
293
+ bitmap[: len(rows)] = np.array([[c == "#" for c in r] for r in rows], dtype=bool)
294
+ self._glyphs[ch] = bitmap
295
+
296
+ @property
297
+ def line_height(self) -> int:
298
+ return self.ascent + self.descent
299
+
300
+ def __contains__(self, ch: str) -> bool:
301
+ return self._resolve(ch) != "\ufffd" or ch == "\ufffd"
302
+
303
+ def _resolve(self, ch: str) -> str:
304
+ ch = _ALIASES.get(ch, ch)
305
+ if self.uppercase and ch not in self._glyphs:
306
+ ch = ch.upper()
307
+ return ch if ch in self._glyphs else "\ufffd"
308
+
309
+ def glyph(self, ch: str) -> np.ndarray:
310
+ return self._glyphs[self._resolve(ch)]
311
+
312
+ def measure(self, text: str) -> tuple[int, int]:
313
+ """Return ``(width, height)`` in pixels of rendered ``text``."""
314
+ lines = str(text).split("\n")
315
+ width = max(self._line_width(line) for line in lines)
316
+ height = len(lines) * self.line_height + (len(lines) - 1) * self.line_gap
317
+ return width, height
318
+
319
+ def _line_width(self, line: str) -> int:
320
+ if not line:
321
+ return 0
322
+ return sum(self.glyph(c).shape[1] for c in line) + self.spacing * (len(line) - 1)
323
+
324
+ def render(self, text: str, align: str = "left") -> np.ndarray:
325
+ """Render ``text`` to a boolean mask of shape ``(height, width)``."""
326
+ return _render_cached(self, str(text), align).copy()
327
+
328
+
329
+ @lru_cache(maxsize=4096)
330
+ def _render_cached(font: BitmapFont, text: str, align: str) -> np.ndarray:
331
+ lines = text.split("\n")
332
+ w, h = font.measure(text)
333
+ out = np.zeros((h, w), dtype=bool)
334
+ y = 0
335
+ for line in lines:
336
+ lw = font._line_width(line)
337
+ x = {"left": 0, "center": (w - lw) // 2, "right": w - lw}[align]
338
+ for ch in line:
339
+ g = font.glyph(ch)
340
+ out[y : y + g.shape[0], x : x + g.shape[1]] |= g
341
+ x += g.shape[1] + font.spacing
342
+ y += font.line_height + font.line_gap
343
+ return out
344
+
345
+
346
+ FONT_5X7 = BitmapFont("5x7", _GLYPHS_5X7, ascent=7, descent=2)
347
+ FONT_3X5 = BitmapFont("3x5", _GLYPHS_3X5, ascent=5, descent=0, uppercase=True)
348
+
349
+ FONTS: dict[str, BitmapFont] = {"5x7": FONT_5X7, "3x5": FONT_3X5, "tiny": FONT_3X5}
350
+
351
+
352
+ def get_font(font: str | BitmapFont) -> BitmapFont:
353
+ if isinstance(font, BitmapFont):
354
+ return font
355
+ try:
356
+ return FONTS[font]
357
+ except KeyError:
358
+ raise ValueError(f"unknown font {font!r}; choose from {sorted(FONTS)}") from None
@@ -0,0 +1,53 @@
1
+ """Pixel sprites used as scatter/line markers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Sequence
6
+
7
+ import numpy as np
8
+
9
+ _SPRITES: dict[str, list[str]] = {
10
+ "p": ["#"],
11
+ ".": [".#.", "###", ".#."],
12
+ "o": [".###.", "#####", "#####", "#####", ".###."],
13
+ "s": ["#####", "#####", "#####", "#####", "#####"],
14
+ "^": ["...#...", "..###..", ".#####.", "#######"],
15
+ "v": ["#######", ".#####.", "..###..", "...#..."],
16
+ "D": ["...#...", "..###..", ".#####.", "#######", ".#####.", "..###..", "...#..."],
17
+ "+": ["..#..", "..#..", "#####", "..#..", "..#.."],
18
+ "x": ["#...#", ".#.#.", "..#..", ".#.#.", "#...#"],
19
+ "*": ["..#..", "#.#.#", ".###.", "#.#.#", "..#.."],
20
+ "heart": [".##.##.", "#######", "#######", ".#####.", "..###..", "...#..."],
21
+ "star": ["...#...", "..###..", "#######", ".#####.", "..###..", ".##.##.", "#.....#"],
22
+ "skull": [".#####.", "#######", "#..#..#", "#######", "###.###", ".#####.", ".#.#.#."],
23
+ "ufo": ["..###..", ".#####.", "#.#.#.#", "#######", ".#...#."],
24
+ "drop": ["..#..", "..#..", ".###.", "#####", "#####", ".###."],
25
+ }
26
+ _ALIASES = {"circle": "o", "square": "s", "diamond": "D", "triangle": "^", "pixel": "p",
27
+ "point": ".", "plus": "+", "cross": "x"}
28
+
29
+ MarkerLike = str | Sequence[str] | np.ndarray
30
+
31
+ MARKERS = tuple(_SPRITES) + tuple(_ALIASES)
32
+
33
+
34
+ def marker_mask(marker: MarkerLike, size: int = 1) -> np.ndarray:
35
+ """Return the boolean sprite for ``marker`` scaled by integer factor ``size``.
36
+
37
+ ``marker`` may be a name (see :data:`MARKERS`), a list of ``#``/``.`` row
38
+ strings, or a boolean array.
39
+ """
40
+ if isinstance(marker, str):
41
+ name = _ALIASES.get(marker, marker)
42
+ if name not in _SPRITES:
43
+ raise ValueError(f"unknown marker {marker!r}; choose from {sorted(MARKERS)}")
44
+ rows = _SPRITES[name]
45
+ mask = np.array([[c == "#" for c in r] for r in rows], dtype=bool)
46
+ elif isinstance(marker, np.ndarray):
47
+ mask = marker.astype(bool)
48
+ else:
49
+ mask = np.array([[c == "#" for c in r] for r in marker], dtype=bool)
50
+ size = max(int(size), 1)
51
+ if size > 1:
52
+ mask = np.repeat(np.repeat(mask, size, axis=0), size, axis=1)
53
+ return mask
@@ -0,0 +1,62 @@
1
+ """Retro hardware palettes.
2
+
3
+ All palettes are lists of ``(r, g, b)`` tuples with 8-bit channels.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+
9
+ def _hex(*codes: str) -> list[tuple[int, int, int]]:
10
+ out = []
11
+ for code in codes:
12
+ code = code.lstrip("#")
13
+ out.append((int(code[0:2], 16), int(code[2:4], 16), int(code[4:6], 16)))
14
+ return out
15
+
16
+
17
+ # Commonly used NES (2C02) palette approximation; the duplicate blacks are removed.
18
+ NES = _hex(
19
+ "7C7C7C", "0000FC", "0000BC", "4428BC", "940084", "A80020", "A81000", "881400",
20
+ "503000", "007800", "006800", "005800", "004058", "000000",
21
+ "BCBCBC", "0078F8", "0058F8", "6844FC", "D800CC", "E40058", "F83800", "E45C10",
22
+ "AC7C00", "00B800", "00A800", "00A844", "008888",
23
+ "F8F8F8", "3CBCFC", "6888FC", "9878F8", "F878F8", "F85898", "F87858", "FCA044",
24
+ "F8B800", "B8F818", "58D854", "58F898", "00E8D8", "787878",
25
+ "FCFCFC", "A4E4FC", "B8B8F8", "D8B8F8", "F8B8F8", "F8A4C0", "F0D0B0", "FCE0A8",
26
+ "F8D878", "D8F878", "B8F8B8", "B8F8D8", "00FCFC", "F8D8F8",
27
+ )
28
+
29
+ GAMEBOY = _hex("0F380F", "306230", "8BAC0F", "9BBC0F")
30
+
31
+ PICO8 = _hex(
32
+ "000000", "1D2B53", "7E2553", "008751", "AB5236", "5F574F", "C2C3C7", "FFF1E8",
33
+ "FF004D", "FFA300", "FFEC27", "00E436", "29ADFF", "83769C", "FF77A8", "FFCCAA",
34
+ )
35
+
36
+ # "Pepto" Commodore 64 palette.
37
+ C64 = _hex(
38
+ "000000", "FFFFFF", "68372B", "70A4B2", "6F3D86", "588D43", "352879", "B8C76F",
39
+ "6F4F25", "433900", "9A6759", "444444", "6C6C6C", "9AD284", "6C5EB5", "959595",
40
+ )
41
+
42
+ # IBM CGA mode 4, palette 1 (high intensity).
43
+ CGA = _hex("000000", "55FFFF", "FF55FF", "FFFFFF")
44
+
45
+ ONE_BIT = _hex("000000", "FFFFFF")
46
+
47
+ PALETTES: dict[str, list[tuple[int, int, int]]] = {
48
+ "nes": NES,
49
+ "gameboy": GAMEBOY,
50
+ "pico8": PICO8,
51
+ "c64": C64,
52
+ "cga": CGA,
53
+ "1bit": ONE_BIT,
54
+ }
55
+
56
+
57
+ def get_palette(name: str) -> list[tuple[int, int, int]]:
58
+ """Return a copy of a named palette."""
59
+ try:
60
+ return list(PALETTES[name.lower()])
61
+ except KeyError:
62
+ raise ValueError(f"unknown palette {name!r}; choose from {sorted(PALETTES)}") from None
pixelplotlib/pyplot.py ADDED
@@ -0,0 +1,106 @@
1
+ """A small matplotlib.pyplot-like stateful interface."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import functools
6
+
7
+ from .axes import Axes
8
+ from .figure import Figure
9
+ from .styles import Style
10
+
11
+ _figures: list[Figure] = []
12
+
13
+
14
+ def figure(size: tuple[int, int] | None = None, style: str | Style | None = None,
15
+ scale: int | None = None) -> Figure:
16
+ """Create a new figure and make it current."""
17
+ fig = Figure(size=size, style=style, scale=scale)
18
+ _figures.append(fig)
19
+ return fig
20
+
21
+
22
+ def gcf() -> Figure:
23
+ """Current figure (created on demand)."""
24
+ if not _figures:
25
+ return figure()
26
+ return _figures[-1]
27
+
28
+
29
+ def gca() -> Axes:
30
+ """Current axes (created on demand)."""
31
+ return gcf().gca()
32
+
33
+
34
+ def subplots(nrows: int = 1, ncols: int = 1, size: tuple[int, int] | None = None,
35
+ style: str | Style | None = None, scale: int | None = None, squeeze: bool = True):
36
+ """Create a figure with a grid of axes: ``fig, ax = subplots()``."""
37
+ fig = figure(size=size, style=style, scale=scale)
38
+ return fig, fig.subplots(nrows, ncols, squeeze=squeeze)
39
+
40
+
41
+ def subplot(nrows: int, ncols: int, index) -> Axes:
42
+ return gcf().add_subplot(nrows, ncols, index)
43
+
44
+
45
+ def close(fig: Figure | str | None = None) -> None:
46
+ """Close the current figure, a given figure, or ``"all"``."""
47
+ if fig == "all":
48
+ _figures.clear()
49
+ elif fig is None:
50
+ if _figures:
51
+ _figures.pop()
52
+ elif fig in _figures:
53
+ _figures.remove(fig)
54
+
55
+
56
+ def savefig(path, **kwargs) -> None:
57
+ gcf().save(path, **kwargs)
58
+
59
+
60
+ def show(**kwargs) -> None:
61
+ """Show and close all open figures (``backend="sixel"`` draws them in the terminal)."""
62
+ for fig in list(_figures):
63
+ fig.show(**kwargs)
64
+ _figures.clear()
65
+
66
+
67
+ def suptitle(title: str) -> Figure:
68
+ return gcf().suptitle(title)
69
+
70
+
71
+ def colorbar(mappable=None, label: str | None = None, ticks=None):
72
+ return gca().colorbar(mappable, label=label, ticks=ticks)
73
+
74
+
75
+ def _wrap(name: str, target: str | None = None):
76
+ meth = getattr(Axes, target or name)
77
+
78
+ @functools.wraps(meth)
79
+ def wrapper(*args, **kwargs):
80
+ return getattr(gca(), target or name)(*args, **kwargs)
81
+
82
+ wrapper.__name__ = name
83
+ return wrapper
84
+
85
+
86
+ _AXES_FUNCS = [
87
+ "plot", "step", "scatter", "bar", "barh", "hist", "hist2d", "fill_between", "fill",
88
+ "errorbar", "stem", "axhline", "axvline", "axhspan", "axvspan", "imshow", "pcolormesh",
89
+ "contour", "contourf", "quiver", "pie", "boxplot", "violinplot", "text", "annotate",
90
+ "legend", "grid", "axis",
91
+ ]
92
+ _RENAMED = {
93
+ "title": "set_title", "xlabel": "set_xlabel", "ylabel": "set_ylabel",
94
+ "xlim": "set_xlim", "ylim": "set_ylim", "xscale": "set_xscale", "yscale": "set_yscale",
95
+ "xticks": "set_xticks", "yticks": "set_yticks",
96
+ }
97
+
98
+ for _name in _AXES_FUNCS:
99
+ globals()[_name] = _wrap(_name)
100
+ for _name, _target in _RENAMED.items():
101
+ globals()[_name] = _wrap(_name, _target)
102
+
103
+ __all__ = [
104
+ "figure", "gcf", "gca", "subplots", "subplot", "close", "savefig", "show", "suptitle",
105
+ "colorbar", *_AXES_FUNCS, *_RENAMED,
106
+ ]