How to plot a scatter FacetGrid from a dataframe with multi-level columns

Viewed 52
data = {('Weight', 'Additive', 'Water'): {0: 3, 1: 3, 2: 3, 3: 3, 4: 3},
        ('Weight', 'Additive', 'Grass'): {0: 6.0, 1: 7.0, 2: 6.0, 3: 0, 4: 0},
        ('Weight', 'Filler', 'Flowers'): {0: 1, 1: 2, 2: 3, 3: 4, 4: 5},
        ('Color', '', ''): {0: 15, 1: 18, 2: 21, 3: 35, 4: 40}}
combo = pd.DataFrame(data)

    Weight               Color
  Additive        Filler      
     Water Grass Flowers      
0        3   6.0       1    15
1        3   7.0       2    18
2        3   6.0       3    21
3        3   0.0       4    35
4        3   0.0       5    40

I have a MultiIndex level table in a pandas dataframe called 'combo' and am trying to make a FacetGrid scatterplot. When I try with the code below I get the error: 'Length of order must be same as number of levels (3), got 2'

grid = sns.FacetGrid(combo, col = combo['Weight'])
grid.map(sns.scatterplot, combo['Weight'], combo['Color'])
plt.show()
1 Answers
import seaborn as sns
import pandas as pd

# sample data
data = {('Weight', 'Additive', 'Water'): {0: 3, 1: 3, 2: 3, 3: 3, 4: 3},
        ('Weight', 'Additive', 'Grass'): {0: 6.0, 1: 7.0, 2: 6.0, 3: 0, 4: 0},
        ('Weight', 'Filler', 'Flowers'): {0: 1, 1: 2, 2: 3, 3: 4, 4: 5},
        ('Color', '', ''): {0: 15, 1: 18, 2: 21, 3: 35, 4: 40}}
df = pd.DataFrame(data)

# flatten the column titles and remove two spaces from the 'Color  ' column name
df.columns = df.columns.to_flat_index().str.join(' ').str.replace('  ', '')

# convert the df to a long format to use with seaborn
dfm = df.melt('Color', var_name='Substance', value_name='Weight')

# clean the column values in the Substance column
dfm.Substance = dfm.Substance.str.replace('Weight ', '').str.replace('_', ' ')

# display(dfm)
    Color       Substance  Weight
0      15  Additive Water     3.0
1      18  Additive Water     3.0
2      21  Additive Water     3.0
3      35  Additive Water     3.0
4      40  Additive Water     3.0
5      15  Additive Grass     6.0
6      18  Additive Grass     7.0
7      21  Additive Grass     6.0
8      35  Additive Grass     0.0
9      40  Additive Grass     0.0
10     15  Filler Flowers     1.0
11     18  Filler Flowers     2.0
12     21  Filler Flowers     3.0
13     35  Filler Flowers     4.0
14     40  Filler Flowers     5.0

plot using hue

g = sns.relplot(kind='scatter', data=dfm, x='Weight', y='Color', hue='Substance')

enter image description here

plot using col

g = sns.relplot(kind='scatter', data=dfm, x='Weight', y='Color', col='Substance')

enter image description here

Related