代码之家  ›  专栏  ›  技术社区  ›  Alex

如何在python中自动调整散点图标签而不被其他标签重叠?

  •  0
  • Alex  · 技术社区  · 6 年前

    https://github.com/Phlya/adjustText 它看起来应该有用,但我只是想找到一个从数据帧绘制的例子。当我尝试复制adjustText示例时,它抛出了一个错误,因此这是我当前的代码。

      df["category"] = df["category"].astype(int)
      df2 = df.sort_values(by=['count'], ascending=False).head()
      ax = df.plot.scatter(x="category", y="count")
      a = df2['category']
      b = df2['count']
      texts = []
     for xy in zip(a, b):
            texts.append(plt.text(xy))
        adjust_text(texts, arrowprops=dict(arrowstyle="->", color='r', lw=0.5))
    
    plt.title("Count of {column} in {table}".format(**sql_dict))
    

    但是我得到了这个TypeError:TypeError:text()缺少2个必需的位置参数:“y”和“s”这是我试图将其转换为轴坐标的地方,它可以工作,但坐标只是重叠。

        df["category"] = df["category"].astype(int)
        df2 = df.sort_values(by=['count'], ascending=False).head()
        ax = df.plot.scatter(x="category", y="count")
        a = df2['category']
        b = df2['count']
        for xy in zip(a, b):
            ax.annotate('(%s, %s)' % xy, xy=xy)
    

    正如您在这里看到的,我将从sql中的表构造df,并且我将向您提供这个特定表在这里应该是什么样子的。在这个特定的表中,它是以天为单位的停留时间与有多少人停留那么长时间的比较。

    [![picture of a graph of overlapping items][1]][1]
    

    enter image description here [洛杉矶天数] 3 350 1 4000 15 34

    等等。非常感谢。如果你还需要什么,请告诉我。

    这里是df的一个例子

           category  count
    0          2  29603
    1          4  33980
    2          9  21387
    3         11  17661
    4         18  10618
    5         20   8395
    6         27   5293
    7         29   4121
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Alex    6 年前

        labels = ['{}'.format(i) for i in zip(a, b)]
        texts = []
        for x, y, text in zip(a, b, labels):
            texts.append(ax.text(x, y, text))
        adjust_text(texts, force_text=0.05, arrowprops=dict(arrowstyle="-|>",
                                                            color='r', alpha=0.5))
    

    enter image description here

    推荐文章