【问题标题】:loop through dataframe column and plot all variable?循环遍历数据框列并绘制所有变量?
【发布时间】:2019-11-05 09:06:43
【问题描述】:

我有一个包含 35 个变量的列表,并且想要绘制所有变量的直方图以查看分布类型。

fig, axs = plt.subplots(6, 6)
for i in range(6):
    for j in range(6):
        for column in X.columns:
            axs[i,j] = sns.distplot(X[column], hist=True, kde=True, 
               bins=int(180/5), color = 'darkblue', 
               hist_kws={'edgecolor':'black'},
               kde_kws={'linewidth': 4})
            axs[i,j].set_title(column)

目前它只打印最后 35 个变量。

【问题讨论】:

  • 你想在 36 个图中绘制所有变量吗?
  • 是的,所有 36 个变量的绘图

标签: python pandas for-loop


【解决方案1】:

这个小改动应该可以解决问题:

fig, axs = plt.subplots(6, 6)
for i in range(6):
    for j in range(6):
        if (i*6) + j > 33:
            break
        curr_column = X.columns[(i*6) + j]
        sns.distplot(X[curr_column], hist=True, kde=True,
                     ax=axs[i,j], 
                     bins=int(180/5), color = 'darkblue', 
                     hist_kws={'edgecolor':'black'},
                     kde_kws={'linewidth': 4})
        axs[i,j].set_title(curr_column)

【讨论】:

  • 我得到这个错误索引 34 is out of bounds for axis 0 with size 34
  • 听起来您没有 36 列。检查X.shape。是否有可能您要绘制的变量之一设置为数据框的索引?
  • 哦,对不起,它是 34
  • @DineshKumar:编辑代码使其在 34 列(即索引 33)后停止绘图:
  • 它仍在绘制最后一列
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-18
  • 1970-01-01
  • 2021-05-06
  • 2017-03-09
  • 2017-10-02
相关资源
最近更新 更多