有没有办法在 matplotlib 上标记/注释我的气泡图(带有 z 轴的散点图)?

数据挖掘 Python 可视化 matplotlib
2021-10-09 02:19:37

我想标记我的气泡图,标签在气泡内。像这样的东西。 气泡图

有没有办法做到这一点?

我试过的:

plt.annotate(temp.index, (temp.gre_total, temp.ugrad_gpa))
plt.show()

但这会引发错误。我认为这只有在我遍历每个值时才有效?我不太确定。

1个回答

您可以使用 seaborn 包,使用散点图标记大小来生成您的气泡然后,您需要遍历数据点并为散点图中的每个点添加一个文本标签。

# Load libraries
import pandas as pd
import matplotlib.pylab as plt
import seaborn as sns

# Create example dataframe
df = pd.DataFrame({
'x': [1, 1.1, 1.2, 2, 5],
'y': [5, 15, 7, 10, 2],
's': [10000,20000,30000,40000,50000],
'group': ['Stamford','Yale','Harvard','MIT','Cambridge']
})

#Create figure
plt.figure(figsize = (15,10))

# Create scatterplot. alpha controls the opacity and s controls the size.
ax = sns.scatterplot(df.x, df.y, alpha = 0.5,s = df.s)

ax.set_xlim(0,6)
ax.set_ylim(-2, 18)

#For each point, we add a text inside the bubble
for line in range(0,df.shape[0]):
     ax.text(df.x[line], df.y[line], df.group[line], horizontalalignment='center', size='medium', color='black', weight='semibold')

哪个输出: 在此处输入图像描述