分别绘制所有pandas数据框列

2024-04-27 00:41:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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 subblots=True来安排它们。下面的示例可以帮助我在(2,2)网格中获取四列的图形。但对于所有50列来说这是一个很长的方法

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

Tags: 数据truepandasdfplotvaluegroup数字
2条回答

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

enter image description here

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

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

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

enter image description here

如果通过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])

相关问题 更多 >