0

我目前正在尝试开发一个便利功能,它应该为 pandas 数据框中的每一列创建一个基本图,其中包含数据框中所有列的数据集中的值及其数量。

def plot_value_counts(df, leave_out):
  # is supposed to create the subplots grid where I can add the plots
  fig, axs = plt.subplots(int(len(df)/2) + 1,int(len(df)/2) + 1)
  for idx, name in enumerate(list(df)):
    if name == leave_out:
      continue
    else:
      axs[idx] = df[name].value_counts().plot(kind="bar")
  return fig, axs

这个片段永远运行,永远不会停止。我尝试查看有关 stackoverflow 的其他类似问题,但找不到任何特定于我的案例的内容。

subplots 函数的使用来自以下问题:Masplotlib 中是否可以自动生成多个子图?

下面是数据文件的一个简短示例,以便大家理解问题: https ://gist.github.com/hentschelpatrick/e0a7e1400a4b5c356ec8b0e4952f8cc1#file-train-csv

4

2 回答 2

1

axis您可以在绘图方法docs中传递对象。你应该迭代列:

fig, axs = plt.subplots(int(len(df)/2) + 1,int(len(df)/2) + 1)
for idx, name in enumerate(df.columns):
    if name == leave_out:
        continue
    else:
        df[name].value_counts().plot(kind="bar", ax=axs[idx])

编辑:如果您有内存问题(似乎没有运行),请先尝试不使用子图和show每个图:

for idx, name in enumerate(df.columns):
    if name == leave_out:
        continue
    else:
        df[name].value_counts().plot(kind="bar")
        plt.show()
于 2019-02-15T12:01:19.230 回答
1

这是我为我的项目编写的一个函数,用于绘制熊猫数据框中的所有列。它将生成一个大小为 nx4 的网格并绘制所有列

def plotAllFeatures(dfData):
    plt.figure(1, figsize=(20,50))
    pos=1
    for feature in dfData.columns:
        plt.subplot(np.ceil(len(dfData.columns)/4),4,pos)
        dfData[feature].plot(title=feature)
        pos=pos+1
    plt.show()
于 2019-02-15T17:11:25.357 回答