使用循环创建 seaborn displot

Creating seaborn displot with loop

我想做的是以每对两个占据一行的方式创建displots。所以,我使用了这些代码行:

columns = list(cols) # cols created from dataframe.columns
sns.set(rc = {"figure.figsize": (12, 15)})
sns.set_style(style = "white")

for i in range(len(columns)):
    plt.subplot(10, 2, i + 1)
    sns.displot(data[columns[i]], rug = True)

但是,结果是运行时错误和形状奇怪的图。 The result

有谁知道我做错了什么? 谢谢

sns.displot is a figure-level function and always creates its own new figure. To get what you want, you could create a long-form 数据框。

下面是一些示例代码,展示了总体思路:

from matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

data = pd.DataFrame(data=np.random.rand(30, 20), columns=[*'abcdefghijklmnopqrst'])
cols = data.columns
data_long = data.melt(value_vars=cols)
g = sns.displot(data_long, x='value', col='variable', col_wrap=2, height=2)
g.fig.subplots_adjust(top=0.97, bottom=0.07, left=0.07, hspace=0.5)
plt.show()