Seaborn中如何在多个子图中显示displot?

3
我打算将Seaborn的显示插入到不同的子图中。使用下面的代码,我想将Label1传递给ax1,将Label2传递给df2。然而,我收到了一个警告:UserWarning: displot是一个基于图形层的函数,不接受ax参数。你可能需要尝试histplot。warnings.warn(msg, UserWarning) 是否有解决这个问题的方法?我之前在使用hue参数方面遇到了histplot的问题。如果必要的话,我不太愿意使用它。
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

fig, (ax1, ax2) = plt.subplots(1,2, figsize = (12,6))

df = pd.DataFrame({      
    'Num' : [1,2,1,2,3,2,1,3,2,2,1,2,3,3,1,3],
    'Label1' : ['A','B','C','B','B','C','C','B','B','A','C','A','B','A','C','A'],  
    'Label2' : ['D','E','D','F','E','D','F','E','F','D','E','F','E','D','D','F'],   
    'Item' : ['Up','Left','Up','Left','Down','Right','Up','Down','Right','Down','Right','Up','Up','Right','Down','Left'],        
   })

ax1 = sns.displot(data = df, 
               x = 'Label1', 
               hue = 'Num',
               row = 'Item', 
               row_order = ['Up','Down','Left','Right'],
               shrink = 0.9, 
               discrete = True,
               aspect = 4, 
               height = 2,
               ax = ax1
               )

ax2 = sns.displot(data = df, 
               x = 'Label2', 
               hue = 'Num',
               row = 'Item', 
               row_order = ['Up','Down','Left','Right'],
               shrink = 0.9, 
               discrete = True,
               aspect = 4, 
               height = 2,
               ax = ax2
               )
1个回答

1
如果您想避免使用 histplot(),我认为您可以通过使用 displot() 并将数据进行 melt() 处理,然后使用 colLabel1Label2 放入两列中,这是最接近的方法。
sns.displot(
    data = df.melt(['Num', 'Item'], var_name='Group', value_name='Label'),
    y = 'Label',
    hue = 'Num',
    row = 'Item',
    col = 'Group',
    row_order = ['Up', 'Down', 'Left', 'Right'],
    shrink = 0.9,
    discrete = True,
    aspect = 4,
    height = 2,
)

displot with 2 cols


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接