简体   繁体   中英

Python: dynamically produce seaborn plots then display results side-by-side?

I'm trying to produce multiple seaborn kernel density plots for the numeric variables of my Pandas DataFrame. I have the names of all of my numeric columns in a list, numberCol . Presently, I can make a kdeplot for each variable that I explicitly name, like so:

import seaborn as sbn
sbn.set_style('whitegrid')
sbn.kdeplot(np.array(df.v2), bw=0.5) # for pandas.core.frame.DataFrame input

Is there a better way to iterate through the numberCol list, produce an sbn.kdeplot for each variable in numberCol , then display them side-by-side with something smarter than something like:

import matplotlib.pyplot as plt
import seaborn as sns

# Here we create a figure instance, and two subplots
fig = plt.figure(figsize = (20,20)) # width x height
ax1 = fig.add_subplot(3, 3, 1) # row, column, position
ax2 = fig.add_subplot(3, 3, 2)
ax3 = fig.add_subplot(3, 3, 3)

# We use ax parameter to tell seaborn which subplot to use for this plot
sns.heatmap(data=subset1.corr(), ax=ax1, cmap = cmap, square=True, cbar_kws={'shrink': .3}, annot=True, annot_kws={'fontsize': 12})
sns.heatmap(data=subset2.corr(), ax=ax2, cmap = cmap, square=True, cbar_kws={'shrink': .3}, annot=True, annot_kws={'fontsize': 12})
sns.heatmap(data=subset3.corr(), ax=ax3, cmap = cmap, square=True, cbar_kws={'shrink': .3}, annot=True, annot_kws={'fontsize': 12})

If I understand your question, this should do the trick

Ncols = 9
cols = ['col_{:d}'.format(i) for i in range(Ncols)]
df = pd.DataFrame(np.random.random(size=(1000,Ncols)),columns=cols)

fig, axs = plt.subplots(3,3) # adjust the geometry based on your number of columns to plot
for ax,col in zip(axs.flatten(), cols):
    sns.kdeplot(df[col], ax=ax)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM