在 matplotlib 中以不同大小的标记顶部进行注释

问题描述 投票:0回答:1

我可以获取标记的坐标以将注释移动到三角形的顶部吗?

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()

这给了我:

python python-3.x matplotlib
1个回答
0
投票

您需要 (a) 将 y 坐标移动与标记高度成比例的距离; (b) 将文本置于底部中心(美式中的“中心”!)。

请注意,标记的“大小”与其面积成正比。所以它的高度与 sqrt(size) 成正比。

一定量的尝试和错误产生了这一点。高度缩放可能取决于标记的类型。

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()

© www.soinside.com 2019 - 2024. All rights reserved.