【问题标题】:How to assign colors to a scatter plot based on values in a dataframe如何根据数据框中的值将颜色分配给散点图
【发布时间】:2021-01-18 16:34:21
【问题描述】:

使用 thebones1 DataFrame,绘制 spnbmd 与年龄的散点图。男性和女性点应该有不同的颜色或符号。

到目前为止,我已经创建了数据框 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')

我需要帮助添加颜色

【问题讨论】:

    标签: python dataframe colors scatter-plot


    【解决方案1】:

    您可以在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')
    

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

    【讨论】:

      【解决方案2】:

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

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

      或者,如果您不想使用 seaborn 而只使用数据框绘图,则通过分别为男性和女性行创建两个新数据框来分别绘制两者,并添加一个标记参数(您可以在此处选择可能的标记: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')
      

      【讨论】:

        猜你喜欢
        • 2021-02-15
        • 1970-01-01
        • 2017-09-14
        • 1970-01-01
        • 1970-01-01
        • 2022-06-10
        • 2013-10-08
        • 2015-04-07
        • 1970-01-01
        相关资源
        最近更新 更多