海伯恩圈地

2024-05-19 12:06:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我在用Spyder循环绘制Seaborn countplots。问题是,这些情节似乎是在同一个对象中彼此重叠,而我最终只看到情节的最后一个实例。如何在控制台中逐个查看每个绘图?

for col in df.columns:
   if  ((df[col].dtype == np.float64) | (df[col].dtype == np.int64)):
       i=0
       #Later
   else :
       print(col +' count plot \n') 
       sns.countplot(x =col, data =df)
       sns.plt.title(col +' count plot')        

Tags: 对象实例绘图dfplotcountnp绘制
3条回答

在调用sns.countplot之前,需要创建一个新的图形。

假设您已经导入了import matplotlib.pyplot as plt,您只需在sns.countplot(...)之前添加plt.figure()

例如:

import matplotlib
import matplotlib.pyplot as plt
import seaborn

for x in some_list:
    df = create_df_with(x)
    plt.figure() #this creates a new figure on which your plot will appear
    seaborn.countplot(use_df);

可以为每个循环创建一个新图形,也可以在不同的轴上绘制。下面是创建每个循环的新图形的代码。它还可以更有效地获取int和float列。

df1 = df.select_dtypes([np.int, np.float])

for i, col in enumerate(df1.columns):
    plt.figure(i)
    sns.countplot(x=col, data=df1)

在评论中回答这个问题:如何把所有的东西都画成一个图形?我还展示了另一种在控制台中查看绘图的方法。

import matplotlib.pyplot as plt

df1 = df.select_dtypes([np.int, np.float])

n=len(df1.columns)
fig,ax = plt.subplots(n,1, figsize=(6,n*2), sharex=True)
for i in range(n):
    plt.sca(ax[i])
    col = df1.columns[i]
    sns.countplot(df1[col].values)
    ylabel(col);

注:

  • 如果列中的值范围不同-设置sharex=False或将其删除
  • 不需要标题:seaborn自动将列名插入为xlabel
  • 对于压缩视图,将xlabel更改为ylabel,如代码段中所示

相关问题 更多 >

    热门问题