在matplotlib中为不同大小的标记顶部添加注释

2 投票
1 回答
32 浏览
提问于 2025-04-12 18:18

我能否获取标记的坐标,以便把注释移动到三角形的顶部?

import matplotlib.pyplot as plt

X = [1,2,3,4,5]
Y = [1,1,1,1,1]
labels = 'ABCDE'
sizes = [1000, 1500, 2000, 2500, 3000]

fig, ax = plt.subplots()

ax.scatter(X, Y, s= sizes, marker = 10)

for x, y, label, size in zip(X, Y, labels, sizes):
    print(x,y)
    ax.annotate(label, (x, y), fontsize=12)

plt.show()

这给了我:

在这里输入图片描述

1 个回答

3

你需要做的是 (a) 根据标记的高度来调整 y 坐标;(b) 把文字放在标记的底部中间位置(在美国,这叫“中心”)。

要注意,标记的“大小”是和它的面积成正比的。所以它的高度和大小的平方根是成正比的。

经过一番尝试和错误,得出了这个结果。高度的缩放可能还和标记的类型有关。

import math
import matplotlib.pyplot as plt

X = [1,2,3,4,5]
Y = [1,1,1,1,1]
labels = 'ABCDE'
sizes = [1000, 1500, 2000, 2500, 3000]

fig, ax = plt.subplots()

ax.scatter(X, Y, s= sizes, marker = 10)

for x, y, label, size in zip(X, Y, labels, sizes):
    print(x,y,size)
    ax.annotate(label, (x, y + math.sqrt( size ) / 3000 ), horizontalalignment='center', fontsize=12)

plt.show()

enter image description here

撰写回答