Matplotlib文本轴数据点标注:如何将标注置于数据点右侧?
Fixing Annotation Positioning Next to Data Points in Matplotlib
Hey there! I see the issue with your annotation placement—right now, you're setting xytext to the exact same coordinates as xy, so the label is overlapping with your data points instead of sitting to the right. Let's adjust that, and since your x-axis uses categorical values (Bronze/Gold/Silver), we'll use relative offset positioning to make this work smoothly.
The Key Fix
Instead of setting xytext to match the data point coordinates, we'll use offset points to shift the label to the right of each marker. Here's the revised code with the fix integrated:
import pandas as pd import matplotlib.pyplot as plt # Your original data processing (unchanged) 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'] # Plot setup (unchanged) 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 processing (unchanged) count_data = gr1_df.groupby('Hometown')['Medal'].value_counts() df2 = pd.DataFrame(count_data, columns=['Counts']).reset_index() # Modified annotation loop ax = plt.gca() for index, row in df2.iterrows(): ax.annotate( str(row['Counts']), xy=(row['Medal'], row['Hometown']), xytext=(10, 0), # Shift text 10 points to the right, no vertical shift textcoords='offset points', # Treat xytext as relative offset from xy va='center' # Vertically align text with the marker's center ) plt.show()
What Changed?
xytext=(10, 0): Moves the annotation 10 points to the right of the data point (tweak the 10 to make the gap bigger or smaller as needed).textcoords='offset points': Critical for categorical axes—this tells Matplotlib thexytextvalues are relative offsets, not absolute coordinates (since your x-axis isn't numerical).va='center': Ensures the text lines up perfectly with the middle of your marker, making the plot look polished.
This will place your count labels neatly to the right of each medal/hometown data point without overlap!
内容的提问来源于stack exchange,提问作者SanjSam
相关产品推荐
相关产品推荐

