Matplotlib-将文本标签向右移动x点

时间:2019-02-12 14:54:30

标签: python matplotlib

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

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)

enter image description here

我有垂直和水平居中的文本标签(即1304,469等),但理想情况下,我希望它向右移动,以便远离气泡。我已经尝试过ha=right,但它只推动了一点点。

有什么可以用来将其完全从气泡中移开的东西吗?即代码,我可以输入以下for loop

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

3 个答案:

答案 0 :(得分:2)

我只是使用偏移百分比(例如20%)来重新定位文本的x坐标。另外,您可以关闭x限制的手动设置。

fig, ax = plt.subplots(figsize=(4, 10))

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]

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

plt.scatter(x, y, s=z*4000, c="#8C4799", alpha=0.3) 

enter image description here

答案 1 :(得分:1)

xytext的参数ax.annotate让您执行以下操作:

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', xytext=(1.05,y[i]) )

plt.scatter(x, y, s=z*4000, c="#8C4799", alpha=0.3)

带来此:

enter image description here

编辑:如果希望标签位于每个圆圈的右边,则必须创建一个位置数组,然后遍历它

答案 2 :(得分:1)

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

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

这将使用

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

enter image description here