分别绘制所有 pandas 数据框列

Plot all pandas dataframe columns separately

我有一个 pandas 数据框,它只有数字列,我正在尝试为所有特征创建一个单独的直方图

ind group people value value_50
 1      1    5    100    1
 1      2    2    90     1
 2      1    10   80     1
 2      2    20   40     0
 3      1    7    10     0
 3      2    23   30     0

但在我的现实生活中有 50 多列,我如何为所有这些创建一个单独的图

我试过了

df.plot.hist( subplots = True, grid = True)

它给了我一个重叠的不清晰的情节。

如何使用 pandas subplots = True 来安排它们。下面的示例可以帮助我在 (2,2) 网格中获取四列的图形。但对于所有 50 列来说,这是一个很长的方法

fig, [(ax1,ax2),(ax3,ax4)]  = plt.subplots(2,2, figsize = (20,10))

Pandas subplots=True 将轴排列在一列中。

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame(np.random.rand(7,20))

df.plot(subplots=True)

plt.tight_layout()
plt.show()

这里没有应用tight_layout,因为图形太小,无法很好地排列坐标轴。不过可以使用更大的数字 (figsize=(...))。

为了让轴在网格上,可以使用 layout 参数,例如

df.plot(subplots=True, layout=(4,5))

如果通过 plt.subplots()

创建轴,也可以实现同样的效果
fig, axes = plt.subplots(nrows=4, ncols=5)
df.plot(subplots=True, ax=axes)

如果你想单独绘制它们(这就是我在这里结束的原因),你可以使用

for i in df.columns:
    plt.figure()
    plt.hist(df[i])

此任务的替代方法是使用具有超参数 "layout" 的 "hist" 方法。使用@ImportanceOfBeingErnest 提供的部分代码的示例:

import numpy as np
import matplotlib.pyplot as plt
import pandas  as pd

df = pd.DataFrame(np.random.rand(7,20))

df.hist(layout=(5,4), figsize=(15,10))

plt.show()

虽然问题中没有要求,但我想我会补充一点,使用 x 参数进行绘图将允许您为 x 轴数据指定一列。

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame(np.random.rand(7,20),columns=list('abcdefghijklmnopqrst'))
df.plot(x='a',subplots=True, layout=(4,5))    

plt.tight_layout()
plt.show()

https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.plot.html

使用pandas.DataFrame I would suggest using pandas.DataFrame.apply。使用自定义函数,在此示例中 plot(),您可以单独打印和保存每个图形。

def plot(col):
 
    fig, ax = plt.subplots()
    ax.plot(col)
    plt.show()

df.apply(plot)