How to compensate lines in matplotlib by X points

I use matplotlib to build some data that I want to comment with arrows (distance markers). These arrows should be offset by several points so as not to overlap with line data:

import matplotlib.pyplot as plt
import matplotlib.transforms as transforms

fig, ax = plt.subplots()

x = [0, 1]
y = [0, 0]

# Plot horizontal line
ax.plot(x, y)

dy = 5/72

offset = transforms.ScaledTranslation(0, dy, ax.get_figure().dpi_scale_trans)
verttrans = ax.transData+offset

# Plot horizontal line 5 points above (works!)
ax.plot(x, y, transform = verttrans)

# Draw arrow 5 points above line (doesn't work--not vertically translated)
ax.annotate("", (0,0), (1,0),
            size = 10,
            transform=verttrans,
            arrowprops = dict(arrowstyle = '<|-|>'))

plt.show()

Is there any way to make the lines drawn ax.annotate()by offset points of X? I want to use absolute coordinates (for example, points or inches) instead of data coordinates, since the limits of the axis are subject to change.

Thank!

+4
source share
2 answers

The following code does what I wanted. It uses ax.transData and figure.get_dpi ():

import matplotlib.pyplot as plt
import matplotlib.transforms as transforms

fig, ax = plt.subplots()


x = [0, 1]
y = [0, 0]


ax.plot(x, y)


dy = 5/72

i = 1  # 0 for dx

tmp = ax.transData.transform([(0,0), (1,1)])
tmp = tmp[1,i] - tmp[0,i]  # 1 unit in display coords
tmp = 1/tmp  # 1 pixel in display coords
tmp = tmp*dy*ax.get_figure().get_dpi()  # shift pixels in display coords

ax.plot(x, y)

ax.annotate("", [0,tmp], [1,tmp],
            size = 10,
            arrowprops = dict(arrowstyle = '<|-|>'))

plt.show()
+3
source

? , , API annotate -

annotate(s, xy, xytext=None, ...)

-

ax.annotate("", (0,0.01), (1,0.01),
    size = 10,
    arrowprops = dict(arrowstyle = '<|-|>'))

0.01 y. annotate (. doc). , ?

+2

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


All Articles