How to label bubble chart/scatter plot with column from pandas dataframe?

前端 未结 2 1768
盖世英雄少女心
盖世英雄少女心 2020-12-30 11:52

I am trying to label a scatter/bubble chart I create from matplotlib with entries from a column in a pandas data frame. I have seen plenty of examples and questions related

相关标签:
2条回答
  • 2020-12-30 12:08

    You can use DataFrame.plot.scatter and then select in loop by DataFrame.iat:

    ax = df.plot.scatter(x='x', y='y', alpha=0.5)
    for i, txt in enumerate(df.users):
        ax.annotate(txt, (df.x.iat[i],df.y.iat[i]))
    plt.show()
    

    0 讨论(0)
  • 2020-12-30 12:13

    Jezreal's answer is fine, but i will post this just to show what i meant with df.iterrows in the other thread.

    I'm afraid you have to put the scatter (or plot) command in the loop as well if you want to have a dynamic size.

    df = pd.DataFrame(dict(x=x, y=y, s=s, users=users))
    
    fig, ax = plt.subplots(facecolor='w')
    
    for key, row in df.iterrows():
        ax.scatter(row['x'], row['y'], s=row['s']*5, alpha=.5)
        ax.annotate(row['users'], xy=(row['x'], row['y']))
    

    0 讨论(0)
提交回复
热议问题