I have a customized Text
object, which has the same logic as the following simplified object:
import matplotlib.pyplot as plt
from matplotlib.text import Text
class MyText(Text):
def __init__(self, x, y, txt, height, **kwargs):
super().__init__(x, y, txt, **kwargs)
self.height = height
def mydraw(self, ax):
txt = ax.add_artist(self)
myset_fontsize(txt, self.height)
return self
def set_height(self, height):
self.height = height
#myset_fontsize(self, height)
def myset_fontsize(txtobj, height):
trans = txtobj.get_transform()
pixels, _ = trans.transform((txtobj.height, 0)) - trans.transform((0,0))
dpi = txtobj.axes.get_figure().get_dpi()
points = pixels / dpi * 72
txtobj.set_fontsize(points)
if __name__ == '__main__':
fig, ax = plt.subplots()
ax.grid(True)
txt = MyText(0.2, 0.2, 'hello', 0.1)
txt.mydraw(ax)
MyText
is different from the built-in Text
in that the fontsize is dependent on the height
, which, for example, specifies the height of the text in the data coordinates. Except this, MyText
is almost the same as Text
. The example code gives the following figure:
This works fine for a static image. However, I want MyTest
to be interactive, which includes the following goals:
In an interactive plot mode,
txt.set_height(0.5)
shoule change the fontsize dynamically. I know I can add a snippet as the comment shows, but ifMyText
object is not added to the axes,txt.set_height(0.5)
will throw anAttributeError
. In short,txt.set_height()
should behave similarly totxt.set_fontsize()
.When the figure is resized by dragging the plot window,
MyText
should change the fontsize accordingly, that is, the height of text in the data coordinates should keep the same. But currently the fontsize is unchanged when resizing the figure. I have found this answer, butmpl_connect
needs some way to get theFigure
object, and I wantMyText
interactive after callingtxt.mydraw(ax)
.
- When I change the aspect ratio of the figure,
MyText
should change the fontsize accordingly, same as the second point.
Thanks for any ideas!