Python 标注箭头方向

Python anotation arrow direction

我正在尝试使用 Matplotlib 在 Python 2.7 中注释散点图。剧情代码如下:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.DataFrame(np.random.rand(5,3), columns=list('ABC'))
df.insert(0,'Annotation_Text',['ABC','DEF','GHI','JKL','mnop'])

q = 2
pqr = 1

# Scatter Plot:
x = df['A']
y = df.iloc[:,q]
plt.scatter(x, y, marker='o', label = df.columns.tolist()[q])

# Plot annotation:
plt.annotate(df.iloc[pqr,0]+', (%.2f, %.2f)' % (x.ix[pqr],y.ix[pqr]), xy=(x.ix[pqr], y.ix[pqr]), xycoords='data', xytext = (x.ix[pqr], y.ix[pqr]), textcoords='offset points', arrowprops=dict(arrowstyle='-|>'))

# Axes title/legend:
plt.xlabel('xlabel', fontsize=18)
plt.ylabel('ylabel', fontsize=16)
plt.legend(scatterpoints = 1)

plt.show()

可以看到,主线是plt.annotate(df.iloc[pqr,0]+', (%...............开头的那一行。

我认为主要问题出在 plt.annotate() 行的这一部分:xytext = (x.ix[pqr], y.ix[pqr]), textcoords='offset points', arrowprops=dict(arrowstyle='-|>')。从这里开始,xytext = (x.ix[pqr], y.ix[pqr]) 只是要注释的数据点的 x 和 y 坐标的元组。不幸的是,这是将注释放在数据点上,这是我不想要的。我想在数据点和注释文本之间留一些空白 space。

此外,我对这条线生成的箭头和注释有疑问。见下文。

问题:

有没有办法控制文本标注不与数据点重叠?另外,如何将箭头方向从右到左更改为 a) best 方向或 b) 从左到右?

plt.annotate(...)中,xy给出了你想要指向的数据的位置(箭头的一端),xytext给出了你的文本的位置。在您的代码中,它们是重叠的,因为您为 xyxytext 指定了相同的位置。试试这个(例如):

plt.annotate(df.iloc[pqr,0]+', (%.2f, %.2f)' % (x.ix[pqr], y.ix[pqr]), xy=(x.ix[pqr], y.ix[pqr]), xycoords='data', xytext=(x.ix[pqr], y.ix[pqr]+0.3), arrowprops=dict(arrowstyle='-|>'), horizontalalignment='center')

箭头默认从文本指向数据点。如果要改变箭头的方向,可以使用arrowprops=dict(arrowstyle='<|-')