【问题标题】:Create for loop to plot histograms for individual columns of DataFrame with Seaborn使用 Seaborn 创建 for 循环以绘制 DataFrame 的各个列的直方图
【发布时间】:2018-06-09 11:38:03
【问题描述】:

所以我正在尝试使用 for 循环为我的 DatFrame 中的所有连续变量绘制直方图

df1 = df.select_dtypes([np.object])

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

我在这里通过搜索找到的。

但是现在我想对 distplot 做同样的事情,所以我尝试将上面的代码修改为:

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

for i, col in enumerate(df1.columns):
    plt.figure(i)
    sns.distplot(df1)

但它只是给了我一个空的情节。关于我能做什么的任何想法?

编辑:例如DataFrame:

dftest = pd.DataFrame(np.random.randint(low=0, high=10, size=(5, 5)),
                    columns=['a', 'b', 'c', 'd', 'e']) 

【问题讨论】:

标签: python pandas plot seaborn


【解决方案1】:

您似乎想为数据框的每列生成一个带有distplot 的图形。因此,您需要为每个特定图形指定正在使用的数据。

正如seaborn documentation 所说的distplot(a, ...)

a:系列、一维数组或列表。观察到的数据。

所以在这种情况下:

for i, col in enumerate(df1.columns):
    plt.figure(i)
    sns.distplot(df1[col])

【讨论】:

  • 多么简单的解决方法!非常感谢!现在我只需要弄清楚如何处理我的缺失值并绘制所有内容!万事如意!
  • 如何在一个大图中实现它并在其中包含多个小图表? @mportanceOfBeingErnest
【解决方案2】:

定义一个函数来绘制直方图

def histograms_plot(dataframe, features, rows, cols):

fig=plt.figure(figsize=(20,20))
for i, feature in enumerate(features):
    ax=fig.add_subplot(rows,cols,i+1)
    dataframe[feature].hist(bins=20,ax=ax,facecolor='green')
    ax.set_title(feature+" Distribution",color='red')

fig.tight_layout()  
plt.show()

histograms_plot(df,df.columns,6,3)

【讨论】:

  • 谢谢。如何缩放子图以使 x 轴相同?
猜你喜欢
  • 2020-07-21
  • 1970-01-01
  • 2019-04-09
  • 2022-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-11
相关资源
最近更新 更多