如何在matplotlib的散点图中放置多类图例?

2024-10-03 13:27:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把图例放在散点图中,我使用了c参数对类进行分组并分配颜色。 我的代码如下:

peral = data[['SiO2a', 'A/CNK','Type', 'Code']]**
Locality    SiO2a   A/CNK   Type    Code
0   CN  71.58   1.13    Rhyolite    7
1   CN  71.76   1.14    Rhyolite    7
2   CN  70.95   1.08    Rhyolite    7
3   CN  70.79   1.14    Rhyolite    7
4   CN  71.69   1.12    Rhyolite    7
...     ...     ...     ...     ...     ...
158     Pairique    63.74   1.09    mafic inclusion     11
159     Pairique    61.77   1.09    mafic inclusion     11
160     Huayra Huasi    65.43   1.10    mafic inclusion     11
161     Huayra Huasi    61.14   1.26    mafic inclusion     11
162     Huayra Huasi    62.53   1.21    mafic inclusion     11
plt.figure(figsize=(10,10))
plt.scatter(peral['SiO2a'], peral['A/CNK'], c=peral['Code'])
plt.legend()
plt.ylim(0.8,2.5)
plt.xlabel('SiO2 %wt')
plt.ylabel('A/CNK')

Scatter plot

'Code'是将LabelEncoder应用于列'Type'的结果,我想用列'Type'的原始名称构造图例

有人知道怎么做吗


Tags: 参数typecodepltcn图例inclusioncnk
1条回答
网友
1楼 · 发布于 2024-10-03 13:27:08

您可以在'Type'值上循环,并将每个值作为筛选器应用:

for type_ in df['Type'].unique():
    ax.scatter(df[df['Type'] == type_]['SiO2a'], df[df['Type'] == type_]['A/CNK'], marker = 'o', label = type_)

完整代码

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv(r'data/data.csv')

fig, ax = plt.subplots(figsize = (10, 10))

for type_ in df['Type'].unique():
    ax.scatter(df[df['Type'] == type_]['SiO2a'], df[df['Type'] == type_]['A/CNK'], marker = 'o', label = type_)

ax.legend(frameon = True)
ax.set_ylim(0.8,2.5)
ax.set_xlabel('SiO2 %wt')
ax.set_ylabel('A/CNK')

plt.show()

enter image description here

相关问题 更多 >