Pandas 使用seaborn打印时,如何为色调参数指定多个变量?

Pandas 使用seaborn打印时,如何为色调参数指定多个变量?,pandas,matplotlib,data-visualization,pandas-groupby,seaborn,Pandas,Matplotlib,Data Visualization,Pandas Groupby,Seaborn,使用seaborn时,有没有一种方法可以为色调参数包含多个变量(列)?问这个问题的另一种方式是,在将数据绘制在单个x、y轴绘图上之前,如何将数据按多个变量分组 我想做下面这样的事情。但是,目前我无法为色调参数指定两个变量: sns.relplot(x='#', y='Attack', hue=['Legendary', 'Stage'], data=df) 例如,假设我有一个如下所示的熊猫数据帧,其中包含一个通过教程获得的a 我想在x轴上绘制pokedex#,在y轴上绘制攻击。然而,我希望数

使用seaborn时,有没有一种方法可以为色调参数包含多个变量(列)?问这个问题的另一种方式是,在将数据绘制在单个x、y轴绘图上之前,如何将数据按多个变量分组

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

sns.relplot(x='#', y='Attack', hue=['Legendary', 'Stage'], data=df)
例如,假设我有一个如下所示的熊猫数据帧,其中包含一个通过教程获得的a

我想在x轴上绘制pokedex#,在y轴上绘制攻击。然而,我希望数据按阶段和阶段进行分组。使用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)    

编辑1:


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

在seaborn的
散点图()
中,您可以组合
色调=
样式=
参数,为每个组合生成不同的标记和不同的颜色

示例(逐字摘自):

< P>使用<代码> Seabn .RelPoxs/Cort>,将需要的组连接到一个列中,然后在新变量上运行图:

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)
                          })
绘图

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

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