x 和 y 轴为文本时标注数据点 matplotlib

Annotate data points when x and y axis is text matplotlib

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

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')

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

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

善良