使用seaborn进行绘制时,如何为色调参数指定多个变量?

时间:2020-02-23 20:10:12

标签: pandas matplotlib data-visualization pandas-groupby seaborn

使用 seaborn 时,是否可以为 hue 参数包含多个变量(列)?提出此问题的另一种方式是,在将数据绘制到单个x,y轴图上之前,如何将它们按多个变量分组?

我想做下面的事情。但是,目前我无法为 hue 参数指定两个变量。

sns.relplot(x='#', y='Attack', hue=['Legendary', 'Stage'], data=df)

例如,假设我有一个如下所示的pandas DataFrame,其中包含一个通过Pokemon database教程获得的this

enter image description here

我想在x轴上绘制 pokedex#,在y轴上绘制 Attack 。但是,我想将数据按 Stage Legendary 进行分组。使用 matplotlib ,我编写了一个自定义函数,该函数按 ['Legendary','Stage'] 将数据框分组,然后遍历每个组进行绘图(请参见下面的结果) )。尽管我的自定义功能可以按预期工作,但我希望可以通过seaborn轻松实现。我猜想肯定还有其他人试图使用seaborn在单个图中可视化3个以上变量吗?

fig, ax = plt.subplots()
grouping_variables = ['Stage','Legendary']
group_1 = df.groupby(grouping_variables)
for group_1_label, group_1_df in group_1:
    ax.scatter(group_1_df['#'], group_1_df['Attack'], label=group_1_label)
ax_legend = ax.legend(title=grouping_variables)    

enter image description here

编辑1:

注意:在我提供的示例中,我按照两个变量(例如:Legendary和Stage)对数据进行了分组。但是,其他情况可能需要任意数量的变量(例如5个变量)。

2 个答案:

答案 0 :(得分:1)

在seaborn的scatterplot()中,您可以结合使用hue=style=参数来为每种组合生成不同的标记和不同的颜色

示例(从the documentation逐字记录):

tips = sns.load_dataset("tips")
ax = sns.scatterplot(x="total_bill", y="tip", data=tips)
ax = sns.scatterplot(x="total_bill", y="tip",
                     hue="day", style="time", data=tips)

enter image description here

答案 1 :(得分:0)

要使用GlobalGameMechanics中的 hue ,请考虑将所需的组连接到单个列中,然后在新变量上运行绘图:

seaborn.relplot

使用随机数据进行演示

数据

def run_plot(df, flds):
   # CREATE NEW COLUMN OF CONCATENATED VALUES
   df['_'.join(flds)] =  pd.Series(df.reindex(flds, axis='columns')
                                     .astype('str')
                                     .values.tolist()
                                  ).str.join('_')

   # PLOT WITH hue
   sns.relplot(x='#', y='Attack', hue='_'.join(flds), data=random_df, aspect=1.5)
   plt.show()

   plt.clf()
   plt.close()

import numpy as np
import pandas as pd

import matplotlib.pyplot as plt
import seaborn as sns

### DATA
np.random.seed(22320)
random_df = pd.DataFrame({'#': np.arange(1,501),
                          'Name': np.random.choice(['Bulbasaur', 'Ivysaur', 'Venusaur', 
                                                    'Charmander', 'Charmeleon'], 500),
                          'HP': np.random.randint(1, 100, 500),
                          'Attack': np.random.randint(1, 100, 500),
                          'Defense': np.random.randint(1, 100, 500),
                          'Sp. Atk': np.random.randint(1, 100, 500),
                          'Sp. Def': np.random.randint(1, 100, 500),
                          'Speed': np.random.randint(1, 100, 500),
                          'Stage': np.random.randint(1, 3, 500),
                          'Legend': np.random.choice([True, False], 500)
                          })

Two Group Plot Output

run_plot(random_df, ['Legend', 'Stage'])

Three Group Plot