python - 如何在散点图中添加特定标签?

标签 python matplotlib jupyter-notebook scatter

我正在尝试使用 matplotlib 在 python 中标记散点图中的几个点。

我的 x 和 y 是主要列和次要列。我希望能够通过国家/地区名称列来注释和增加点的大小(例如标签中国和美国)。

我的表名为 df6,它包含多个列。我想从国家/地区名称列中标记 5 个点。

enter image description here

x = df6.primary
y = df6.secondary
z = df6.Country Name
plt.title('Primary & Secondary')
plt.xlabel('Primary')
plt.ylabel('Secondary')
plt.show()

enter image description here

最佳答案

我制作了一个简单的 DataFrame 来展示如何做到这一点;主要的“技巧”是用 df['Country Name'].isin( … ) 创建一个 mask 。并获取掩码为 True 的 (x,y,label) 值:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

data={
    'x':np.arange(0,7,1),
    'y':np.arange(0,7,1),
    'Country Name':['Aruba','Germany','Austria','China','USA','England','Italy']
}

df=pd.DataFrame(data)

plt.scatter(df['x'],df['y'],c="b",s=3**2,zorder=2)

selectedCountries=['Germany','USA', 'China']
mask=(df['Country Name'].isin( selectedCountries ))
plt.scatter(df['x'][mask],df['y'][mask],c="r",s=5**2,zorder=3)

for (x,y,label) in df[['x','y','Country Name']][mask].values:
    plt.text(x,y,label,zorder=4)

plt.show()

关于python - 如何在散点图中添加特定标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55884803/

相关文章:

python - 不断收到TypeError : 'list' object is not callable

Python 使用 mechanize 提交 post 数据

python - 将参数从主窗口传递到弹出的 Qdialog 窗口

jupyter-notebook - 如何更改 Jupyter 笔记本中的编辑模式快捷方式?

python - 如何删除 Matplotlib 图中的线条

matplotlib - 在matplotlib中创建多个大小不等的列和行

python - 如何绘制以时间序列为行的 Pandas 数据框?

python - 两个分类变量的笛卡尔积

python - Pandas - 根据 A 列中的值访问 B 列中的值

jupyter-notebook - 如何检测是在 Jupyter Notebook 还是 Lab