如何根据数据帧中的值为散点图指定颜色

2024-09-29 17:15:23 发布

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

使用Bones1数据框,绘制spnbmd与年龄的散点图。公点和母点应具有不同的颜色或符号

到目前为止,我已经创建了dataframe bone1:

     idnum    age  gender    spnbmd  obs_num
0        1  11.70    male  0.018081        1
3        2  13.25    male  0.010264        1
6        3  11.40    male -0.029641        1
9        4  10.55  female  0.108043        1
12       5  12.75  female  0.096414        1
..     ...    ...     ...       ...      ...
480    380  11.60    male  0.116368        1
481    381   9.80  female  0.097902        1
482    382  11.90    male  0.028986        1
483    383  11.20    male -0.064103        1
484    384   9.80  female  0.049908        1

我知道如何添加散点图:bone1.plot.scatter(x='age',y=spnbmd'))

我需要帮助添加颜色


Tags: 数据dataframeage颜色绘制符号malefemale
2条回答

最好的方法是使用seaborn,使用色调参数作为性别

import seaborn as sns
sns.scatterplot(data=bone1, x='age', y='spnbmd', hue='gender')

或者,如果您不想使用seaborn,而只想使用dataframe plotting,则通过分别为阳性行和阴性行创建两个新dataframe来分别绘制这两个数据帧,并添加一个marker参数(您可以在此处从可能的标记中选择:https://matplotlib.org/api/markers_api.html

male_bone1 = bone1.loc[bone1['gender'] == 'Male'] #Selects male rows
female_bone1 = bone1.loc[bone1['gender'] == 'Female'] #Selects female 
male_bone1.plot.scatter(x = 'age', y = 'spnbmd', marker = 'x')
female_bone1.plot.scatter(x = 'age', y = 'spnbmd', marker = 'o')

您可以在bone1.plot.scatter()函数中引入参数“c”

差不多 bone1.plot.scatter(x, y, c=['green','yellow'])

“c”参数可以是单个字符串、如上所示的一系列颜色字符串,也可以是列名称或位置,其值将用于根据颜色映射为标记点着色

示例-

ax2 = df.plot.scatter(x='length',
                      y='width',
                      c='species',
                      colormap='viridis')

enter image description here

您可以在他们的documentation中找到更多信息

相关问题 更多 >

    热门问题