eh329
eh329

Reputation: 104

Creating seaborn displot with loop

What i would like to do is creating displots in a way that each pair of two occupies a row. So, i used these lines of codes:

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)

However, the result is a runtime error and strange shaped plots. The result

Does anyone know what i am doing wrong? Thanks

Upvotes: 0

Views: 692

Answers (1)

JohanC
JohanC

Reputation: 80279

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 dataframe.

Here is some example code showing the general idea:

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

sns.displot using long data

Upvotes: 1

Related Questions