Skip to main content
 首页 » 编程设计

python之Matplotlib之将文本标签向右移动 'x' 点

2025年05月04日19jpfss

我有以下代码生成气泡图,然后将标签作为文本添加到图中:

fig, ax = plt.subplots(figsize = (5,10)) 
 
# create data 
x = [1,1,1,1,1,1,1,1,1,1] 
y = ['A','B','C','D', 
     'E','F','G','H','I',''] 
z = [10,20,80,210,390,1050,2180,4690,13040,0] 
 
labels = [1,2,8,21,39,105,218,469,1304] 
 
plt.xlim(0.9,1.1) 
 
for i, txt in enumerate(labels): 
    ax.annotate(txt, (x[i], y[i]), ha='center', va='center', ) 
 
plt.scatter(x, y, s=z*4000, c="#8C4799", alpha=0.3) 

我将文本标签垂直和水平居中(即 1304,469 等),但理想情况下我希望它向右移动,以便远离气泡。我试过 ha=right,但它只是稍微插入了它。

有什么我可以用来让它完全远离气泡的东西吗? IE。代码我可以把它放在下面的 for loop:

for i, txt in enumerate(labels): 
    ax.annotate(txt, (x[i], y[i]), ha='center', va='center', ) 

请您参考如下方法:

由于气泡的大小 s 为 s=z*4000,因此气泡的半径为 np.sqrt(z*4000)/2。 (有关解释,请参阅 scatter plot marker size)。

因此,您将创建一个注释,该注释位于数据坐标中气泡的中心,并以点(或可能为 2)为单位将其偏移 np.sqrt(z*4000)/2或多加 3 分以使其看起来更漂亮)。

这将使用

来完成
annotate("text", xy=(x[i],y[i]),  
         xytext=(np.sqrt(z[i]*4000)/2+2, 0),  textcoords="offset points") 

完整示例:

import matplotlib.pyplot as plt 
import numpy as np 
 
 
fig, ax = plt.subplots(figsize = (5,10)) 
 
# create data 
x = [1,1,1,1,1,1,1,1,1,1] 
y = ['A','B','C','D', 
     'E','F','G','H','I',''] 
z = [10,20,80,210,390,1050,2180,4690,13040,0] 
 
labels = [1,2,8,21,39,105,218,469,1304] 
 
plt.xlim(0.9,1.1) 
 
 
sc = plt.scatter(x, y, s=z*4000, c="#8C4799", alpha=0.3) 
 
for txt, size, xi, yi in zip(labels, sc.get_sizes(), x,y): 
    ax.annotate(txt, xy=(xi,yi), xytext=(np.sqrt(size)/2+2, 0), 
                textcoords="offset points", 
                ha='left', va='center', ) 
 
plt.show()