Home > Software design >  How to plot a scatter FacetGrid from a dataframe with multi-level columns
How to plot a scatter FacetGrid from a dataframe with multi-level columns

Time:07-12

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()

CodePudding user response:

  • Tested in python 3.10, pandas 1.4.2, matplotlib 3.5.1, seaborn 0.11.2
  • It is not recommended to directly use 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