Вычисление поворота текста Matplotlib - PullRequest
0 голосов
/ 25 июня 2018

Я пытаюсь выяснить, как повернуть текст в matplotlib, чтобы выровнять его по кривой на графике, но я не понял, какие преобразования дают правильную систему координат для поворота текста, чтобы соответствовать определенному наклону в координатах данных. Вот минимальный пример рисования линии и попытки выровнять текст вдоль нее:

# Make some really non-square figure
plt.figure(figsize=(2,5))

# Draw some line between two points
pB=np.array((0,0))
pA=np.array((1,2))
pC=(pA+pB)/2
plt.plot(*zip(pA,pB))

# All the transforms at our disposal
tD=plt.gca().transData
tA=plt.gca().transAxes
tF=plt.gcf().transFigure

# Transform the endpoints of the line two some coordinate system
pA,pB=[
        ##### What goes here???
        p    # <- trivial no transform
        #tD.transform(p)
        #tA.inverted().transform(tD.transform(p))
        #tF.inverted().transform(tD.transform(p))
    for p in (pA,pB)]

# Then calculate the angle of the line
rise,run=pA-pB
rot=(180/np.pi)*np.arctan(rise/run)

# Draw some text at that angle
plt.text(pC[0],pC[1],'hi there',rotation=rot,
         horizontalalignment='center',verticalalignment='bottom');

Независимо от того, что я пытаюсь, текст по-прежнему дезориентирован:

[это изображение для случая без преобразования выше, представленного с помощью опции %matplotlib inline в записной книжке Jupyter.]

enter image description here

1 Ответ

0 голосов
/ 25 июня 2018

Как предлагается в комментариях, вы можете включить пропорциональное соотношение между абстрактным представлением ( размер оси ) и фактическим числом ( размер рисунка ). Угол поворота текста является абсолютной мерой, когда угол кривой зависит от шкалы оси

# define the figure size
fig_x, fig_y = 4, 8
plt.figure(figsize=(fig_x, fig_y))

# Draw some line between two points
pB = np.array((0, 0))
pA = np.array((1, 2))
pC = (pA+pB)/2
plt.plot(*zip(pA, pB))

# Calculate the angle of the line
dx, dy = pA-pB
# --- retrieve the 'abstract' size
x_min, x_max = plt.xlim()
y_min, y_max = plt.ylim()
# --- apply the proportional conversion
Dx = dx * fig_x / (x_max - x_min)
Dy = dy * fig_y / (y_max - y_min)
# --- convert gaps into an angle
angle = (180/np.pi)*np.arctan( Dy / Dx)

# Draw  text at that angle
plt.text(pC[0], pC[1], 'it worked', rotation=angle,
         horizontalalignment='center', verticalalignment='bottom')
plt.show()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...