我在pyplot中遇到文本对齐方面的困难。我试图在圆形树状图中注释以圆形方式排列的点,因此重要的是标签指向远离点并保持直角。这是我到目前为止的相关部分。
水平标签就像一个魅力,但垂直标签显然是关闭的。似乎horizontalalignment
/ verticalalignment
应用于原始坐标和边界框。是否有任何选项/方式来正确对齐标签而不执行一些疯狂的特技,比如找出文本高度并相应地移动标签。我想知道用极坐标覆盖第二个绘图/轴并将文本放在上面是否有意义,但我不确定这是否会引导我到任何地方。或者说我错过了一些非常明显的东西......
这是一个最小的工作示例:
import matplotlib.pyplot as plt
(fig, ax) = plt.subplots(figsize = (4,4))
def kex(N):
alpha = 360. / N
coordX = []
coordY = []
alphas = []
for i in range(0,N):
alpha_loop = alpha * i
coordX.append( math.cos(math.radians(alpha_loop)) )
coordY.append( math.sin(math.radians(alpha * i)) )
alphas.append(alpha_loop)
return [coordX, coordY, alphas]
N = 10
points = kex(N)
ax.scatter(points[0], points[1])
for i in range(0,N):
x = points[0][i]
y = points[1][i]
a = points[2][i]
if x > 0:
ax.text(x + x * 0.1, y + y * 0.1, "AAA", rotation = a,
bbox=dict(facecolor = "none", edgecolor ="red"))
else:
ax.text(x + x * 0.1, y + y * 0.1, "AAA", rotation = a - 180,
bbox=dict(facecolor = "none", edgecolor ="red"), ha = "right")
ax.axis("off")
plt.show()
感谢任何帮助!
答案 0 :(得分:2)
您可以将文本偏移到足以使其与点重叠。然后,我们的想法是对文本进行居中对齐(ha="center", va="center"
),这样就可以坐在图形中点和它注释点之间的扩展(虚拟)线上。
import matplotlib.pyplot as plt
import numpy as np
(fig, ax) = plt.subplots(figsize = (4,4))
def kex(N):
alpha=2*np.pi/N
alphas = alpha*np.arange(N)
coordX = np.cos(alphas)
coordY = np.sin(alphas)
return np.c_[coordX, coordY, alphas]
N = 10
r = 1.2
points = kex(N)
ax.scatter(points[:,0], points[:,1])
for i in range(0,N):
a = points[i,2]
x,y = (r*np.cos(a), r*np.sin(a))
if points[i,0] < 0: a = a - np.pi
ax.text(x,y, "AAA", rotation = np.rad2deg(a), ha="center", va="center",
bbox=dict(facecolor = "none", edgecolor ="red"))
ax.axis("off")
plt.show()