Python Seaborn 在循环中绘制
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41325160/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Seaborn plots in a loop
提问by Tronald Dump
I am using Spyder and plotting Seaborn countplots in a loop. The problem is that the plots seem to be happening on top of each other in the same object and I end up seeing only the last instance of the plot. How can I view each plot in my console one below the other?
我正在使用 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')
回答by Ted Petrou
You can create a new figure each loop or possibly plot on a different axis. Here is code that creates the new figure each loop. It also grabs the int and float columns more efficiently.
您可以在每个循环中创建一个新图形,也可以在不同的轴上绘制。这是在每个循环中创建新图形的代码。它还可以更有效地获取 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)
回答by jorgeh
Before calling sns.countplot
you need to create a new figure.
在调用之前,sns.countplot
您需要创建一个新图形。
Assuming you have imported import matplotlib.pyplot as plt
you can simply add plt.figure()
right before sns.countplot(...)
假设您已经导入,import matplotlib.pyplot as plt
您可以简单地在plt.figure()
之前添加sns.countplot(...)
For example:
例如:
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);
回答by sherdim
To answer on the question in comments: How to plot everything in the single figure? I also show an alternative method to view plots in a console one below the other.
回答评论中的问题:如何在单个图中绘制所有内容?我还展示了另一种在控制台中查看绘图的方法。
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);
Notes:
笔记:
- if a range of values in your columns differs - set sharex=False or remove it
- no need for titles: seaborn automatically inserts column names as xlabel
- for compact view change xlabels to ylabel as in the code snippet
- 如果列中的值范围不同 - 设置 sharex=False 或将其删除
- 无需标题:seaborn 自动将列名插入为 xlabel
- 对于紧凑视图,如代码片段中那样将 xlabels 更改为 ylabel