python - 当 x 轴和 y 轴为文本时注释数据点 matplotlib

标签 python matplotlib plot annotate

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

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

最佳答案

您必须使用 annotatexytexttextcoords 参数。功能。这是一个将数字写在点右侧的调用。

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

善良

关于python - 当 x 轴和 y 轴为文本时注释数据点 matplotlib,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58306255/

相关文章:

python - 使用 matplotlib 绘制数组列表

python - 与python的matplotlib图交互: assign value to selected features

r - 如何在同一窗口中打印三个维恩图

python - 如何使用 apply 将列作为参数传递给类

python - 在 Python 中使用 Enter 键触发按钮单击

python - 如何实现自动更新的可变 PickleTypes

matlab - Matlab 中具有密度的散点图

python - Pandas 分类数据类型的行为不符合预期

Python Pandas 绘制由 secondary_y 更改的图层顺序

r - 为什么我的用户在 ggplot2 的 geom_text 中提供的标签会生成错误?