Snap or lock text to marker in Matplotlib

Is there a way to anchor or lock text to a marker? When using the interactive zoom provided pyplot, the text moves beyond, as shown.

import matplotlib.pyplot as plt

x=[2,4]
y=[2,3]

fig, ax = plt.subplots()
ax.plot(x, y, 'ro',markersize=23)

offset = 1.0 
ax.set_xlim(min(x)-offset, max(x)+ offset)
ax.set_ylim(min(y)-offset, max(y)+ offset)

for x,y in zip(x,y):
     ax.annotate(str(y),  xy=(x-0.028,y-0.028))

plt.show()

Text is out of bounds

+4
source share
1 answer

The simple answer is that it runs by default. The text of the lower left corner is anchored to the position indicated by xy. Now, as you can see in the figures below, when interactively scaling one of the markers, the relative position of the marker and the text is preserved.

import matplotlib.pyplot as plt

x=[2,4]
y=[2,3]

fig, ax = plt.subplots()
ax.plot(x, y, 'ro',markersize=23)

offset = 1.0 
ax.set_xlim(min(x)-offset, max(x)+ offset)
ax.set_ylim(min(y)-offset, max(y)+ offset)

for x,y in zip(x,y):
     ax.annotate(str(y),  xy=(x,y))

plt.show()

enter image description hereenter image description here

, , . , , 0,028 xy=(x-0.028,y-0.028), , , , . , matplotlib . , 0.028 , "" , .

, . annotate textcoords offset point. xytext ( ) xy:

ax.annotate(str(y),  xy=(x,y), xytext=(-5.0,-5.0), textcoords='offset points')

, , . , , . . . :

import matplotlib.pyplot as plt

x=[2,4]
y=[2,12]

fig, ax = plt.subplots()
ax.plot(x, y, 'ro',markersize=23)

offset = 1.0 
ax.set_xlim(min(x)-offset, max(x)+ offset)
ax.set_ylim(min(y)-offset, max(y)+ offset)

for x,y in zip(x,y):
    text = str(y)
    fontsize, aspect_ratio = (12, 0.5) # needs to be adapted to font
    width = len(text) * aspect_ratio * fontsize 
    height = fontsize
    a = ax.annotate(text,  xy=(x,y), xytext=(-width/2.0,-height/2.0), textcoords='offset points')

plt.show()

enter image description here

2, - , . . .

+1

Source: https://habr.com/ru/post/1568547/


All Articles