Seaborn Plots in a Loop

Seaborn Scatter Plot multiple plots with loop

Most likely sns.scatterplot() will work. sns.pairplot will only work if you want all pairwise plots between your columns.

For example dataset is like this:

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

states = ['alabama','alaska','arizona']

df = pd.DataFrame(np.random.uniform(0,1,(20,6)),
columns = [i + "_" + j for i in states for j in ['cpm','spend']])
df.head()

alabama_cpm alabama_spend alaska_cpm alaska_spend arizona_cpm arizona_spend
0 0.444585 0.305385 0.113950 0.396746 0.450246 0.072074
1 0.028701 0.446495 0.527090 0.013968 0.367590 0.598380
2 0.726407 0.214152 0.220744 0.955635 0.337088 0.128571

Then using the code you have:

fig, ax = plt.subplots(3,1,figsize=(5,5))

for i,state in enumerate(states[0:3]):
state_cpm = state + "_" + "cpm"
state_spend = state + "_" + "spend"

sns.scatterplot(data=df, x=state_cpm, y=state_spend,ax=ax[i])

Sample Image

How to add legends to a plot i made using a for loop in seaborn?

How about putting label in sns:

df = sns.load_dataset('iris')

for i in df.columns[:4]:
sns.distplot(df[i], hist=False, label=i)

Output:

Sample Image

And without for loop:

df.iloc[:,:4].plot.kde()

Output:

Sample Image

Creating seaborn displot with loop

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



Related Topics



Leave a reply



Submit