【问题标题】:Matplotlib How to calculate the bottom y value of a scatter dotMatplotlib 如何计算散点的底部 y 值
【发布时间】:2019-07-02 21:40:32
【问题描述】:

代码如下:

import itertools
import pandas as pd
import matplotlib.pyplot as plt

# reuse these colors
colors = itertools.cycle(["r", "b", "g"])

# some random data
df = pd.DataFrame({'x':[1,2,3,4,5],
                   'y':[2,4,5,2,4],
                   'area': [100, 200, 400, 500, 800],
                   'label': ['blah1','blah2','blah3','blah4','blah5']
                  })

# draw a scatter plot
def draw_scatter_plot(
    x,
    y,
    marker_size,
    marker_color: itertools.cycle,
    labels
):


    fig, ax = plt.subplots(figsize=(12, 8))

    if marker_size:
        i = 0
        while i<len(x):
            ax.scatter(x[i], y[i], color = next(marker_color), s = marker_size[i])
            ax.annotate(
                    labels[i],
                    (x[i], y[i]), # adjust y[i] here
                    fontproperties=cur_font,
                    fontsize=14,
                    ha="center",
                    va="top",
                )
            i+=1


    plt.show()

draw_scatter_plot(df.x.tolist(),
                  df.y.tolist(),
                  df.area.tolist(),
                  colors,
                  df.label.tolist())

结果如下:

如您所见,标签与圆圈底部重叠。如何计算圆的底部 y 值,以便始终可以定位标签,使其不与圆重叠?

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    我们的想法是将文本移动散点直径的一半,np.sqrt(marker_size[i])/2.。然后,您可以添加额外的 2 个点,使文本不接触标记。

    ax.annotate(labels[i],
                xy=(x[i], y[i]), 
                xytext=(0, -np.sqrt(marker_size[i])/2. - 2),
                textcoords="offset points",                    
                ha="center",
                va="top")
    

    【讨论】:

      【解决方案2】:

      一种解决方案是使用textcoords,如this 答案所示。您可以关闭原始答案中的精美框。

      ax.annotate(labels[i],(x[i], y[i]), xytext=(0, -15),
                  textcoords='offset points', fontsize=14,ha="center",va="top",)
      

      【讨论】:

      • 感谢您的回复,非常感谢。如您所见,圆圈的大小各不相同,有没有办法获得圆圈的实际大小并相应地调整 y 位置? (而不是 y 位置的硬编码 -15)
      • @Cheng 尝试答案here 以及这些答案中发布的链接,以获得数据坐标中的散点大小。
      【解决方案3】:

      您可以按如下方式更改注释:

      [plt.annotate("{}, {}".format(x,y), xy=(x,y), xytext=(x-.1,y-.16)) for x, y in zip(x, y)]
      

      使用它,您必须根据 x,y 轴的缩放比例来缩放 yxtext 坐标。

      还有一条评论:因为您在 while 循环中使用它,您可能希望将其更改为:

      plt.annotate("{}, {}".format(x[i],y[i]), xy=(x[i],y[i]), xytext=(x[i]-.1,y[i]-.16))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多