【问题标题】:Annotate data points when x and y axis is text matplotlib当 x 和 y 轴为文本 matplotlib 时注释数据点
【发布时间】:2019-10-09 14:18:29
【问题描述】:

我正在尝试在下面显示的图中注释数据点

enter image description here

我无法将注释文本放置在数据点的右侧。关于如何做到这一点的任何提示?

group1=df.groupby(['Year','Olympics','Medal','Hometown'])['Event'].count()
gr1_df=group1.reset_index()

bronze_data=gr1_df[gr1_df['Medal']=='Bronze']
gold_data=gr1_df[gr1_df['Medal']=='Gold']
silver_data=gr1_df[gr1_df['Medal']=='Silver']

plt.figure();
plt.style.use('seaborn');
plt.plot(bronze_data['Medal'],bronze_data['Hometown'],'*',label='Bronze Medals',alpha=0.5,markersize=10);
plt.plot(gold_data['Medal'],gold_data['Hometown'], 'o',label='Gold Medals',alpha=0.5,markersize=10);
plt.plot(silver_data['Medal'],silver_data['Hometown'],'^',label='Silver Medals',alpha=0.5,markersize=10);
plt.xlabel('Medal');
plt.ylabel('Hometown');
plt.legend();

count_data=gr1_df.groupby('Hometown')['Medal'].value_counts()
count_data.columns=['Counts']
df2=pd.DataFrame(count_data)
df2.columns=['Counts']
df2.reset_index(inplace=True)

ax=plt.gca()

for index, row in df2.iterrows():
    ax.annotate(str(row['Counts']),xy=(row['Medal'],row['Hometown']),xytext=(row['Medal'],row['Hometown']),xycoords='data')

【问题讨论】:

    标签: python matplotlib plot annotate


    【解决方案1】:

    您必须使用annotate 函数的xytexttextcoords 参数。这是一个将数字写在点右侧的调用。

    ax.annotate(str(row['Counts']),xy=(row['Medal'],row['Hometown']), xytext=(5,-3),textcoords='offset points')
    

    种类

    【讨论】:

    • @SanjSam 毫不犹豫地批准答案,让其他人知道问题已解决。种类。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-21
    • 1970-01-01
    • 1970-01-01
    • 2013-08-16
    • 2016-11-10
    • 2014-10-30
    • 1970-01-01
    相关资源
    最近更新 更多