首页 > 解决方案 > 如何在 matplotlib 的散点图中偏移文本?

问题描述

我在我的 PCA 中注释了两个特定点,但文本位于一堆点的中间,难以阅读。我想将它向下移动(并添加我认为我已经成功完成的箭头)。任何人都可以帮忙吗?

我通过以下方式制作了文本:

for i, txt in enumerate(cluster_center_names):
    plt.annotate(txt,(x_cluster_center[i],y_cluster_center[i]), weight="bold", fontsize=10, arrowprops=dict(arrowstyle="->", color='black'))

在此处输入图像描述

标签: pythondata-visualizationmatplotlib

解决方案


用于xytext=(x,y)设置文本的坐标。您可以以绝对值(在数据、轴或图形坐标中)或相对位置提供这些坐标,textcoords="offset points"例如。

注释教程中的更多示例

x1,y1 = 0,0
x2,y2 = 20,50
fig, ax = plt.subplots()
ax.scatter(x1,y1)
ax.annotate("Annotation",
            xy=(x1, y1), xycoords='data',
            xytext=(x2, y2), textcoords='offset points',
            arrowprops=dict(arrowstyle="->", color='black')
            )

在此处输入图像描述


推荐阅读