Skip to content

Commit 1fbdcf2

Browse files
committed
ENH: add a FormattedText artist
1 parent 32a6c87 commit 1fbdcf2

File tree

2 files changed

+32
-3
lines changed

2 files changed

+32
-3
lines changed

data_prototype/wrappers.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from matplotlib.lines import Line2D as _Line2D
99
from matplotlib.image import AxesImage as _AxesImage
1010
from matplotlib.patches import StepPatch as _StepPatch
11+
from matplotlib.text import Text as _Text
1112
from matplotlib.collections import LineCollection as _LineCollection
1213
from matplotlib.artist import Artist as _Artist
1314

@@ -229,6 +230,26 @@ def _update_wrapped(self, data):
229230
self._wrapped_instance.set_data(data["density"], data["edges"])
230231

231232

233+
class FormatedText(ProxyWrapper):
234+
_wrapped_class = _Text
235+
_privtized_methods = ("set_text",)
236+
237+
def __init__(self, data: DataContainer, format_func, nus=None, /, **kwargs):
238+
super().__init__(data, nus)
239+
self._wrapped_instance = self._wrapped_class(text="", **kwargs)
240+
self._format_func = format_func
241+
242+
@_stale_wrapper
243+
def draw(self, renderer):
244+
self._update_wrapped(
245+
self._query_and_transform(renderer, xunits=[], yunits=[]),
246+
)
247+
return self._wrapped_instance.draw(renderer)
248+
249+
def _update_wrapped(self, data):
250+
self._wrapped_instance.set_text(self._format_func(**data))
251+
252+
232253
@_forwarder(
233254
(
234255
"set_clip_path",

examples/animation.py

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@
1515
from matplotlib.animation import FuncAnimation
1616

1717
from data_prototype.containers import _Transform, Desc
18-
from data_prototype.wrappers import LineWrapper
18+
19+
from data_prototype.wrappers import LineWrapper, FormatedText
1920

2021

2122
class SinOfTime:
@@ -46,7 +47,7 @@ def next_time():
4647
"x": th,
4748
"y": np.sin(th + phase),
4849
"phase": phase,
49-
"time": time,
50+
"time": cur_time,
5051
}, hash(cur_time)
5152

5253
return next_time()
@@ -58,9 +59,16 @@ def update(frame, art):
5859

5960
sot_c = SinOfTime()
6061
lw = LineWrapper(sot_c, lw=5, color="green", label="sin(time)")
61-
62+
fc = FormatedText(
63+
sot_c,
64+
"ϕ={phase:.2f} ".format,
65+
x=2 * np.pi,
66+
y=1,
67+
ha="right",
68+
)
6269
fig, ax = plt.subplots()
6370
ax.add_artist(lw)
71+
ax.add_artist(fc)
6472
ax.set_xlim(0, 2 * np.pi)
6573
ax.set_ylim(-1.1, 1.1)
6674
ani = FuncAnimation(

0 commit comments

Comments
 (0)