【问题标题】:Seaborn plots in a loopSeaborn 循环绘制
【发布时间】:2017-05-10 13:25:24
【问题描述】:

我正在使用 Spyder 并在循环中绘制 Seaborn 计数图。问题是情节似乎在同一个对象中彼此重叠,我最终只看到情节的最后一个实例。如何在我的控制台中查看每个情节在另一个下方?

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

【问题讨论】:

标签: python pandas matplotlib seaborn


【解决方案1】:

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

import matplotlib.pyplot as plt

df1 = df.select_dtypes([np.int, np.float])
for i, col in enumerate(df1.columns):
    plt.figure(i)
    sns.countplot(x=col, data=df1)

【讨论】:

  • 如果我想在一个图中绘制所有内容,而不是在另一个图中绘制,我该怎么做?
  • ``` fig,ax = subplots(n,1, figsize=(6,12), sharex=True) for i in range(n): sca(ax[i]) sns. countplot(x=col, data=df1) ``` 根据您的需要更改图形的大小。
  • 为什么你认为它更有效?选择 dtypes 时不创建数据框 df 的副本吗? OP 的代码没有这样做
【解决方案2】:

回答 cmets 中的问题:如何在单个图中绘制所有内容?我还展示了另一种在控制台中查看图表的替代方法。

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
  • 对于紧凑视图,将 xlabels 更改为 ylabel,如代码 sn-p 中所示

【讨论】:

  • sca 函数来自哪个库?
  • import matplotlib.pyplot as plt plt.sca(1)
  • sca >> 设置当前轴
【解决方案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);

【讨论】:

    猜你喜欢
    • 2021-02-20
    • 2020-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-11
    • 2016-05-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多