【问题标题】:matplotlib multiple plots with pandasmatplotlib 带有熊猫的多个绘图
【发布时间】:2019-02-15 11:33:17
【问题描述】:

我目前正在尝试开发一个便利功能,它应该为 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

这个 sn-p 永远运行,永不停止。 我尝试查看有关 stackoverflow 的其他类似问题,但找不到任何针对我的案例的具体问题。

subplots函数的用法来自以下问题:Is it possible to automatically generate multiple subplots in matplotlib?

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

【问题讨论】:

  • 您能否提供一个(简短的!)输入示例,该过程为您挂起?
  • @ason​​gtoruin 我用一些数据添加了一个指向要点的链接。

标签: python pandas matplotlib


【解决方案1】:

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

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

【讨论】:

  • 它仍然无限期运行
  • 该方法有效,但显然它不喜欢 100 个子图。尝试使用plt.show() 传递单个轴/图形(请参阅编辑)
  • 我已经找到了内存不足的原因,即使只有 6 列。其中 2 个是数值,它们没有被分箱,导致绘图极度过载。谢谢!
【解决方案2】:

这是我为我的项目编写的一个函数,用于绘制 pandas 数据框中的所有列。它将生成一个大小为 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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-13
    • 2017-04-01
    • 2020-02-11
    • 1970-01-01
    • 2020-08-31
    • 1970-01-01
    相关资源
    最近更新 更多