Python matplotlib旋转文本具有偏移量

Python matplotlib旋转文本具有偏移量,python,matplotlib,Python,Matplotlib,我试图在一些线的边界内画一些文字。行可以旋转,因此文本也需要旋转 当我添加没有旋转的文本时,它似乎有正确的位置和大小。但旋转之后,情况并非如此(最好在看图片时进行解释) 以下是我尝试过的: import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots(1) fig.set_dpi( 100 ) fig.set_size_inches( 1, 1 ) # Plot diagonal line (45 degr

我试图在一些线的边界内画一些文字。行可以旋转,因此文本也需要旋转

当我添加没有旋转的文本时,它似乎有正确的位置和大小。但旋转之后,情况并非如此(最好在看图片时进行解释)

以下是我尝试过的:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(1)
fig.set_dpi( 100 )
fig.set_size_inches( 1, 1 )

# Plot diagonal line (45 degrees)
ax.plot((0, 0),(0, 10))
ax.plot((10, 10), (0, 10))
ax.plot((0, 10), (10, 10))
ax.plot((0, 10), (0, 0))
ax.plot((0,10),(1.3,1.3)) # font size 10 has 13 pixels, hence 1.3
ax.plot((3,10),(3,10))

# compute the offset of the line that is exactly 1.3 above the diagonal
d = np.array([-1,1])
d = d / np.sqrt(sum(d**2)) * 1.3
u = np.array([3,3]) + d
ax.plot( (u[0], 10+u[0]-u[1]), (u[1], 10 ))

# set limits so that it no longer looks on screen to be 45 degrees
ax.set_xlim([0, 10])
ax.set_ylim([0, 10])

# Plot text
ax.text(0,0, 'In', fontsize=10 )
ax.text(4,0, 'Bbox', fontsize=10, bbox={"pad":0} )
ax.text(3,3, 'Out', fontsize=10, rotation=45, verticalalignment="bottom", \
    horizontalalignment="left", rotation_mode="anchor" )
ax.text(6,6, 'Bbox', fontsize=10, rotation=45, verticalalignment="bottom", \
    horizontalalignment="left", rotation_mode="anchor",bbox={"pad":0} )
plt.axis("off")
plt.savefig( "test.pdf", bbox_inches="tight" )
这给了我以下输出。使用旋转但偏移的文本打印:

请注意,“Out”并不完全符合其两条相邻线的预期。 有人知道如何调整/修复此问题吗?

对于“文本”中的
,您可以使用
verticalalignment=“baseline”
(隐式地,因为这是默认设置)。对于
“Out”
文本,您使用
垂直对齐=“bottom”

您也可以将其更改为
verticalalignment=“baseline”
,或者完全忽略它

ax.text(0,0, 'In', fontsize=10 )
ax.text(4,0, 'Bbox', fontsize=10, bbox={"pad":0} )
ax.text(3,3, 'Out', fontsize=10, rotation=45, 
        horizontalalignment="left", rotation_mode="anchor" )
ax.text(6,6, 'Bbox', fontsize=10, rotation=45, 
        horizontalalignment="left", rotation_mode="anchor",bbox={"pad":0} )


matplotlib网站上有一个很好的例子解释了这种行为。

谢谢!显然我忽略了默认参数。还感谢您提供演示的链接。matplotlib网站对我来说仍然有点混乱。。。