在 sns histplot 上设置顺序

JPA*_*888 13 python pandas seaborn

我正在尝试使用seaborn 设置堆叠的顺序histplot。下面的情节很好,但我希望改变顺序,以便Up, Down, Left, Right从左到右阅读时可以读取。

尝试通过order或时出现错误col_order。

raise AttributeError('{!r} object has no property {!r}'

AttributeError: 'Rectangle' object has no property 'order'
Run Code Online (Sandbox Code Playgroud)

不过,在未传递订单时它工作正常。

import pandas as pd
import seaborn as sns

df = pd.DataFrame({      
    'Label' : ['A','B','C','B','B','C','C','B','B','A','C','A','B','A','C','A'],   
    'Item' : ['Up','Left','Up','Left','Down','Right','Up','Down','Right','Down','Right','Up','Up','Right','Down','Left'],        
   })

g = sns.histplot(data = df, 
            x = 'Item', 
            hue = 'Label',
            #order = ['Up','Down','Left','Right'],
            multiple = 'fill', 
            shrink = 0.8, 
            discrete = True,
            legend = True,
            )
Run Code Online (Sandbox Code Playgroud)

dat*_*sta 20

您不能从内部订购seaborn。pandas不过你可以从那里订购。要为字符串提供自定义排序顺序,您可以将Item列转换为Categorical,并在第二个参数中指定顺序。

之后,您将得到按照您想要的顺序排列的图:

df['Item'] = pd.Categorical(df['Item'], ['Up','Down','Left','Right'])
Run Code Online (Sandbox Code Playgroud)

完整代码:

import pandas as pd
import seaborn as sns

df = pd.DataFrame({      
    'Label' : ['A','B','C','B','B','C','C','B','B','A','C','A','B','A','C','A'],   
    'Item' : ['Up','Left','Up','Left','Down','Right','Up','Down','Right','Down','Right','Up','Up','Right','Down','Left'],        
   })


df['Item'] = pd.Categorical(df['Item'], ['Up','Down','Left','Right'])

g = sns.histplot(data = df, 
            x = 'Item', 
            hue = 'Label',
            #order = ['Up','Down','Left','Right'],
            multiple = 'fill', 
            shrink = 0.8, 
            discrete = True,
            legend = True,
            )
Run Code Online (Sandbox Code Playgroud)