Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pyplot Keep Text Size While Zooming

I would like to have some text in a pyplot figure, and be able to zoom in on it without it changing scale. See below example of the plot, what I'd like to happen, and what actually happens.
Code reproducing the error:

import matplotlib.pyplot as plt
plt.plot((0, 0, 1, 1, 0), (1, 0, 0, 1, 1))
plt.text(0, 0, 'Test', fontsize=150)
plt.show()

Example pictures: The Example Plot What I Would Like To Happen When Zooming What Actually Happens

like image 872
Rotem Shalev Avatar asked Jan 19 '26 12:01

Rotem Shalev


1 Answers

Text in matplotlib is defined in points. Points is an absolute quantity, proportional to inches. Text will hence always have the same size.

Here you would like to define text in data coordinates. This is possible by converting the text to a path first, then adding that path to the axes. It's done via a TextPath, which is subsequently converted to a PathPatch

import matplotlib.pyplot as plt
from matplotlib.textpath import TextPath
from matplotlib.patches import PathPatch

plt.plot((0, 0, 1, 1, 0), (1, 0, 0, 1, 1))

tp = TextPath((0,0), "Test", size=0.4)
plt.gca().add_patch(PathPatch(tp, color="black"))

plt.show()

enter image description here

like image 131
ImportanceOfBeingErnest Avatar answered Jan 21 '26 02:01

ImportanceOfBeingErnest



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!