Python 是否可以为相关图中的每个数据点添加标签?
我正在做一个按大陆划分的国家的政府信任和幸福指数之间的关联图。我想在每个数据点上添加相应的国家名称,我如何才能做到这一点?我的绘图代码如下:Python 是否可以为相关图中的每个数据点添加标签?,python,matplotlib,seaborn,data-visualization,Python,Matplotlib,Seaborn,Data Visualization,我正在做一个按大陆划分的国家的政府信任和幸福指数之间的关联图。我想在每个数据点上添加相应的国家名称,我如何才能做到这一点?我的绘图代码如下: plt.rcParams['figure.figsize'] = (6, 4) sns.scatterplot(x=df_sasia["Trust"],y=df_sasia["Happiness Score"], data=df_seasia,s=80) 以下是一种方法(散布点旁边的标签): 另一种方法是直接在(x
plt.rcParams['figure.figsize'] = (6, 4)
sns.scatterplot(x=df_sasia["Trust"],y=df_sasia["Happiness Score"], data=df_seasia,s=80)
以下是一种方法(散布点旁边的标签):
另一种方法是直接在(x,y)处绘制标签:
import pandas as pd
import numpy as np
import matplotlib.pylab as plt
import seaborn as sns
# Create dataframe
df = pd.DataFrame({
'x': [1, 1.5, 3, 4, 5],
'y': [5, 15, 5, 10, 2],
'group': ['A','other group','B','C','D']
})
# basic plot
p1=sns.regplot(data=df, x="x", y="y", fit_reg=False, marker="o",
color="blue", scatter_kws={'s':400})
def add_label(row, shift_x=0.2):
p1.text(row.x+shift_x, row.y, row.group,
horizontalalignment='left', size='medium',
color='grey', weight='semibold')
# add annotations one by one with a loop
for r in range(0, len(df)):
add_label(df.iloc[r])
#create a new figure and set the x and y limits
fig, axes = plt.subplots(figsize=(5,5))
axes.set_xlim(0.5,5.5)
axes.set_ylim(-2,16)
#loop through data points and plot each point
for l, row in df.iterrows():
#add the data point as text
plt.annotate(row['group'],
(row['x'], row['y']),
horizontalalignment='center',
verticalalignment='center',
size=11,
color='green')